linera-core 0.15.17

The core Linera protocol, including client and server logic, node synchronization, etc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
// Copyright (c) Facebook, Inc. and its affiliates.
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
    collections::{BTreeMap, BTreeSet, HashMap, VecDeque},
    sync::{Arc, Mutex, RwLock},
    time::Duration,
};

use futures::{
    future::{Either, Shared},
    FutureExt as _,
};
use linera_base::{
    crypto::{CryptoError, CryptoHash, ValidatorPublicKey},
    data_types::{
        ApplicationDescription, ArithmeticError, Blob, BlockHeight, Epoch, Round, TimeDelta,
        Timestamp,
    },
    doc_scalar,
    hashed::Hashed,
    identifiers::{AccountOwner, ApplicationId, BlobId, ChainId, EventId, StreamId},
};
use linera_cache::{UniqueValueCache, ValueCache, DEFAULT_CLEANUP_INTERVAL_SECS};
#[cfg(with_testing)]
use linera_chain::ChainExecutionContext;
use linera_chain::{
    data_types::{BlockProposal, BundleExecutionPolicy, MessageBundle, ProposedBlock},
    types::{
        Block, CertificateValue, ConfirmedBlock, ConfirmedBlockCertificate, GenericCertificate,
        LiteCertificate, Timeout, TimeoutCertificate, ValidatedBlock, ValidatedBlockCertificate,
    },
    ChainError, ChainStateView,
};
use linera_execution::{ExecutionError, ExecutionStateView, Query, QueryOutcome, ResourceTracker};
use linera_storage::{Clock as _, Storage};
use linera_views::{context::InactiveContext, ViewError};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::sync::{oneshot, OwnedRwLockReadGuard};
use tracing::{instrument, trace, warn};

/// A read guard providing access to a chain's [`ChainStateView`].
///
/// Holds a read lock on the chain worker state, preventing writes for its
/// lifetime. The `OwnedRwLockReadGuard` internally holds a strong `Arc`
/// reference to the `RwLock<ChainWorkerState>`, keeping the state alive.
/// Dereferences to `ChainStateView`.
pub struct ChainStateViewReadGuard<S: Storage>(
    OwnedRwLockReadGuard<ChainWorkerState<S>, ChainStateView<S::Context>>,
);

impl<S: Storage> std::ops::Deref for ChainStateViewReadGuard<S> {
    type Target = ChainStateView<S::Context>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Re-export of [`EventSubscriptionsResult`] for use by other crate modules.
pub(crate) use crate::chain_worker::EventSubscriptionsResult;
use crate::{
    chain_worker::{
        handle, state::ChainWorkerState, BlockOutcome, ChainWorkerConfig, CrossChainUpdateResult,
        DeliveryNotifier,
    },
    client::ListeningMode,
    data_types::{ChainInfoQuery, ChainInfoResponse, CrossChainRequest},
    notifier::Notifier,
};

#[cfg(test)]
#[path = "unit_tests/worker_tests.rs"]
mod worker_tests;

/// Wraps a future in `SyncFuture` on non-web targets so that it satisfies `Sync` bounds.
/// On web targets the future is returned as-is.
#[cfg(not(web))]
pub(crate) fn wrap_future<F: std::future::Future>(f: F) -> sync_wrapper::SyncFuture<F> {
    sync_wrapper::SyncFuture::new(f)
}

/// Wraps a future in `SyncFuture` on non-web targets so that it satisfies `Sync` bounds.
/// On web targets the future is returned as-is.
#[cfg(web)]
pub(crate) fn wrap_future<F: std::future::Future>(f: F) -> F {
    f
}

pub const DEFAULT_BLOCK_CACHE_SIZE: usize = 5_000;
pub const DEFAULT_EXECUTION_STATE_CACHE_SIZE: usize = 10_000;

#[cfg(with_metrics)]
mod metrics {
    use std::sync::LazyLock;

    use linera_base::prometheus_util::{
        exponential_bucket_interval, register_histogram, register_histogram_vec,
        register_int_counter, register_int_counter_vec,
    };
    use linera_chain::{data_types::MessageAction, types::ConfirmedBlockCertificate};
    use prometheus::{Histogram, HistogramVec, IntCounter, IntCounterVec};

    pub static NUM_ROUNDS_IN_CERTIFICATE: LazyLock<HistogramVec> = LazyLock::new(|| {
        register_histogram_vec(
            "num_rounds_in_certificate",
            "Number of rounds in certificate",
            &["certificate_value", "round_type"],
            exponential_bucket_interval(0.1, 50.0),
        )
    });

    pub static NUM_ROUNDS_IN_BLOCK_PROPOSAL: LazyLock<HistogramVec> = LazyLock::new(|| {
        register_histogram_vec(
            "num_rounds_in_block_proposal",
            "Number of rounds in block proposal",
            &["round_type"],
            exponential_bucket_interval(0.1, 50.0),
        )
    });

    pub static TRANSACTION_COUNT: LazyLock<IntCounterVec> =
        LazyLock::new(|| register_int_counter_vec("transaction_count", "Transaction count", &[]));

    pub static INCOMING_BUNDLE_COUNT: LazyLock<IntCounter> =
        LazyLock::new(|| register_int_counter("incoming_bundle_count", "Incoming bundle count"));

    pub static REJECTED_BUNDLE_COUNT: LazyLock<IntCounter> =
        LazyLock::new(|| register_int_counter("rejected_bundle_count", "Rejected bundle count"));

    pub static INCOMING_MESSAGE_COUNT: LazyLock<IntCounter> =
        LazyLock::new(|| register_int_counter("incoming_message_count", "Incoming message count"));

    pub static OPERATION_COUNT: LazyLock<IntCounter> =
        LazyLock::new(|| register_int_counter("operation_count", "Operation count"));

    pub static OPERATIONS_PER_BLOCK: LazyLock<Histogram> = LazyLock::new(|| {
        register_histogram(
            "operations_per_block",
            "Number of operations per block",
            exponential_bucket_interval(1.0, 10000.0),
        )
    });

    pub static INCOMING_BUNDLES_PER_BLOCK: LazyLock<Histogram> = LazyLock::new(|| {
        register_histogram(
            "incoming_bundles_per_block",
            "Number of incoming bundles per block",
            exponential_bucket_interval(1.0, 10000.0),
        )
    });

    pub static TRANSACTIONS_PER_BLOCK: LazyLock<Histogram> = LazyLock::new(|| {
        register_histogram(
            "transactions_per_block",
            "Number of transactions per block",
            exponential_bucket_interval(1.0, 10000.0),
        )
    });

    pub static NUM_BLOCKS: LazyLock<IntCounterVec> = LazyLock::new(|| {
        register_int_counter_vec("num_blocks", "Number of blocks added to chains", &[])
    });

    pub static CERTIFICATES_SIGNED: LazyLock<IntCounterVec> = LazyLock::new(|| {
        register_int_counter_vec(
            "certificates_signed",
            "Number of confirmed block certificates signed by each validator",
            &["validator_name"],
        )
    });

    pub static PREVIOUS_EVENT_BLOCKS_STREAM_COUNT: LazyLock<Histogram> = LazyLock::new(|| {
        register_histogram(
            "previous_event_blocks_stream_count",
            "Number of event streams requested per PreviousEventBlocks query",
            exponential_bucket_interval(1.0, 10000.0),
        )
    });

    pub static CHAIN_INFO_QUERIES: LazyLock<IntCounter> = LazyLock::new(|| {
        register_int_counter(
            "chain_info_queries",
            "Number of chain info queries processed",
        )
    });

