1use std::{
8 collections::{BTreeMap, BTreeSet},
9 iter,
10};
11
12use allocative::Allocative;
13use custom_debug_derive::Debug;
14use linera_witty::{WitLoad, WitStore, WitType};
15use serde::{Deserialize, Serialize};
16use thiserror::Error;
17
18use crate::{
19 data_types::{Round, TimeDelta},
20 doc_scalar,
21 identifiers::AccountOwner,
22};
23
24#[derive(
26 PartialEq,
27 Eq,
28 Clone,
29 Hash,
30 Debug,
31 Serialize,
32 Deserialize,
33 WitLoad,
34 WitStore,
35 WitType,
36 Allocative,
37)]
38pub struct TimeoutConfig {
39 #[debug(skip_if = Option::is_none)]
41 pub fast_round_duration: Option<TimeDelta>,
42 pub base_timeout: TimeDelta,
44 pub timeout_increment: TimeDelta,
46 pub fallback_duration: TimeDelta,
49}
50
51impl Default for TimeoutConfig {
52 fn default() -> Self {
53 Self {
54 fast_round_duration: None,
55 base_timeout: TimeDelta::from_secs(10),
56 timeout_increment: TimeDelta::from_secs(1),
57 fallback_duration: TimeDelta::MAX,
60 }
61 }
62}
63
64#[derive(
66 PartialEq,
67 Eq,
68 Clone,
69 Hash,
70 Debug,
71 Default,
72 Serialize,
73 Deserialize,
74 WitLoad,
75 WitStore,
76 WitType,
77 Allocative,
78)]
79pub struct ChainOwnership {
80 #[debug(skip_if = BTreeSet::is_empty)]
82 pub super_owners: BTreeSet<AccountOwner>,
83 #[debug(skip_if = BTreeMap::is_empty)]
85 pub owners: BTreeMap<AccountOwner, u64>,
86 pub first_leader: Option<AccountOwner>,
88 pub multi_leader_rounds: u32,
90 pub open_multi_leader_rounds: bool,
94 pub timeout_config: TimeoutConfig,
96}
97
98impl ChainOwnership {
99 pub fn single_super(owner: AccountOwner) -> Self {
101 ChainOwnership {
102 super_owners: iter::once(owner).collect(),
103 owners: BTreeMap::new(),
104 first_leader: None,
105 multi_leader_rounds: 2,
106 open_multi_leader_rounds: false,
107 timeout_config: TimeoutConfig::default(),
108 }
109 }
110
111 pub fn single(owner: AccountOwner) -> Self {
113 ChainOwnership {
114 super_owners: BTreeSet::new(),
115 owners: iter::once((owner, 100)).collect(),
116 first_leader: None,
117 multi_leader_rounds: 2,
118 open_multi_leader_rounds: false,
119 timeout_config: TimeoutConfig::default(),
120 }
121 }
122
123 pub fn multiple(
125 owners_and_weights: impl IntoIterator<Item = (AccountOwner, u64)>,
126 multi_leader_rounds: u32,
127 timeout_config: TimeoutConfig,
128 ) -> Self {
129 ChainOwnership {
130 super_owners: BTreeSet::new(),
131 owners: owners_and_weights.into_iter().collect(),
132 first_leader: None,
133 multi_leader_rounds,
134 open_multi_leader_rounds: false,
135 timeout_config,
136 }
137 }
138
139 #[cfg(with_testing)]
141 pub fn with_regular_owner(mut self, owner: AccountOwner, weight: u64) -> Self {
142 self.owners.insert(owner, weight);
143 self
144 }
145
146 pub fn is_active(&self) -> bool {
148 !self.super_owners.is_empty()
149 || !self.owners.is_empty()
150 || self.timeout_config.fallback_duration == TimeDelta::ZERO
151 }
152
153 pub fn is_owner(&self, owner: &AccountOwner) -> bool {
155 self.super_owners.contains(owner)
156 || self.owners.contains_key(owner)
157 || self.first_leader.as_ref().is_some_and(|fl| fl == owner)
158 }
159
160 pub fn can_propose_in_multi_leader_round(&self, owner: &AccountOwner) -> bool {
163 self.open_multi_leader_rounds
164 || self.owners.contains_key(owner)
165 || self.super_owners.contains(owner)
166 }
167
168 pub fn round_timeout(&self, round: Round) -> Option<TimeDelta> {
170 let tc = &self.timeout_config;
171 if round.is_fast() && self.owners.is_empty() {
172 return None; }
174 match round {
175 Round::Fast => tc.fast_round_duration,
176 Round::MultiLeader(r) if r.saturating_add(1) == self.multi_leader_rounds => {
177 Some(tc.base_timeout)
178 }
179 Round::MultiLeader(_) => None,
180 Round::SingleLeader(r) | Round::Validator(r) => {
181 let increment = tc.timeout_increment.saturating_mul(u64::from(r));
182 Some(tc.base_timeout.saturating_add(increment))
183 }
184 }
185 }
186
187 pub fn first_round(&self) -> Round {
189 if !self.super_owners.is_empty() {
190 Round::Fast
191 } else if self.owners.is_empty() {
192 Round::Validator(0)
193 } else if self.multi_leader_rounds > 0 {
194 Round::MultiLeader(0)
195 } else {
196 Round::SingleLeader(0)
197 }
198 }
199
200 pub fn all_owners(&self) -> impl Iterator<Item = &AccountOwner> {
202 self.super_owners.iter().chain(self.owners.keys())
203 }
204
205 pub fn has_fallback(&self) -> bool {
208 self.timeout_config.fallback_duration < TimeDelta::MAX
209 }
210
211 pub fn next_round(&self, round: Round) -> Option<Round> {
213 let next_round = match round {
214 Round::Fast if self.multi_leader_rounds == 0 => Round::SingleLeader(0),
215 Round::Fast => Round::MultiLeader(0),
216 Round::MultiLeader(r) => r
217 .checked_add(1)
218 .filter(|r| *r < self.multi_leader_rounds)
219 .map_or(Round::SingleLeader(0), Round::MultiLeader),
220 Round::SingleLeader(r) => r
221 .checked_add(1)
222 .map_or(Round::Validator(0), Round::SingleLeader),
223 Round::Validator(r) => Round::Validator(r.checked_add(1)?),
224 };
225 Some(next_round)
226 }
227
228 pub fn is_super_owner_no_regular_owners(&self, owner: &AccountOwner) -> bool {
230 self.owners.is_empty() && self.super_owners.contains(owner)
231 }
232}
233
234#[derive(Clone, Copy, Debug, Error, WitStore, WitType)]
237pub enum ManageChainError {
238 #[error("Unauthorized chain management operation")]
240 NotPermitted,
241}
242
243#[derive(Clone, Copy, Debug, Error, WitStore, WitType)]
246pub enum AccountPermissionError {
247 #[error("Unauthorized attempt to access account owned by {0}")]
249 NotPermitted(AccountOwner),
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255 use crate::crypto::{Ed25519SecretKey, Secp256k1SecretKey};
256
257 #[test]
258 fn test_ownership_round_timeouts() {
259 let super_pub_key = Ed25519SecretKey::generate().public();
260 let super_owner = AccountOwner::from(super_pub_key);
261 let pub_key = Secp256k1SecretKey::generate().public();
262 let owner = AccountOwner::from(pub_key);
263
264 let ownership = ChainOwnership {
265 super_owners: BTreeSet::from_iter([super_owner]),
266 owners: BTreeMap::from_iter([(owner, 100)]),
267 first_leader: Some(owner),
268 multi_leader_rounds: 10,
269 open_multi_leader_rounds: false,
270 timeout_config: TimeoutConfig {
271 fast_round_duration: Some(TimeDelta::from_secs(5)),
272 base_timeout: TimeDelta::from_secs(10),
273 timeout_increment: TimeDelta::from_secs(1),
274 fallback_duration: TimeDelta::from_secs(60 * 60),
275 },
276 };
277
278 assert_eq!(
279 ownership.round_timeout(Round::Fast),
280 Some(TimeDelta::from_secs(5))
281 );
282 assert_eq!(ownership.round_timeout(Round::MultiLeader(8)), None);
283 assert_eq!(
284 ownership.round_timeout(Round::MultiLeader(9)),
285 Some(TimeDelta::from_secs(10))
286 );
287 assert_eq!(
288 ownership.round_timeout(Round::SingleLeader(0)),
289 Some(TimeDelta::from_secs(10))
290 );
291 assert_eq!(
292 ownership.round_timeout(Round::SingleLeader(1)),
293 Some(TimeDelta::from_secs(11))
294 );
295 assert_eq!(
296 ownership.round_timeout(Round::SingleLeader(8)),
297 Some(TimeDelta::from_secs(18))
298 );
299 }
300}
301
302doc_scalar!(ChainOwnership, "Represents the owner(s) of a chain");