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 multi_leader_rounds: u32,
88 pub open_multi_leader_rounds: bool,
92 pub timeout_config: TimeoutConfig,
94}
95
96impl ChainOwnership {
97 pub fn single_super(owner: AccountOwner) -> Self {
99 ChainOwnership {
100 super_owners: iter::once(owner).collect(),
101 owners: BTreeMap::new(),
102 multi_leader_rounds: 5,
103 open_multi_leader_rounds: false,
104 timeout_config: TimeoutConfig::default(),
105 }
106 }
107
108 pub fn single(owner: AccountOwner) -> Self {
110 ChainOwnership {
111 super_owners: BTreeSet::new(),
112 owners: iter::once((owner, 100)).collect(),
113 multi_leader_rounds: 5,
114 open_multi_leader_rounds: false,
115 timeout_config: TimeoutConfig::default(),
116 }
117 }
118
119 pub fn multiple(
121 owners_and_weights: impl IntoIterator<Item = (AccountOwner, u64)>,
122 multi_leader_rounds: u32,
123 timeout_config: TimeoutConfig,
124 ) -> Self {
125 ChainOwnership {
126 super_owners: BTreeSet::new(),
127 owners: owners_and_weights.into_iter().collect(),
128 multi_leader_rounds,
129 open_multi_leader_rounds: false,
130 timeout_config,
131 }
132 }
133
134 #[cfg(with_testing)]
136 pub fn with_regular_owner(mut self, owner: AccountOwner, weight: u64) -> Self {
137 self.owners.insert(owner, weight);
138 self
139 }
140
141 pub fn is_active(&self) -> bool {
143 !self.super_owners.is_empty()
144 || !self.owners.is_empty()
145 || self.timeout_config.fallback_duration == TimeDelta::ZERO
146 }
147
148 pub fn verify_owner(&self, owner: &AccountOwner) -> bool {
150 self.super_owners.contains(owner) || self.owners.contains_key(owner)
151 }
152
153 pub fn can_propose_in_multi_leader_round(&self, owner: &AccountOwner) -> bool {
156 self.open_multi_leader_rounds
157 || self.owners.contains_key(owner)
158 || self.super_owners.contains(owner)
159 }
160
161 pub fn round_timeout(&self, round: Round) -> Option<TimeDelta> {
163 let tc = &self.timeout_config;
164 if round.is_fast() && self.owners.is_empty() {
165 return None; }
167 match round {
168 Round::Fast => tc.fast_round_duration,
169 Round::MultiLeader(r) if r.saturating_add(1) == self.multi_leader_rounds => {
170 Some(tc.base_timeout)
171 }
172 Round::MultiLeader(_) => None,
173 Round::SingleLeader(r) | Round::Validator(r) => {
174 let increment = tc.timeout_increment.saturating_mul(u64::from(r));
175 Some(tc.base_timeout.saturating_add(increment))
176 }
177 }
178 }
179
180 pub fn first_round(&self) -> Round {
182 if !self.super_owners.is_empty() {
183 Round::Fast
184 } else if self.owners.is_empty() {
185 Round::Validator(0)
186 } else if self.multi_leader_rounds > 0 {
187 Round::MultiLeader(0)
188 } else {
189 Round::SingleLeader(0)
190 }
191 }
192
193 pub fn all_owners(&self) -> impl Iterator<Item = &AccountOwner> {
195 self.super_owners.iter().chain(self.owners.keys())
196 }
197
198 pub fn next_round(&self, round: Round) -> Option<Round> {
200 let next_round = match round {
201 Round::Fast if self.multi_leader_rounds == 0 => Round::SingleLeader(0),
202 Round::Fast => Round::MultiLeader(0),
203 Round::MultiLeader(r) => r
204 .checked_add(1)
205 .filter(|r| *r < self.multi_leader_rounds)
206 .map_or(Round::SingleLeader(0), Round::MultiLeader),
207 Round::SingleLeader(r) => r
208 .checked_add(1)
209 .map_or(Round::Validator(0), Round::SingleLeader),
210 Round::Validator(r) => Round::Validator(r.checked_add(1)?),
211 };
212 Some(next_round)
213 }
214
215 pub fn is_super_owner_no_regular_owners(&self, owner: &AccountOwner) -> bool {
217 self.owners.is_empty() && self.super_owners.contains(owner)
218 }
219}
220
221#[derive(Clone, Copy, Debug, Error, WitStore, WitType)]
223pub enum CloseChainError {
224 #[error("Unauthorized attempt to close the chain")]
226 NotPermitted,
227}
228
229#[derive(Clone, Copy, Debug, Error, WitStore, WitType)]
231pub enum ChangeOwnershipError {
232 #[error("Unauthorized attempt to change the chain ownership")]
234 NotPermitted,
235}
236
237#[derive(Clone, Copy, Debug, Error, WitStore, WitType)]
239pub enum ChangeApplicationPermissionsError {
240 #[error("Unauthorized attempt to change the application permissions")]
242 NotPermitted,
243}
244
245#[derive(Clone, Copy, Debug, Error, WitStore, WitType)]
248pub enum AccountPermissionError {
249 #[error("Unauthorized attempt to access account owned by {0}")]
251 NotPermitted(AccountOwner),
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257 use crate::crypto::{Ed25519SecretKey, Secp256k1SecretKey};
258
259 #[test]
260 fn test_ownership_round_timeouts() {
261 let super_pub_key = Ed25519SecretKey::generate().public();
262 let super_owner = AccountOwner::from(super_pub_key);
263 let pub_key = Secp256k1SecretKey::generate().public();
264 let owner = AccountOwner::from(pub_key);
265
266 let ownership = ChainOwnership {
267 super_owners: BTreeSet::from_iter([super_owner]),
268 owners: BTreeMap::from_iter([(owner, 100)]),
269 multi_leader_rounds: 10,
270 open_multi_leader_rounds: false,
271 timeout_config: TimeoutConfig {
272 fast_round_duration: Some(TimeDelta::from_secs(5)),
273 base_timeout: TimeDelta::from_secs(10),
274 timeout_increment: TimeDelta::from_secs(1),
275 fallback_duration: TimeDelta::from_secs(60 * 60),
276 },
277 };
278
279 assert_eq!(
280 ownership.round_timeout(Round::Fast),
281 Some(TimeDelta::from_secs(5))
282 );
283 assert_eq!(ownership.round_timeout(Round::MultiLeader(8)), None);
284 assert_eq!(
285 ownership.round_timeout(Round::MultiLeader(9)),
286 Some(TimeDelta::from_secs(10))
287 );
288 assert_eq!(
289 ownership.round_timeout(Round::SingleLeader(0)),
290 Some(TimeDelta::from_secs(10))
291 );
292 assert_eq!(
293 ownership.round_timeout(Round::SingleLeader(1)),
294 Some(TimeDelta::from_secs(11))
295 );
296 assert_eq!(
297 ownership.round_timeout(Round::SingleLeader(8)),
298 Some(TimeDelta::from_secs(18))
299 );
300 }
301}
302
303doc_scalar!(ChainOwnership, "Represents the owner(s) of a chain");