    /// Holds metrics data extracted from a confirmed block certificate.
    pub struct MetricsData {
        certificate_log_str: &'static str,
        round_type: &'static str,
        round_number: u32,
        confirmed_transactions: u64,
        confirmed_incoming_bundles: u64,
        confirmed_rejected_bundles: u64,
        confirmed_incoming_messages: u64,
        confirmed_operations: u64,
        validators_with_signatures: Vec<String>,
    }

    impl MetricsData {
        /// Creates a new `MetricsData` by extracting data from the certificate.
        pub fn new(certificate: &ConfirmedBlockCertificate) -> Self {
            Self {
                certificate_log_str: certificate.inner().to_log_str(),
                round_type: certificate.round.type_name(),
                round_number: certificate.round.number(),
                confirmed_transactions: certificate.block().body.transactions.len() as u64,
                confirmed_incoming_bundles: certificate.block().body.incoming_bundles().count()
                    as u64,
                confirmed_rejected_bundles: certificate
                    .block()
                    .body
                    .incoming_bundles()
                    .filter(|b| b.action == MessageAction::Reject)
                    .count() as u64,
                confirmed_incoming_messages: certificate
                    .block()
                    .body
                    .incoming_bundles()
                    .map(|b| b.messages().count())
                    .sum::<usize>() as u64,
                confirmed_operations: certificate.block().body.operations().count() as u64,
                validators_with_signatures: certificate
                    .signatures()
                    .iter()
                    .map(|(validator_name, _)| validator_name.to_string())
                    .collect(),
            }
        }

