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
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{collections::HashSet, sync::Arc, time::Duration};

use async_trait::async_trait;
use futures::{
    future::{self, Either},
    lock::Mutex,
    StreamExt,
};
use linera_base::{
    crypto::AccountSecretKey,
    data_types::Timestamp,
    identifiers::{ChainId, Destination},
};
use linera_chain::data_types::OutgoingMessage;
use linera_core::{
    client::{ChainClient, ChainClientError},
    node::ValidatorNodeProvider,
    worker::Reason,
};
use linera_execution::{Message, SystemMessage};
use linera_storage::{Clock as _, Storage};
use tracing::{debug, error, info, instrument, warn, Instrument as _};

use crate::{wallet::Wallet, Error};

#[derive(Debug, Default, Clone, clap::Args)]
pub struct ChainListenerConfig {
    /// Do not create blocks automatically to receive incoming messages. Instead, wait for
    /// an explicit mutation `processInbox`.
    #[arg(
        long = "listener-skip-process-inbox",
        env = "LINERA_LISTENER_SKIP_PROCESS_INBOX"
    )]
    pub skip_process_inbox: bool,

    /// Wait before processing any notification (useful for testing).
    #[arg(
        long = "listener-delay-before-ms",
        default_value = "0",
        env = "LINERA_LISTENER_DELAY_BEFORE"
    )]
    pub delay_before_ms: u64,

    /// Wait after processing any notification (useful for rate limiting).
    #[arg(
        long = "listener-delay-after-ms",
        default_value = "0",
        env = "LINERA_LISTENER_DELAY_AFTER"
    )]
    pub delay_after_ms: u64,
}

type ContextChainClient<C> =
    ChainClient<<C as ClientContext>::ValidatorNodeProvider, <C as ClientContext>::Storage>;

#[cfg_attr(not(web), async_trait, trait_variant::make(Send))]
#[cfg_attr(web, async_trait(?Send))]
pub trait ClientContext: 'static {
    type ValidatorNodeProvider: ValidatorNodeProvider + Sync;
    type Storage: Storage + Clone + Send + Sync + 'static;

    fn wallet(&self) -> &Wallet;

    fn make_chain_client(&self, chain_id: ChainId) -> Result<ContextChainClient<Self>, Error>;

    async fn update_wallet_for_new_chain(
        &mut self,
        chain_id: ChainId,
        key_pair: Option<AccountSecretKey>,
        timestamp: Timestamp,
    ) -> Result<(), Error>;

    async fn update_wallet(&mut self, client: &ContextChainClient<Self>) -> Result<(), Error>;

    fn clients(&self) -> Result<Vec<ContextChainClient<Self>>, Error> {
        let mut clients = vec![];
        for chain_id in &self.wallet().chain_ids() {
            clients.push(self.make_chain_client(*chain_id)?);
        }
        Ok(clients)
    }
}

/// A `ChainListener` is a process that listens to notifications from validators and reacts
/// appropriately.
pub struct ChainListener {
    config: ChainListenerConfig,
    listening: Arc<Mutex<HashSet<ChainId>>>,
}

impl ChainListener {
    /// Creates a new chain listener given client chains.
    pub fn new(config: ChainListenerConfig) -> Self {
        Self {
            config,
            listening: Default::default(),
        }
    }

    /// Runs the chain listener.
    pub async fn run<C>(self, context: Arc<Mutex<C>>, storage: C::Storage)
    where
        C: ClientContext,
    {
        let chain_ids = context.lock().await.wallet().chain_ids();
        for chain_id in chain_ids {
            Self::run_with_chain_id(
                chain_id,
                context.clone(),
                storage.clone(),
                self.config.clone(),
                self.listening.clone(),
            );
        }
    }

    #[instrument(level = "trace", skip_all, fields(?chain_id))]
    fn run_with_chain_id<C>(
        chain_id: ChainId,
        context: Arc<Mutex<C>>,
        storage: C::Storage,
        config: ChainListenerConfig,
        listening: Arc<Mutex<HashSet<ChainId>>>,
    ) where
        C: ClientContext,
    {
        let _handle = linera_base::task::spawn(
            async move {
                if let Err(err) =
                    Self::run_client_stream(chain_id, context, storage, config, listening).await
                {
                    error!("Stream for chain {} failed: {}", chain_id, err);
                }
            }
            .in_current_span(),
        );
    }

