Skip to main content

linera_core/environment/wallet/
mod.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::ops::Deref;
5
6use futures::{Stream, StreamExt as _, TryStreamExt as _};
7use linera_base::{
8    crypto::CryptoHash,
9    data_types::{BlockHeight, ChainDescription, Epoch, Timestamp},
10    identifiers::{AccountOwner, ChainId},
11};
12
13use crate::{client::PendingProposal, data_types::ChainInfo};
14
15mod memory;
16pub use memory::Memory;
17
18/// The locally tracked state of a single chain.
19#[derive(Default, Clone, serde::Serialize, serde::Deserialize)]
20#[allow(missing_docs)]
21pub struct Chain {
22    pub owner: Option<AccountOwner>,
23    pub block_hash: Option<CryptoHash>,
24    pub next_block_height: BlockHeight,
25    pub timestamp: Timestamp,
26    pub pending_proposal: Option<PendingProposal>,
27    pub epoch: Option<Epoch>,
28}
29
30impl From<&ChainInfo> for Chain {
31    fn from(info: &ChainInfo) -> Self {
32        Self {
33            owner: None,
34            block_hash: info.block_hash,
35            next_block_height: info.next_block_height,
36            timestamp: info.timestamp,
37            pending_proposal: None,
38            epoch: Some(info.epoch),
39        }
40    }
41}
42
43impl From<ChainInfo> for Chain {
44    fn from(info: ChainInfo) -> Self {
45        Self::from(&info)
46    }
47}
48
49impl From<&ChainDescription> for Chain {
50    fn from(description: &ChainDescription) -> Self {
51        Self::new(None, description.config().epoch, description.timestamp())
52    }
53}
54
55impl From<ChainDescription> for Chain {
56    fn from(description: ChainDescription) -> Self {
57        (&description).into()
58    }
59}
60
61impl Chain {
62    /// Creates a chain that we haven't interacted with before.
63    pub fn new(owner: Option<AccountOwner>, current_epoch: Epoch, now: Timestamp) -> Self {
64        Self {
65            owner,
66            block_hash: None,
67            timestamp: now,
68            next_block_height: BlockHeight::ZERO,
69            pending_proposal: None,
70            epoch: Some(current_epoch),
71        }
72    }
73}
74
75/// A trait for the wallet (i.e. set of chain states) tracked by the client.
76#[cfg_attr(not(web), trait_variant::make(Send))]
77pub trait Wallet {
78    /// The error type returned by the wallet's operations.
79    type Error: std::error::Error + Send + Sync;
80    /// Returns the state of the chain with the given ID, if it is tracked.
81    async fn get(&self, id: ChainId) -> Result<Option<Chain>, Self::Error>;
82    /// Removes the chain with the given ID, returning its previous state if any.
83    async fn remove(&self, id: ChainId) -> Result<Option<Chain>, Self::Error>;
84    /// Returns a stream over all tracked chains and their states.
85    fn items(&self) -> impl Stream<Item = Result<(ChainId, Chain), Self::Error>>;
86    /// Inserts or replaces the state of the given chain, returning the previous state if any.
87    async fn insert(&self, id: ChainId, chain: Chain) -> Result<Option<Chain>, Self::Error>;
88    /// Inserts the given chain only if it is not already tracked, returning the existing state otherwise.
89    async fn try_insert(&self, id: ChainId, chain: Chain) -> Result<Option<Chain>, Self::Error>;
90
91    /// Modifies a chain in the wallet. Returns `Ok(None)` if the chain doesn't exist.
92    ///
93    /// The closure may be called more than once (e.g. on CAS contention), so it
94    /// must be idempotent. `Fn` (not `FnMut`) is required to discourage reliance
95    /// on mutable captured state.
96    async fn modify(
97        &self,
98        id: ChainId,
99        f: impl Fn(&mut Chain) + Send,
100    ) -> Result<Option<()>, Self::Error>;
101
102    /// Returns a stream over the IDs of all tracked chains.
103    fn chain_ids(&self) -> impl Stream<Item = Result<ChainId, Self::Error>> {
104        self.items().map(|result| result.map(|kv| kv.0))
105    }
106
107    /// Returns a stream over the IDs of the tracked chains that have an owner.
108    fn owned_chain_ids(&self) -> impl Stream<Item = Result<ChainId, Self::Error>> {
109        self.items()
110            .try_filter_map(|(id, chain)| async move { Ok(chain.owner.map(|_| id)) })
111    }
112}
113
114impl<W: Deref<Target: Wallet> + linera_base::util::traits::AutoTraits> Wallet for W {
115    type Error = <W::Target as Wallet>::Error;
116
117    async fn get(&self, id: ChainId) -> Result<Option<Chain>, Self::Error> {
118        self.deref().get(id).await
119    }
120
121    async fn remove(&self, id: ChainId) -> Result<Option<Chain>, Self::Error> {
122        self.deref().remove(id).await
123    }
124
125    fn items(&self) -> impl Stream<Item = Result<(ChainId, Chain), Self::Error>> {
126        self.deref().items()
127    }
128
129    async fn insert(&self, id: ChainId, chain: Chain) -> Result<Option<Chain>, Self::Error> {
130        self.deref().insert(id, chain).await
131    }
132
133    async fn try_insert(&self, id: ChainId, chain: Chain) -> Result<Option<Chain>, Self::Error> {
134        self.deref().try_insert(id, chain).await
135    }
136
137    fn chain_ids(&self) -> impl Stream<Item = Result<ChainId, Self::Error>> {
138        self.deref().chain_ids()
139    }
140
141    fn owned_chain_ids(&self) -> impl Stream<Item = Result<ChainId, Self::Error>> {
142        self.deref().owned_chain_ids()
143    }
144
145    async fn modify(
146        &self,
147        id: ChainId,
148        f: impl Fn(&mut Chain) + Send,
149    ) -> Result<Option<()>, Self::Error> {
150        self.deref().modify(id, f).await
151    }
152}