        /// Records the metrics for a processed block.
        pub fn record(self) {
            NUM_BLOCKS.with_label_values(&[]).inc();
            NUM_ROUNDS_IN_CERTIFICATE
                .with_label_values(&[self.certificate_log_str, self.round_type])
                .observe(self.round_number as f64);
            TRANSACTIONS_PER_BLOCK.observe(self.confirmed_transactions as f64);
            INCOMING_BUNDLES_PER_BLOCK.observe(self.confirmed_incoming_bundles as f64);
            OPERATIONS_PER_BLOCK.observe(self.confirmed_operations as f64);
            if self.confirmed_transactions > 0 {
                TRANSACTION_COUNT
                    .with_label_values(&[])
                    .inc_by(self.confirmed_transactions);
                if self.confirmed_incoming_bundles > 0 {
                    INCOMING_BUNDLE_COUNT.inc_by(self.confirmed_incoming_bundles);
                }
                if self.confirmed_rejected_bundles > 0 {
                    REJECTED_BUNDLE_COUNT.inc_by(self.confirmed_rejected_bundles);
                }
                if self.confirmed_incoming_messages > 0 {
                    INCOMING_MESSAGE_COUNT.inc_by(self.confirmed_incoming_messages);
                }
                if self.confirmed_operations > 0 {
                    OPERATION_COUNT.inc_by(self.confirmed_operations);
                }
            }

            for validator_name in self.validators_with_signatures {
                CERTIFICATES_SIGNED
                    .with_label_values(&[&validator_name])
                    .inc();
            }
        }
    }
}

/// Instruct the networking layer to send cross-chain requests and/or push notifications.
#[derive(Default, Debug)]
pub struct NetworkActions {
    /// The cross-chain requests
    pub cross_chain_requests: Vec<CrossChainRequest>,
    /// The push notifications.
    pub notifications: Vec<Notification>,
}

impl NetworkActions {
    pub fn extend(&mut self, other: NetworkActions) {
        self.cross_chain_requests.extend(other.cross_chain_requests);
        self.notifications.extend(other.notifications);
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// Notification that a chain has a new certified block or a new message.
pub struct Notification {
    pub chain_id: ChainId,
    pub reason: Reason,
}

doc_scalar!(
    Notification,
    "Notify that a chain has a new certified block or a new message"
);

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// Reason for the notification.
pub enum Reason {
    NewBlock {
        height: BlockHeight,
        hash: CryptoHash,
        event_streams: BTreeSet<StreamId>,
    },
    NewIncomingBundle {
        origin: ChainId,
        height: BlockHeight,
    },
    NewRound {
        height: BlockHeight,
        round: Round,
    },
    BlockExecuted {
        height: BlockHeight,
        hash: CryptoHash,
    },
    // NOTE: Keep this at the end for backward compatibility with old validators
    // that use bincode integer-based variant indices. Old validators don't emit
    // NewEvents, and inserting it before existing variants would shift their indices.
    NewEvents {
        height: BlockHeight,
        hash: CryptoHash,
        event_streams: BTreeSet<StreamId>,
    },
}

/// Error type for worker operations.
#[derive(Debug, Error, strum::IntoStaticStr)]
pub enum WorkerError {
    #[error(transparent)]
    CryptoError(#[from] CryptoError),

    #[error(transparent)]
    ArithmeticError(#[from] ArithmeticError),

    #[error(transparent)]
    ViewError(#[from] ViewError),

    #[error("Certificates are in confirmed_log but not in storage: {0:?}")]
    ReadCertificatesError(Vec<CryptoHash>),

    #[error(transparent)]
    ChainError(#[from] Box<ChainError>),

    #[error(transparent)]
    BcsError(#[from] bcs::Error),

    // Chain access control
    #[error("Block was not signed by an authorized owner")]
    InvalidOwner,

    #[error("Operations in the block are not authenticated by the proper owner: {0}")]
    InvalidSigner(AccountOwner),

    // Chaining
    #[error(
        "Chain is expecting a next block at height {expected_block_height} but the given block \
        is at height {found_block_height} instead"
    )]
    UnexpectedBlockHeight {
        expected_block_height: BlockHeight,
        found_block_height: BlockHeight,
    },
    #[error("Unexpected epoch {epoch}: chain {chain_id} is at {chain_epoch}")]
    InvalidEpoch {
        chain_id: ChainId,
        chain_epoch: Epoch,
        epoch: Epoch,
    },

    #[error("Events not found: {0:?}")]
    EventsNotFound(Vec<EventId>),

    // Other server-side errors
    #[error("Invalid cross-chain request")]
    InvalidCrossChainRequest,
    #[error("The block does not contain the hash that we expected for the previous block")]
    InvalidBlockChaining,
    #[error(
        "Block timestamp ({block_timestamp}) is further in the future from local time \
        ({local_time}) than block time grace period ({block_time_grace_period:?}) \
        [us:{block_timestamp_us}:{local_time_us}]",
        block_timestamp_us = block_timestamp.micros(),
        local_time_us = local_time.micros(),
    )]
    InvalidTimestamp {
        block_timestamp: Timestamp,
        local_time: Timestamp,
        block_time_grace_period: Duration,
    },
    #[error("We don't have the value for the certificate.")]
    MissingCertificateValue,
    #[error("Block at height {height} on chain {chain_id} not found in local storage")]
    LocalBlockNotFound {
        height: BlockHeight,
        chain_id: ChainId,
    },
    #[error("The hash certificate doesn't match its value.")]
    InvalidLiteCertificate,
    #[error("Fast blocks cannot query oracles")]
    FastBlockUsingOracles,
    #[error("Blobs not found: {0:?}")]
    BlobsNotFound(Vec<BlobId>),
    #[error(
        "confirmed_log/preprocessed_blocks entry at height {height} for chain {chain_id} not found"
    )]
    ConfirmedBlockHashNotFound {
        height: BlockHeight,
        chain_id: ChainId,
    },
    #[error("The block proposal is invalid: {0}")]
    InvalidBlockProposal(String),
    #[error("Blob was not required by any pending block")]
    UnexpectedBlob,
    #[error("Number of published blobs per block must not exceed {0}")]
    TooManyPublishedBlobs(u64),
    #[error("Missing network description")]
    MissingNetworkDescription,
    #[error("thread error: {0}")]
    Thread(#[from] web_thread_pool::Error),

    #[error("Fallback mode is not available on this network")]
    NoFallbackMode,
    #[error("Chain worker was poisoned by a journal resolution failure")]
    PoisonedWorker,
}

impl WorkerError {
    /// Returns whether this error is caused by an issue in the local node.
    ///
    /// Returns `false` whenever the error could be caused by a bad message from a peer.
    pub fn is_local(&self) -> bool {
        match self {
            WorkerError::CryptoError(_)
            | WorkerError::ArithmeticError(_)
            | WorkerError::InvalidOwner
            | WorkerError::InvalidSigner(_)
            | WorkerError::UnexpectedBlockHeight { .. }
            | WorkerError::InvalidEpoch { .. }
            | WorkerError::EventsNotFound(_)
            | WorkerError::InvalidBlockChaining
            | WorkerError::InvalidTimestamp { .. }
            | WorkerError::MissingCertificateValue
            | WorkerError::InvalidLiteCertificate
            | WorkerError::FastBlockUsingOracles
            | WorkerError::BlobsNotFound(_)
            | WorkerError::InvalidBlockProposal(_)
            | WorkerError::UnexpectedBlob
            | WorkerError::TooManyPublishedBlobs(_)
            | WorkerError::NoFallbackMode
            | WorkerError::ViewError(ViewError::NotFound(_)) => false,
            WorkerError::BcsError(_)
            | WorkerError::InvalidCrossChainRequest
            | WorkerError::ViewError(_)
            | WorkerError::ConfirmedBlockHashNotFound { .. }
            | WorkerError::LocalBlockNotFound { .. }
            | WorkerError::MissingNetworkDescription
            | WorkerError::Thread(_)
            | WorkerError::ReadCertificatesError(_)
            | WorkerError::PoisonedWorker => true,
            WorkerError::ChainError(chain_error) => chain_error.is_local(),
        }
    }

    /// Returns the qualified error variant name for the `error_type` metric label,
    /// e.g. `"WorkerError::UnexpectedBlockHeight"`.
    ///
    /// For `ChainError` variants, delegates to `ChainError::error_type()` to
    /// surface the underlying error name rather than just `"ChainError"`.
    pub fn error_type(&self) -> String {
        match self {
            WorkerError::ChainError(chain_error) => chain_error.error_type(),
            other => {
                let variant: &'static str = other.into();
                format!("WorkerError::{variant}")
            }
        }
    }

    /// Returns `true` if this error indicates that the chain worker's in-memory
    /// state may be inconsistent and must be evicted from the cache.
    fn must_reload_view(&self) -> bool {
        matches!(
            self,
            WorkerError::PoisonedWorker
                | WorkerError::ViewError(ViewError::StoreError {
                    must_reload_view: true,
                    ..
                })
        )
    }

    /// Returns `true` if this error indicates that the chain's persisted state is
    /// internally inconsistent, so the worker should consider resetting and
    /// re-executing it from storage.
    fn indicates_corrupted_chain_state(&self) -> bool {
        matches!(
            self,
            WorkerError::ChainError(chain_error)
                if matches!(chain_error.as_ref(), ChainError::CorruptedChainState(_))
        )
    }
}

impl From<ChainError> for WorkerError {
    #[instrument(level = "trace", skip(chain_error))]
    fn from(chain_error: ChainError) -> Self {
        match chain_error {
            ChainError::ExecutionError(execution_error, context) => match *execution_error {
                ExecutionError::BlobsNotFound(blob_ids) => Self::BlobsNotFound(blob_ids),
                ExecutionError::EventsNotFound(event_ids) => Self::EventsNotFound(event_ids),
                _ => Self::ChainError(Box::new(ChainError::ExecutionError(
                    execution_error,
                    context,
                ))),
            },
            error => Self::ChainError(Box::new(error)),
        }
    }
}

#[cfg(with_testing)]
impl WorkerError {
    /// Returns the inner [`ExecutionError`] in this error.
    ///
    /// # Panics
    ///
    /// If this is not caused by an [`ExecutionError`].
    pub fn expect_execution_error(self, expected_context: ChainExecutionContext) -> ExecutionError {
        let WorkerError::ChainError(chain_error) = self else {
            panic!("Expected an `ExecutionError`. Got: {self:#?}");
        };

        let ChainError::ExecutionError(execution_error, context) = *chain_error else {
            panic!("Expected an `ExecutionError`. Got: {chain_error:#?}");
        };

        assert_eq!(context, expected_context);

        *execution_error
    }
}

type ChainWorkerArc<S> = Arc<tokio::sync::RwLock<ChainWorkerState<S>>>;
type ChainWorkerWeak<S> = std::sync::Weak<tokio::sync::RwLock<ChainWorkerState<S>>>;
type ChainWorkerFuture<S> = Shared<oneshot::Receiver<ChainWorkerWeak<S>>>;

/// Each map entry is a `Shared<oneshot::Receiver<Weak<...>>>`:
///
/// - `peek()` returns `None` while a task is loading the worker from storage.
/// - `peek()` returns `Some(Ok(weak))` once the worker is loaded.
/// - `peek()` returns `Some(Err(_))` if loading failed (sender dropped).
///
/// Callers that find a pending entry clone the `Shared` future and await it.
type ChainWorkerMap<S> = Arc<papaya::HashMap<ChainId, ChainWorkerFuture<S>>>;

/// Starts a background task that periodically removes dead weak references
/// from the chain handle map. The actual lifetime management is handled by
/// each handle's keep-alive task.
fn start_sweep<S: Storage + Clone + 'static>(
    chain_workers: &ChainWorkerMap<S>,
    config: &ChainWorkerConfig,
) {
    // Sweep at the smaller of the two TTLs. If both are None, workers
    // live forever so there's nothing to sweep.
    let interval = match (config.ttl, config.sender_chain_ttl) {
        (None, None) => return,
        (Some(d), None) | (None, Some(d)) => d,
        (Some(a), Some(b)) => a.min(b),
    };
    let weak_map = Arc::downgrade(chain_workers);
    linera_base::Task::spawn(async move {
        loop {
            linera_base::time::timer::sleep(interval).await;
            let Some(map) = weak_map.upgrade() else {
                break;
            };
            map.pin_owned().retain(|_, shared| match shared.peek() {
                Some(Ok(weak)) => weak.strong_count() > 0,
                Some(Err(_)) => false, // Loading failed; clean up.
                None => true,          // Still loading; keep.
            });
        }
    })
    .forget();
}

/// State of a worker in a validator or a local node.
pub struct WorkerState<StorageClient: Storage> {
    /// Access to local persistent storage.
    storage: StorageClient,
    /// Configuration options for chain workers.
    pub(crate) chain_worker_config: ChainWorkerConfig,
    block_cache: Arc<ValueCache<CryptoHash, Hashed<Block>>>,
    execution_state_cache:
        Option<Arc<UniqueValueCache<CryptoHash, ExecutionStateView<InactiveContext>>>>,
    /// Chains tracked by a worker, along with their listening modes.
    chain_modes: Option<Arc<RwLock<BTreeMap<ChainId, ListeningMode>>>>,
    /// One-shot channels to notify callers when messages of a particular chain have been
    /// delivered.
    delivery_notifiers: Arc<Mutex<DeliveryNotifiers>>,
    /// The cache of loaded chain workers. Stores weak references; each worker
    /// manages its own lifetime via a keep-alive task. A background sweep
    /// periodically removes dead entries.
    chain_workers: ChainWorkerMap<StorageClient>,
    /// Shard-routing dispatcher for outbound cross-chain requests. Used when we need
    /// to send cross-chain requests outside of the normal `NetworkActions` return
    /// path — in particular, the `RevertConfirm`s emitted after resetting a
    /// corrupted chain. The RPC server layer installs this; without it, we fall
    /// back to dispatching locally through `handle_cross_chain_request`.
    outbound_cross_chain_sender: Option<OutboundCrossChainSender>,
}

/// Dispatcher for outbound cross-chain requests that handles the source-shard-to-
/// target-shard routing that the worker itself is not aware of.
pub type OutboundCrossChainSender = Arc<dyn Fn(CrossChainRequest) + Send + Sync>;

impl<StorageClient> Clone for WorkerState<StorageClient>
where
    StorageClient: Storage + Clone,
{
    fn clone(&self) -> Self {
        WorkerState {
            storage: self.storage.clone(),
            chain_worker_config: self.chain_worker_config.clone(),
            block_cache: self.block_cache.clone(),
            execution_state_cache: self.execution_state_cache.clone(),
            chain_modes: self.chain_modes.clone(),
            delivery_notifiers: self.delivery_notifiers.clone(),
            chain_workers: self.chain_workers.clone(),
            outbound_cross_chain_sender: self.outbound_cross_chain_sender.clone(),
        }
    }
}

pub(crate) type DeliveryNotifiers = HashMap<ChainId, DeliveryNotifier>;

impl<StorageClient> WorkerState<StorageClient>
where
    StorageClient: Storage,
{
    /// Sets the cross-chain message chunk limit.
    pub fn set_cross_chain_message_chunk_limit(&mut self, limit: usize) {
        self.chain_worker_config.cross_chain_message_chunk_limit = limit;
    }

    #[instrument(level = "trace", skip(self))]
    pub fn nickname(&self) -> &str {
        &self.chain_worker_config.nickname
    }

    /// Sets the priority bundle origins.
    pub fn with_priority_bundle_origins(
        mut self,
        origins: std::collections::HashSet<ChainId>,
    ) -> Self {
        self.chain_worker_config.priority_bundle_origins = origins;
        self
    }

    /// Returns the storage client so that it can be manipulated or queried.
    #[instrument(level = "trace", skip(self))]
    #[cfg(not(feature = "test"))]
    pub(crate) fn storage_client(&self) -> &StorageClient {
        &self.storage
    }

    /// Returns the storage client so that it can be manipulated or queried by tests in other
    /// crates.
    #[instrument(level = "trace", skip(self))]
    #[cfg(feature = "test")]
    pub fn storage_client(&self) -> &StorageClient {
        &self.storage
    }

    #[instrument(level = "trace", skip(self, certificate))]
    pub(crate) async fn full_certificate(
        &self,
        certificate: LiteCertificate<'_>,
    ) -> Result<Either<ConfirmedBlockCertificate, ValidatedBlockCertificate>, WorkerError> {
        let block = self
            .block_cache
            .get(&certificate.value.value_hash)
            .ok_or(WorkerError::MissingCertificateValue)?;
        let block = Arc::unwrap_or_clone(block);

        match certificate.value.kind {
            linera_chain::types::CertificateKind::Confirmed => {
                let value = ConfirmedBlock::from_hashed(block);
                Ok(Either::Left(
                    certificate
                        .with_value(value)
                        .ok_or(WorkerError::InvalidLiteCertificate)?,
                ))
            }
            linera_chain::types::CertificateKind::Validated => {
                let value = ValidatedBlock::from_hashed(block);
                Ok(Either::Right(
                    certificate
                        .with_value(value)
                        .ok_or(WorkerError::InvalidLiteCertificate)?,
                ))
            }
            _ => Err(WorkerError::InvalidLiteCertificate),
        }
    }
}

#[allow(async_fn_in_trait)]
#[cfg_attr(not(web), trait_variant::make(Send))]
pub trait ProcessableCertificate: CertificateValue + Sized + 'static {
    async fn process_certificate<S: Storage + Clone + 'static>(
        worker: &WorkerState<S>,
        certificate: GenericCertificate<Self>,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError>;
}

impl ProcessableCertificate for ConfirmedBlock {
    async fn process_certificate<S: Storage + Clone + 'static>(
        worker: &WorkerState<S>,
        certificate: ConfirmedBlockCertificate,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        Box::pin(worker.handle_confirmed_certificate(certificate, None)).await
    }
}