    #[instrument(level = "trace", skip_all, fields(?chain_id))]
    async fn run_client_stream<C>(
        chain_id: ChainId,
        context: Arc<Mutex<C>>,
        storage: C::Storage,
        config: ChainListenerConfig,
        listening: Arc<Mutex<HashSet<ChainId>>>,
    ) -> Result<(), Error>
    where
        C: ClientContext,
    {
        let mut guard = listening.lock().await;
        if guard.contains(&chain_id) {
            // If we are already listening to notifications, there's nothing to do.
            // This can happen if we download a child before the parent
            // chain, and then process the OpenChain message in the parent.
            return Ok(());
        }
        guard.insert(chain_id);
        drop(guard);
        // If the client is not present, we can request it.
        let client = context.lock().await.make_chain_client(chain_id)?;
        let (listener, _listen_handle, mut local_stream) = client.listen().await?;
        client.synchronize_from_validators().await?;
        drop(linera_base::task::spawn(listener.in_current_span()));
        let mut timeout = storage.clock().current_time();
        loop {
            let sleep = Box::pin(storage.clock().sleep_until(timeout));
            let notification = match future::select(local_stream.next(), sleep).await {
                Either::Left((Some(notification), _)) => notification,
                Either::Left((None, _)) => break,
                Either::Right(((), _)) => {
                    timeout = Timestamp::from(u64::MAX);
                    if config.skip_process_inbox {
                        debug!("Not processing inbox due to listener configuration");
                        continue;
                    }
                    debug!("Processing inbox");
                    match client.process_inbox_without_prepare().await {
                        Err(ChainClientError::CannotFindKeyForChain(_)) => {}
                        Err(error) => warn!(%error, "Failed to process inbox."),
                        Ok((certs, None)) => {
                            info!("Done processing inbox. {} blocks created.", certs.len());
                        }
                        Ok((certs, Some(new_timeout))) => {
                            info!(
                                "{} blocks created. Will try processing the inbox later based \
                                 on the given round timeout: {new_timeout:?}",
                                certs.len(),
                            );
                            timeout = new_timeout.timestamp;
                        }
                    }
                    context.lock().await.update_wallet(&client).await?;
                    continue;
                }
            };
            info!("Received new notification: {:?}", notification);
            Self::maybe_sleep(config.delay_before_ms).await;
            match &notification.reason {
                Reason::NewIncomingBundle { .. } => timeout = storage.clock().current_time(),
                Reason::NewBlock { .. } | Reason::NewRound { .. } => {
                    if let Err(error) = client.update_validators(None).await {
                        warn!(
                            "Failed to update validators about the local chain after \
                            receiving notification {:?} with error: {:?}",
                            notification, error
                        );
                    }
                }
            }
            Self::maybe_sleep(config.delay_after_ms).await;
            let Reason::NewBlock { hash, .. } = notification.reason else {
                continue;
            };
            {
                context.lock().await.update_wallet(&client).await?;
            }
            let value = storage.read_hashed_confirmed_block(hash).await?;
            let block = value.inner().block();
            let new_chains = block
                .messages()
                .iter()
                .flatten()
                .filter_map(|outgoing_message| {
                    if let OutgoingMessage {
                        destination: Destination::Recipient(new_id),
                        message: Message::System(SystemMessage::OpenChain(open_chain_config)),
                        ..
                    } = outgoing_message
                    {
                        let owners = open_chain_config
                            .ownership
                            .all_owners()
                            .cloned()
                            .collect::<Vec<_>>();
                        let timestamp = block.header.timestamp;
                        Some((new_id, owners, timestamp))
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>();
            if new_chains.is_empty() {
                continue;
            }
            let mut context_guard = context.lock().await;
            for (new_id, owners, timestamp) in new_chains {
                let key_pair = owners
                    .iter()
                    .find_map(|owner| context_guard.wallet().key_pair_for_owner(owner));
                if key_pair.is_some() {
                    context_guard
                        .update_wallet_for_new_chain(*new_id, key_pair, timestamp)
                        .await?;
                    Self::run_with_chain_id(
                        *new_id,
                        context.clone(),
                        storage.clone(),
                        config.clone(),
                        listening.clone(),
                    );
                }
            }
        }
        Ok(())
    }

    async fn maybe_sleep(delay_ms: u64) {
        if delay_ms > 0 {
            linera_base::time::timer::sleep(Duration::from_millis(delay_ms)).await;
        }
    }
}