impl ProcessableCertificate for ValidatedBlock {
    async fn process_certificate<S: Storage + Clone + 'static>(
        worker: &WorkerState<S>,
        certificate: ValidatedBlockCertificate,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        Box::pin(worker.handle_validated_certificate(certificate)).await
    }
}

impl ProcessableCertificate for Timeout {
    async fn process_certificate<S: Storage + Clone + 'static>(
        worker: &WorkerState<S>,
        certificate: TimeoutCertificate,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        worker.handle_timeout_certificate(certificate).await
    }
}

impl<StorageClient> WorkerState<StorageClient>
where
    StorageClient: Storage + Clone + 'static,
{
    /// Creates a new `WorkerState`.
    ///
    /// The `chain_worker_config` must be fully configured before calling this, because the
    /// TTL sweep task is started immediately based on the config's TTL values.
    #[instrument(level = "trace", skip(storage, chain_worker_config))]
    pub fn new(
        storage: StorageClient,
        chain_worker_config: ChainWorkerConfig,
        chain_modes: Option<Arc<RwLock<BTreeMap<ChainId, ListeningMode>>>>,
    ) -> Self {
        let chain_workers = Arc::new(papaya::HashMap::new());
        start_sweep(&chain_workers, &chain_worker_config);
        let block_cache_size = chain_worker_config.block_cache_size;
        let execution_state_cache_size = chain_worker_config.execution_state_cache_size;
        WorkerState {
            storage,
            chain_worker_config,
            block_cache: Arc::new(ValueCache::new(
                block_cache_size,
                DEFAULT_CLEANUP_INTERVAL_SECS,
            )),
            execution_state_cache: (execution_state_cache_size > 0)
                .then(|| Arc::new(UniqueValueCache::new(execution_state_cache_size))),
            chain_modes,
            delivery_notifiers: Arc::default(),
            chain_workers,
            outbound_cross_chain_sender: None,
        }
    }

    /// Installs a shard-routing dispatcher used for outbound cross-chain requests
    /// generated outside the normal response path (specifically, after resetting a
    /// corrupted chain). Without it, such requests are dispatched locally in a
    /// loop via `handle_cross_chain_request`.
    pub fn with_outbound_cross_chain_sender(mut self, sender: OutboundCrossChainSender) -> Self {
        self.outbound_cross_chain_sender = Some(sender);
        self
    }

    #[instrument(level = "trace", skip(self, certificate, notifier))]
    #[inline]
    pub async fn fully_handle_certificate_with_notifications<T>(
        &self,
        certificate: GenericCertificate<T>,
        notifier: &impl Notifier,
    ) -> Result<ChainInfoResponse, WorkerError>
    where
        T: ProcessableCertificate,
    {
        let notifications = (*notifier).clone();
        let this = self.clone();
        linera_base::Task::spawn(async move {
            let (response, actions) =
                ProcessableCertificate::process_certificate(&this, certificate).await?;
            notifications.notify(&actions.notifications);
            let mut requests = VecDeque::from(actions.cross_chain_requests);
            while let Some(request) = requests.pop_front() {
                let actions = this.handle_cross_chain_request(request).await?;
                requests.extend(actions.cross_chain_requests);
                notifications.notify(&actions.notifications);
            }
            Ok(response)
        })
        .await
    }

    /// Acquires a read lock on the chain worker and executes the given closure.
    ///
    /// The future is boxed to keep deeply nested types off the stack. On non-web
    /// targets it is also wrapped in `SyncFuture` to satisfy `Sync` bounds.
    async fn chain_read<R, F, Fut>(&self, chain_id: ChainId, f: F) -> Result<R, WorkerError>
    where
        F: FnOnce(OwnedRwLockReadGuard<ChainWorkerState<StorageClient>>) -> Fut,
        Fut: std::future::Future<Output = Result<R, WorkerError>>,
    {
        let state = self.get_or_create_chain_worker(chain_id).await?;
        let state_ref = &state;
        let result = Box::pin(wrap_future(async move {
            let guard = handle::read_lock(state_ref).await;
            guard.check_not_poisoned()?;
            f(guard).await
        }))
        .await;
        if let Err(error) = &result {
            if error.must_reload_view() {
                self.evict_poisoned_worker(chain_id, &state);
            }
        }
        result
    }

    /// Acquires a write lock on the chain worker and executes the given closure.
    ///
    /// The write work runs on a detached task (via [`linera_base::task::run_detached`])
    /// so that caller cancellation does not unwind the task mid-save. The
    /// [`RollbackGuard`] lives inside the detached task, so the write lock is held
    /// until the DB round-trip and `post_save` have fully completed — subsequent
    /// readers, including a freshly-loaded replacement worker, only see the
    /// committed state.
    async fn chain_write<R, F, Fut>(&self, chain_id: ChainId, f: F) -> Result<R, WorkerError>
    where
        F: FnOnce(handle::RollbackGuard<StorageClient>) -> Fut
            + linera_base::task::MaybeSend
            + 'static,
        Fut: std::future::Future<Output = Result<R, WorkerError>> + linera_base::task::MaybeSend,
        R: linera_base::task::MaybeSend + 'static,
    {
        let state = self.get_or_create_chain_worker(chain_id).await?;
        let state_for_task = state.clone();
        let result = Box::pin(wrap_future(linera_base::task::run_detached(async move {
            let guard = handle::write_lock(&state_for_task).await;
            guard.check_not_poisoned()?;
            f(guard).await
        })))
        .await;
        if let Err(error) = &result {
            if error.must_reload_view() {
                self.evict_poisoned_worker(chain_id, &state);
            } else if error.indicates_corrupted_chain_state() {
                self.spawn_reset_corrupted_chain_state(chain_id, state);
            }
        }
        result
    }

    /// Spawns a detached task that re-acquires the write lock and recovers the
    /// chain from a detected state corruption. Running the recovery in a separate
    /// task ensures it survives cancellation of the originating request: if the
    /// caller's future is dropped mid-way through re-execution, the chain would
    /// otherwise be left at a partial tip and our safety snapshot would be lost.
    /// Generated `RevertConfirm` requests are dispatched via the installed
    /// shard-routing sender when present (sharded validators), or locally
    /// through `handle_cross_chain_request` otherwise (client nodes and tests).
    /// Errors are logged; the caller already has the original error to
    /// propagate.
    fn spawn_reset_corrupted_chain_state(
        &self,
        chain_id: ChainId,
        state: ChainWorkerArc<StorageClient>,
    ) where
        StorageClient: Clone,
    {
        let this = self.clone();
        linera_base::Task::spawn(async move {
            let requests = {
                let mut guard = handle::write_lock(&state).await;
                match guard.maybe_reset_corrupted_chain_state().await {
                    Ok(Some(requests)) => requests,
                    Ok(None) => return,
                    Err(error) => {
                        tracing::error!(
                            %chain_id, %error, "Failed to reset corrupted chain state"
                        );
                        return;
                    }
                }
            };
            if let Some(sender) = &this.outbound_cross_chain_sender {
                // Sharded validator path: let the RPC layer route each request to
                // the shard that owns the target chain.
                for request in requests {
                    sender(request);
                }
            } else {
                // No routing dispatcher is installed (client node or test), so all
                // involved chains are co-located on this worker. Dispatch locally
                // in a loop, following any cascading cross-chain requests.
                let mut queue = VecDeque::from(requests);
                while let Some(request) = queue.pop_front() {
                    match this.handle_cross_chain_request(request).await {
                        Ok(actions) => queue.extend(actions.cross_chain_requests),
                        Err(error) => {
                            warn!(
                                %chain_id, %error,
                                "Failed to dispatch cross-chain request after \
                                resetting corrupted chain state"
                            );
                        }
                    }
                }
            }
        })
        .forget();
    }

    /// Evicts a poisoned chain worker from the cache, but only if the entry still
    /// points to the same instance. This avoids removing a fresh replacement that
    /// another task may have already loaded.
    fn evict_poisoned_worker(&self, chain_id: ChainId, poisoned: &ChainWorkerArc<StorageClient>) {
        tracing::warn!(%chain_id, "Evicting poisoned chain worker from cache");
        let pin = self.chain_workers.pin();
        let weak_poisoned = Arc::downgrade(poisoned);
        let _ = pin.remove_if(&chain_id, |_key, future| {
            future
                .peek()
                .and_then(|r| r.clone().ok())
                .is_some_and(|weak| weak.ptr_eq(&weak_poisoned))
        });
    }

    /// Gets or creates a chain worker for the given chain.
    ///
    /// The oneshot channel is created outside the `compute` closure to keep
    /// the closure pure (papaya may call it more than once on CAS retry and
    /// may memoize the output). If the fast path hits, the unused channel is
    /// dropped harmlessly.
    ///
    /// Returns a type-erased future to keep `!Sync` intermediate types (e.g.
    /// `std::sync::mpsc::Receiver` from `handle::ServiceRuntimeActor::spawn`) out of
    /// the caller's future type.
    fn get_or_create_chain_worker(
        &self,
        chain_id: ChainId,
    ) -> std::pin::Pin<
        Box<
            impl std::future::Future<Output = Result<ChainWorkerArc<StorageClient>, WorkerError>> + '_,
        >,
    > {
        Box::pin(wrap_future(async move {
            loop {
                // Create the channel outside the closure so that the tx/rx
                // always match regardless of CAS retries.
                let (tx, rx) = oneshot::channel();
                let shared_rx = rx.shared();

                // The papaya guard is !Send, so it must be dropped before
                // any .await point.
                let wait_or_tx = {
                    let pin = self.chain_workers.pin();
                    match pin.compute(chain_id, |existing| match existing {
                        Some((_, entry)) => match entry.peek() {
                            Some(Ok(weak)) => match weak.upgrade() {
                                Some(arc) => papaya::Operation::Abort(Ok(arc)),
                                None => papaya::Operation::Insert(shared_rx.clone()),
                            },
                            Some(Err(_)) => papaya::Operation::Insert(shared_rx.clone()),
                            None => papaya::Operation::Abort(Err(entry.clone())),
                        },
                        None => papaya::Operation::Insert(shared_rx.clone()),
                    }) {
                        papaya::Compute::Aborted(Ok(arc), ..) => return Ok(arc),
                        papaya::Compute::Aborted(Err(wait), ..) => Either::Left(wait),
                        papaya::Compute::Inserted { .. } | papaya::Compute::Updated { .. } => {
                            Either::Right(tx)
                        }
                        papaya::Compute::Removed { .. } => unreachable!(),
                    }
                };

                match wait_or_tx {
                    Either::Left(wait) => {
                        // Another task is loading. Await the shared future.
                        if let Ok(weak) = wait.await {
                            if let Some(arc) = weak.upgrade() {
                                return Ok(arc);
                            }
                        }
                        // Loading failed or worker already dead; retry.
                    }
                    Either::Right(tx) => {
                        // We claimed the loading slot. Load from storage.
                        // On success, send the Weak through the channel.
                        // On error, dropping tx wakes waiters so they can retry.
                        let worker = self.load_chain_worker(chain_id).await?;
                        if tx.send(Arc::downgrade(&worker)).is_err() {
                            tracing::error!(%chain_id, "Receiver dropped while loading worker state.");
                            continue;
                        }
                        return Ok(worker);
                    }
                }
            }
        }))
    }

    /// Loads a chain worker state from storage and wraps it in an Arc.
    async fn load_chain_worker(
        &self,
        chain_id: ChainId,
    ) -> Result<ChainWorkerArc<StorageClient>, WorkerError> {
        let delivery_notifier = self
            .delivery_notifiers
            .lock()
            .unwrap()
            .entry(chain_id)
            .or_default()
            .clone();

        let is_tracked = self.chain_modes.as_ref().is_some_and(|chain_modes| {
            chain_modes
                .read()
                .unwrap()
                .get(&chain_id)
                .is_some_and(ListeningMode::is_full)
        });

        let (service_runtime_endpoint, service_runtime_task) =
            if self.chain_worker_config.long_lived_services {
                let actor =
                    handle::ServiceRuntimeActor::spawn(chain_id, self.storage.thread_pool()).await;
                (Some(actor.endpoint), Some(actor.task))
            } else {
                (None, None)
            };

        let state = crate::chain_worker::state::ChainWorkerState::load(
            self.chain_worker_config.clone(),
            self.storage.clone(),
            self.block_cache.clone(),
            self.execution_state_cache.clone(),
            self.chain_modes.clone(),
            delivery_notifier,
            chain_id,
            service_runtime_endpoint,
            service_runtime_task,
        )
        .await?;

        Ok(handle::create_chain_worker(
            state,
            is_tracked,
            &self.chain_worker_config,
        ))
    }

    /// Tries to execute a block proposal without any verification other than block execution.
    #[instrument(level = "trace", skip(self, block))]
    pub async fn stage_block_execution(
        &self,
        block: ProposedBlock,
        round: Option<u32>,
        published_blobs: Vec<Blob>,
        policy: BundleExecutionPolicy,
    ) -> Result<(ProposedBlock, Block, ChainInfoResponse, ResourceTracker), WorkerError> {
        let chain_id = block.chain_id;
        self.chain_write(chain_id, move |mut guard| async move {
            guard
                .stage_block_execution(block, round, &published_blobs, policy)
                .await
        })
        .await
    }

    /// Executes a [`Query`] for an application's state on a specific chain.
    ///
    /// If `block_hash` is specified, system will query the application's state
    /// at that block. If it doesn't exist, it uses latest state.
    #[instrument(level = "trace", skip(self, chain_id, query))]
    pub async fn query_application(
        &self,
        chain_id: ChainId,
        query: Query,
        block_hash: Option<CryptoHash>,
    ) -> Result<(QueryOutcome, BlockHeight), WorkerError> {
        self.chain_write(chain_id, move |mut guard| async move {
            guard.query_application(query, block_hash).await
        })
        .await
    }

    #[instrument(level = "trace", skip(self, chain_id, application_id), fields(
        nickname = %self.nickname(),
        chain_id = %chain_id,
        application_id = %application_id
    ))]
    pub async fn describe_application(
        &self,
        chain_id: ChainId,
        application_id: ApplicationId,
    ) -> Result<ApplicationDescription, WorkerError> {
        let state = self.get_or_create_chain_worker(chain_id).await?;
        let guard = handle::read_lock_initialized(&state).await?;
        guard.describe_application_readonly(application_id).await
    }

    /// Processes a confirmed block (aka a commit).
    #[instrument(
        level = "trace",
        skip(self, certificate, notify_when_messages_are_delivered),
        fields(
            nickname = %self.nickname(),
            chain_id = %certificate.block().header.chain_id,
            block_height = %certificate.block().header.height
        )
    )]
    async fn process_confirmed_block(
        &self,
        certificate: ConfirmedBlockCertificate,
        notify_when_messages_are_delivered: Option<oneshot::Sender<()>>,
    ) -> Result<(ChainInfoResponse, NetworkActions, BlockOutcome), WorkerError> {
        let chain_id = certificate.block().header.chain_id;
        self.chain_write(chain_id, move |mut guard| async move {
            guard
                .process_confirmed_block(certificate, notify_when_messages_are_delivered)
                .await
        })
        .await
    }

    /// Processes a validated block issued from a multi-owner chain.
    #[instrument(level = "trace", skip(self, certificate), fields(
        nickname = %self.nickname(),
        chain_id = %certificate.block().header.chain_id,
        block_height = %certificate.block().header.height
    ))]
    async fn process_validated_block(
        &self,
        certificate: ValidatedBlockCertificate,
    ) -> Result<(ChainInfoResponse, NetworkActions, BlockOutcome), WorkerError> {
        let chain_id = certificate.block().header.chain_id;
        self.chain_write(chain_id, move |mut guard| async move {
            guard.process_validated_block(certificate).await
        })
        .await
    }

    /// Processes a leader timeout issued from a multi-owner chain.
    #[instrument(level = "trace", skip(self, certificate), fields(
        nickname = %self.nickname(),
        chain_id = %certificate.value().chain_id(),
        height = %certificate.value().height()
    ))]
    async fn process_timeout(
        &self,
        certificate: TimeoutCertificate,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        let chain_id = certificate.value().chain_id();
        self.chain_write(chain_id, move |mut guard| async move {
            guard.process_timeout(certificate).await
        })
        .await
    }

    #[instrument(level = "trace", skip(self, origin, recipient, bundles), fields(
        nickname = %self.nickname(),
        origin = %origin,
        recipient = %recipient,
        num_bundles = %bundles.len()
    ))]
    async fn process_cross_chain_update(
        &self,
        origin: ChainId,
        recipient: ChainId,
        bundles: Vec<(Epoch, MessageBundle)>,
        previous_height: Option<BlockHeight>,
    ) -> Result<CrossChainUpdateResult, WorkerError> {
        self.chain_write(recipient, move |mut guard| async move {
            guard
                .process_cross_chain_update(origin, bundles, previous_height)
                .await
        })
        .await
    }

    /// Returns a stored [`ConfirmedBlockCertificate`] for a chain's block.
    #[instrument(level = "trace", skip(self, chain_id, height), fields(
        nickname = %self.nickname(),
        chain_id = %chain_id,
        height = %height
    ))]
    #[cfg(with_testing)]
    pub async fn read_certificate(
        &self,
        chain_id: ChainId,
        height: BlockHeight,
    ) -> Result<Option<ConfirmedBlockCertificate>, WorkerError> {
        let state = self.get_or_create_chain_worker(chain_id).await?;
        let guard = handle::read_lock_initialized(&state).await?;
        guard.read_certificate(height).await
    }

    /// Returns a read-only view of the [`ChainStateView`] of a chain referenced by its
    /// [`ChainId`].
    ///
    /// The returned guard holds a read lock on the chain state, preventing writes for
    /// its lifetime. Multiple concurrent readers are allowed.
    #[instrument(level = "trace", skip(self), fields(
        nickname = %self.nickname(),
        chain_id = %chain_id
    ))]
    pub async fn chain_state_view(
        &self,
        chain_id: ChainId,
    ) -> Result<ChainStateViewReadGuard<StorageClient>, WorkerError> {
        let state = self.get_or_create_chain_worker(chain_id).await?;
        let guard = handle::read_lock(&state).await;
        Ok(ChainStateViewReadGuard(OwnedRwLockReadGuard::map(
            guard,
            |s| s.chain(),
        )))
    }

    #[instrument(skip_all, fields(
        nick = self.nickname(),
        chain_id = format!("{:.8}", proposal.content.block.chain_id),
        height = %proposal.content.block.height,
    ))]
    pub async fn handle_block_proposal(
        &self,
        proposal: BlockProposal,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        trace!("{} <-- {:?}", self.nickname(), proposal);
        #[cfg(with_metrics)]
        let round = proposal.content.round;

        let chain_id = proposal.content.block.chain_id;
        // Delay if block timestamp is in the future but within grace period.
        let now = self.storage.clock().current_time();
        let block_timestamp = proposal.content.block.timestamp;
        let delta = block_timestamp.delta_since(now);
        let grace_period = TimeDelta::from_micros(
            u64::try_from(self.chain_worker_config.block_time_grace_period.as_micros())
                .unwrap_or(u64::MAX),
        );
        if delta > TimeDelta::ZERO && delta <= grace_period {
            self.storage.clock().sleep_until(block_timestamp).await;
        }

        let response = self
            .chain_write(chain_id, move |mut guard| async move {
                guard.handle_block_proposal(proposal).await
            })
            .await?;
        #[cfg(with_metrics)]
        metrics::NUM_ROUNDS_IN_BLOCK_PROPOSAL
            .with_label_values(&[round.type_name()])
            .observe(round.number() as f64);
        Ok(response)
    }

    /// Processes a certificate, e.g. to extend a chain with a confirmed block.
    // Other fields will be included in the caller's span.
    #[instrument(skip_all, fields(
        chain_id = %certificate.value.chain_id,
        hash = %certificate.value.value_hash,
    ))]
    pub async fn handle_lite_certificate(
        &self,
        certificate: LiteCertificate<'_>,
        notify_when_messages_are_delivered: Option<oneshot::Sender<()>>,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        match self.full_certificate(certificate).await? {
            Either::Left(confirmed) => {
                Box::pin(
                    self.handle_confirmed_certificate(
                        confirmed,
                        notify_when_messages_are_delivered,
                    ),
                )
                .await
            }
            Either::Right(validated) => {
                if let Some(notifier) = notify_when_messages_are_delivered {
                    // Nothing to wait for.
                    if let Err(()) = notifier.send(()) {
                        warn!("Failed to notify message delivery to caller");
                    }
                }
                Box::pin(self.handle_validated_certificate(validated)).await
            }
        }
    }

    /// Processes a confirmed block certificate.
    #[instrument(skip_all, fields(
        nick = self.nickname(),
        chain_id = format!("{:.8}", certificate.block().header.chain_id),
        height = %certificate.block().header.height,
    ))]
    pub async fn handle_confirmed_certificate(
        &self,
        certificate: ConfirmedBlockCertificate,
        notify_when_messages_are_delivered: Option<oneshot::Sender<()>>,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        trace!("{} <-- {:?}", self.nickname(), certificate);
        #[cfg(with_metrics)]
        let metrics_data = metrics::MetricsData::new(&certificate);

        #[allow(unused_variables)]
        let (info, actions, outcome) =
            Box::pin(self.process_confirmed_block(certificate, notify_when_messages_are_delivered))
                .await?;

        #[cfg(with_metrics)]
        if matches!(outcome, BlockOutcome::Processed) {
            metrics_data.record();
        }
        Ok((info, actions))
    }

    /// Processes a validated block certificate.
    #[instrument(skip_all, fields(
        nick = self.nickname(),
        chain_id = format!("{:.8}", certificate.block().header.chain_id),
        height = %certificate.block().header.height,
    ))]
    pub async fn handle_validated_certificate(
        &self,
        certificate: ValidatedBlockCertificate,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        trace!("{} <-- {:?}", self.nickname(), certificate);

        #[cfg(with_metrics)]
        let round = certificate.round;
        #[cfg(with_metrics)]
        let cert_str = certificate.inner().to_log_str();

        #[allow(unused_variables)]
        let (info, actions, outcome) = Box::pin(self.process_validated_block(certificate)).await?;
        #[cfg(with_metrics)]
        {
            if matches!(outcome, BlockOutcome::Processed) {
                metrics::NUM_ROUNDS_IN_CERTIFICATE
                    .with_label_values(&[cert_str, round.type_name()])
                    .observe(round.number() as f64);
            }
        }
        Ok((info, actions))
    }

    /// Processes a timeout certificate
    #[instrument(skip_all, fields(
        nick = self.nickname(),
        chain_id = format!("{:.8}", certificate.inner().chain_id()),
        height = %certificate.inner().height(),
    ))]
    pub async fn handle_timeout_certificate(
        &self,
        certificate: TimeoutCertificate,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        trace!("{} <-- {:?}", self.nickname(), certificate);
        self.process_timeout(certificate).await
    }

    #[instrument(skip_all, fields(
        nick = self.nickname(),
        chain_id = format!("{:.8}", query.chain_id)
    ))]
    pub async fn handle_chain_info_query(
        &self,
        query: ChainInfoQuery,
    ) -> Result<(ChainInfoResponse, NetworkActions), WorkerError> {
        trace!("{} <-- {:?}", self.nickname(), query);
        #[cfg(with_metrics)]
        metrics::CHAIN_INFO_QUERIES.inc();
        let chain_id = query.chain_id;
        let result = self
            .chain_write(chain_id, move |mut guard| async move {
                guard.handle_chain_info_query(query).await
            })
            .await;
        trace!("{} --> {:?}", self.nickname(), result);
        result
    }

    #[instrument(skip_all, fields(
        nick = self.nickname(),
        chain_id = format!("{:.8}", chain_id)
    ))]
    pub async fn download_pending_blob(
        &self,
        chain_id: ChainId,
        blob_id: BlobId,
    ) -> Result<Blob, WorkerError> {
        trace!("{} <-- download_pending_blob({blob_id:8})", self.nickname());
        let result = self
            .chain_read(chain_id, |guard| async move {
                guard.download_pending_blob(blob_id).await
            })
            .await;
        trace!(
            "{} --> {:?}",
            self.nickname(),
            result.as_ref().map(|_| blob_id)
        );
        result
    }

    #[instrument(skip_all, fields(
        nick = self.nickname(),
        chain_id = format!("{:.8}", chain_id)
    ))]
    pub async fn handle_pending_blob(
        &self,
        chain_id: ChainId,
        blob: Blob,
    ) -> Result<ChainInfoResponse, WorkerError> {
        let blob_id = blob.id();
        trace!("{} <-- handle_pending_blob({blob_id:8})", self.nickname());
        let result = self
            .chain_write(chain_id, move |mut guard| async move {
                guard.handle_pending_blob(blob).await
            })
            .await;
        trace!(
            "{} --> {:?}",
            self.nickname(),
            result.as_ref().map(|_| blob_id)
        );
        result
    }

    #[instrument(skip_all, fields(
        nick = self.nickname(),
        chain_id = format!("{:.8}", request.target_chain_id())
    ))]
    pub async fn handle_cross_chain_request(
        &self,
        request: CrossChainRequest,
    ) -> Result<NetworkActions, WorkerError> {
        trace!("{} <-- {:?}", self.nickname(), request);
        match request {
            CrossChainRequest::UpdateRecipient {
                sender,
                recipient,
                bundles,
                previous_height,
            } => {
                let mut actions = NetworkActions::default();
                let origin = sender;
                match self
                    .process_cross_chain_update(origin, recipient, bundles, previous_height)
                    .await?
                {
                    CrossChainUpdateResult::NothingToDo => {}
                    CrossChainUpdateResult::Updated(height) => {
                        actions.notifications.push(Notification {
                            chain_id: recipient,
                            reason: Reason::NewIncomingBundle { origin, height },
                        });
                        actions.cross_chain_requests.push(
                            CrossChainRequest::ConfirmUpdatedRecipient {
                                sender,
                                recipient,
                                latest_height: height,
                            },
                        );
                    }
                    CrossChainUpdateResult::GapDetected {
                        origin,
                        retransmit_from,
                    } => {
                        actions
                            .cross_chain_requests
                            .push(CrossChainRequest::RevertConfirm {
                                sender: origin,
                                recipient,
                                retransmit_from,
                            });
                    }
                }
                Ok(actions)
            }
            CrossChainRequest::ConfirmUpdatedRecipient {
                sender,
                recipient,
                latest_height,
            } => {
                self.chain_write(sender, move |mut guard| async move {
                    guard
                        .confirm_updated_recipient(recipient, latest_height)
                        .await
                })
                .await
            }
            CrossChainRequest::RevertConfirm {
                sender,
                recipient,
                retransmit_from,
            } => {
                self.chain_write(sender, move |mut guard| async move {
                    guard
                        .handle_revert_confirm(recipient, retransmit_from)
                        .await
                })
                .await
            }
        }
    }

    /// Updates the received certificate trackers to at least the given values.
    #[instrument(skip_all, fields(
        nickname = %self.nickname(),
        chain_id = %chain_id,
        num_trackers = %new_trackers.len()
    ))]
    pub async fn update_received_certificate_trackers(
        &self,
        chain_id: ChainId,
        new_trackers: BTreeMap<ValidatorPublicKey, u64>,
    ) -> Result<(), WorkerError> {
        self.chain_write(chain_id, move |mut guard| async move {
            guard
                .update_received_certificate_trackers(new_trackers)
                .await
        })
        .await
    }

    /// Gets preprocessed block hashes in a given height range.
    #[instrument(skip_all, fields(
        nickname = %self.nickname(),
        chain_id = %chain_id,
        start = %start,
        end = %end
    ))]
    pub async fn get_preprocessed_block_hashes(
        &self,
        chain_id: ChainId,
        start: BlockHeight,
        end: BlockHeight,
    ) -> Result<Vec<CryptoHash>, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_preprocessed_block_hashes(start, end).await
        })
        .await
    }

    /// Gets the next block height to receive from an inbox.
    #[instrument(skip_all, fields(
        nickname = %self.nickname(),
        chain_id = %chain_id,
        origin = %origin
    ))]
    pub async fn get_inbox_next_height(
        &self,
        chain_id: ChainId,
        origin: ChainId,
    ) -> Result<BlockHeight, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_inbox_next_height(origin).await
        })
        .await
    }

    /// Gets locking blobs for specific blob IDs.
    /// Returns `Ok(None)` if any of the blobs is not found.
    #[instrument(skip_all, fields(
        nickname = %self.nickname(),
        chain_id = %chain_id,
        num_blob_ids = %blob_ids.len()
    ))]
    pub async fn get_locking_blobs(
        &self,
        chain_id: ChainId,
        blob_ids: Vec<BlobId>,
    ) -> Result<Option<Vec<Blob>>, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_locking_blobs(blob_ids).await
        })
        .await
    }

    /// Gets block hashes for the given heights.
    pub async fn get_block_hashes(
        &self,
        chain_id: ChainId,
        heights: Vec<BlockHeight>,
    ) -> Result<Vec<CryptoHash>, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_block_hashes(heights).await
        })
        .await
    }

    /// Gets proposed blobs from the manager for specified blob IDs.
    pub async fn get_proposed_blobs(
        &self,
        chain_id: ChainId,
        blob_ids: Vec<BlobId>,
    ) -> Result<Vec<Blob>, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_proposed_blobs(blob_ids).await
        })
        .await
    }

    /// Gets event subscriptions from the chain.
    pub async fn get_event_subscriptions(
        &self,
        chain_id: ChainId,
    ) -> Result<EventSubscriptionsResult, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_event_subscriptions().await
        })
        .await
    }

    /// Gets received certificate trackers.
    pub async fn get_received_certificate_trackers(
        &self,
        chain_id: ChainId,
    ) -> Result<HashMap<ValidatorPublicKey, u64>, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_received_certificate_trackers().await
        })
        .await
    }

    /// Returns the pending cross-chain network actions for this chain without
    /// initializing its execution state. Safe to call on chains whose
    /// `ChainDescription` blob is not available locally.
    pub async fn cross_chain_network_actions(
        &self,
        chain_id: ChainId,
    ) -> Result<NetworkActions, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.cross_chain_network_actions().await
        })
        .await
    }

    /// Gets tip state and outbox info for next_outbox_heights calculation.
    pub async fn get_tip_state_and_outbox_info(
        &self,
        chain_id: ChainId,
        receiver_id: ChainId,
    ) -> Result<(BlockHeight, Option<BlockHeight>), WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_tip_state_and_outbox_info(receiver_id).await
        })
        .await
    }

    /// Gets the next height to preprocess.
    pub async fn get_next_height_to_preprocess(
        &self,
        chain_id: ChainId,
    ) -> Result<BlockHeight, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_next_height_to_preprocess().await
        })
        .await
    }

    /// Gets the chain manager's seed for leader election.
    pub async fn get_manager_seed(&self, chain_id: ChainId) -> Result<u64, WorkerError> {
        self.chain_read(
            chain_id,
            |guard| async move { guard.get_manager_seed().await },
        )
        .await
    }

    /// Gets the stream event count for a stream.
    pub async fn get_stream_event_count(
        &self,
        chain_id: ChainId,
        stream_id: StreamId,
    ) -> Result<Option<u32>, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_stream_event_count(stream_id).await
        })
        .await
    }

    /// Gets the `next_expected_events` indices for the given streams.
    pub async fn next_expected_events(
        &self,
        chain_id: ChainId,
        stream_ids: Vec<StreamId>,
    ) -> Result<BTreeMap<StreamId, u32>, WorkerError> {
        self.chain_read(chain_id, |guard| async move {
            guard.get_next_expected_events(stream_ids).await
        })
        .await
    }

    /// Gets the previous event blocks for specific streams.
    pub async fn previous_event_blocks(
        &self,
        chain_id: ChainId,
        stream_ids: Vec<StreamId>,
    ) -> Result<BTreeMap<StreamId, (BlockHeight, CryptoHash)>, WorkerError> {
        #[cfg(with_metrics)]
        metrics::PREVIOUS_EVENT_BLOCKS_STREAM_COUNT.observe(stream_ids.len() as f64);
        self.chain_read(chain_id, |guard| async move {
            guard.get_previous_event_blocks(stream_ids).await
        })
        .await
    }
}

#[cfg(with_testing)]
impl<StorageClient> WorkerState<StorageClient>
where
    StorageClient: Storage + Clone + 'static,
{
    /// Gets a reference to the validator's [`ValidatorPublicKey`].
    ///
    /// # Panics
    ///
    /// If the validator doesn't have a key pair assigned to it.
    #[instrument(level = "trace", skip(self))]
    pub fn public_key(&self) -> ValidatorPublicKey {
        self.chain_worker_config
            .key_pair()
            .expect(
                "Test validator should have a key pair assigned to it \
                in order to obtain its public key",
            )
            .public()
    }
}