iota-sdk 1.0.1

The IOTA SDK provides developers with a seamless experience to develop on IOTA by providing account abstractions and clients to interact with node APIs.
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
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

//! IOTA node MQTT API

mod error;
pub mod types;

use std::{sync::Arc, time::Instant};

use crypto::utils;
use log::warn;
use packable::PackableExt;
use rumqttc::{AsyncClient, Event, EventLoop, Incoming, MqttOptions, NetworkOptions, QoS, SubscribeFilter, Transport};
use tokio::sync::watch::Receiver as WatchReceiver;

pub use self::{error::Error, types::*};
use crate::{
    client::{Client, ClientInner},
    types::block::{
        payload::{milestone::ReceiptMilestoneOption, Payload},
        Block,
    },
};

impl Client {
    /// Returns a handle to the MQTT topics manager.
    pub fn subscriber(&self) -> MqttManager<'_> {
        MqttManager::new(self)
    }

    /// Subscribe to MQTT events with a callback.
    pub async fn subscribe<C: Fn(&TopicEvent) + Send + Sync + 'static>(
        &self,
        topics: impl IntoIterator<Item = Topic> + Send,
        callback: C,
    ) -> Result<(), Error> {
        MqttManager::new(self).with_topics(topics).subscribe(callback).await
    }

    /// Unsubscribe from MQTT events.
    pub async fn unsubscribe(&self, topics: impl IntoIterator<Item = Topic> + Send) -> Result<(), Error> {
        MqttManager::new(self).with_topics(topics).unsubscribe().await
    }
}

impl ClientInner {
    /// Returns the mqtt event receiver.
    pub async fn mqtt_event_receiver(&self) -> WatchReceiver<MqttEvent> {
        self.mqtt.receiver.read().await.clone()
    }
}

async fn set_mqtt_client(client: &Client) -> Result<(), Error> {
    // if the client was disconnected, we clear it so we can start over
    if *client.mqtt_event_receiver().await.borrow() == MqttEvent::Disconnected {
        *client.mqtt.client.write().await = None;
    }
    let exists = client.mqtt.client.read().await.is_some();

    if !exists {
        let node_manager = client.node_manager.read().await;
        let nodes = if !node_manager.ignore_node_health {
            #[cfg(not(target_family = "wasm"))]
            {
                node_manager
                    .healthy_nodes
                    .read()
                    .map_or(node_manager.nodes.clone(), |healthy_nodes| {
                        healthy_nodes.iter().map(|(node, _)| node.clone()).collect()
                    })
            }
            #[cfg(target_family = "wasm")]
            {
                client.node_manager.nodes.clone()
            }
        } else {
            node_manager.nodes.clone()
        };
        for node in &nodes {
            let host = node.url.host_str().expect("can't get host from URL");
            let mut entropy = [0u8; 8];
            utils::rand::fill(&mut entropy)?;
            let id = format!("iotasdk{}", prefix_hex::encode(entropy));
            let broker_options = client.mqtt.broker_options.read().await;
            let port = broker_options.port;
            let secure = node.url.scheme() == "https";
            let mqtt_options = if broker_options.use_ws {
                let uri = format!(
                    "{}://{host}:{}/api/mqtt/v1",
                    if secure { "wss" } else { "ws" },
                    node.url.port_or_known_default().unwrap_or(port)
                );
                let mut mqtt_options = MqttOptions::new(id, uri, port);
                if secure {
                    mqtt_options.set_transport(Transport::wss_with_default_config());
                } else {
                    mqtt_options.set_transport(Transport::ws());
                }
                mqtt_options
            } else {
                let uri = host.to_string();
                let mut mqtt_options = MqttOptions::new(id, uri, port);
                if secure {
                    mqtt_options.set_transport(Transport::tls_with_default_config());
                }
                mqtt_options
            };
            let (_, mut connection) = AsyncClient::new(mqtt_options.clone(), 10);
            connection
                .set_network_options(*NetworkOptions::new().set_connection_timeout(broker_options.timeout.as_secs()));
            // poll the event loop until we find a ConnAck event,
            // which means that the mqtt client is ready to be used on this host
            // if the event loop returns an error, we check the next node
            let mut got_ack = false;
            while let Ok(event) = connection.poll().await {
                if let Event::Incoming(Incoming::ConnAck(_)) = event {
                    got_ack = true;
                    break;
                }
            }

            // if we found a valid mqtt connection, loop it on a separate thread
            if got_ack {
                let (mqtt_client, connection) = AsyncClient::new(mqtt_options, 10);
                client.mqtt.client.write().await.replace(mqtt_client);
                poll_mqtt(client, connection);
            }
        }
    }
    Ok(())
}

fn poll_mqtt(client: &Client, mut event_loop: EventLoop) {
    let client = client.clone();
    std::thread::spawn(move || {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("failed to create Tokio runtime");
        runtime.block_on(async move {
            // rumqttc performs automatic reconnection since we keep running the event loop
            // but the subscriptions are lost on reconnection, so we need to resubscribe
            // the `is_subscribed` flag is set to false on event error, so the ConnAck event
            // can perform the re-subscriptions and reset `is_subscribed` to true.
            // we need the flag since the first ConnAck must be ignored.
            let mut is_subscribed = true;
            let mut error_instant = Instant::now();
            let mut connection_failure_count = 0;

            loop {
                let event = event_loop.poll().await;

                match event {
                    Ok(Event::Incoming(Incoming::ConnAck(_))) => {
                        let _ = client.mqtt.sender.read().await.send(MqttEvent::Connected);
                        if !is_subscribed {
                            is_subscribed = true;
                            // resubscribe topics
                            let topics = client
                                .inner
                                .mqtt
                                .topic_handlers
                                .read()
                                .await
                                .keys()
                                .map(|t| SubscribeFilter::new(t.as_str().to_owned(), QoS::AtLeastOnce))
                                .collect::<Vec<SubscribeFilter>>();
                            if !topics.is_empty() {
                                let _ = client
                                    .inner
                                    .mqtt
                                    .client
                                    .write()
                                    .await
                                    .as_mut()
                                    .unwrap()
                                    .subscribe_many(topics)
                                    .await;
                            }
                        }
                    }
                    Ok(Event::Incoming(Incoming::Publish(p))) => {
                        let client = client.clone();

                        crate::client::async_runtime::spawn(async move {
                            let mqtt_topic_handlers = client.mqtt.topic_handlers.read().await;

                            if let Some(handlers) = mqtt_topic_handlers.get(&Topic::new_unchecked(&p.topic)) {
                                let event = {
                                    if p.topic.contains("blocks") || p.topic.contains("included-block") {
                                        let payload = &*p.payload;
                                        let protocol_parameters = &client.network_info.read().await.protocol_parameters;

                                        match Block::unpack_verified(payload, protocol_parameters) {
                                            Ok(block) => Ok(TopicEvent {
                                                topic: p.topic.clone(),
                                                payload: MqttPayload::Block((&block).into()),
                                            }),
                                            Err(e) => {
                                                warn!("Block unpacking failed: {:?}", e);
                                                Err(())
                                            }
                                        }
                                    } else if p.topic.contains("milestones") {
                                        let payload = &*p.payload;
                                        let protocol_parameters = &client.network_info.read().await.protocol_parameters;

                                        match Payload::unpack_verified(payload, protocol_parameters) {
                                            Ok(Payload::Milestone(milestone)) => Ok(TopicEvent {
                                                topic: p.topic.clone(),
                                                payload: MqttPayload::MilestonePayload(milestone.as_ref().into()),
                                            }),
                                            Ok(p) => {
                                                warn!(
                                                    "'milestone' topic returned non-milestone payload, kind: {:?}",
                                                    p.kind()
                                                );
                                                Err(())
                                            }
                                            Err(e) => {
                                                warn!("MilestonePayload unpacking failed: {:?}", e);
                                                Err(())
                                            }
                                        }
                                    } else if p.topic.contains("receipts") {
                                        let payload = &*p.payload;
                                        let protocol_parameters = &client.network_info.read().await.protocol_parameters;

                                        match ReceiptMilestoneOption::unpack_verified(payload, protocol_parameters) {
                                            Ok(receipt) => Ok(TopicEvent {
                                                topic: p.topic.clone(),
                                                payload: MqttPayload::Receipt((&receipt).into()),
                                            }),
                                            Err(e) => {
                                                warn!("Receipt unpacking failed: {:?}", e);
                                                Err(())
                                            }
                                        }
                                    } else {
                                        match serde_json::from_slice(&p.payload) {
                                            Ok(value) => Ok(TopicEvent {
                                                topic: p.topic.clone(),
                                                payload: MqttPayload::Json(value),
                                            }),
                                            Err(e) => {
                                                warn!("Cannot parse JSON: {:?}", e);
                                                Err(())
                                            }
                                        }
                                    }
                                };
                                if let Ok(event) = event {
                                    for handler in handlers {
                                        handler(&event);
                                    }
                                };
                            }
                        });
                    }
                    Err(_) => {
                        if error_instant.elapsed().as_secs() < 5 {
                            connection_failure_count += 1;
                        } else {
                            connection_failure_count = 1;
                        }
                        if connection_failure_count == client.mqtt.broker_options.read().await.max_reconnection_attempts
                        {
                            let _ = client.mqtt.sender.read().await.send(MqttEvent::Disconnected);
                            break;
                        }
                        error_instant = Instant::now();
                        is_subscribed = false;
                    }
                    _ => {}
                }
            }
        });
    });
}

/// MQTT subscriber.
pub struct MqttManager<'a> {
    client: &'a Client,
}

impl<'a> MqttManager<'a> {
    /// Initializes a new instance of the mqtt subscriber.
    pub fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Add a new topic to the list.
    pub fn with_topic(self, topic: Topic) -> MqttTopicManager<'a> {
        MqttTopicManager::new(self.client).with_topic(topic)
    }

    /// Add a collection of topics to the list.
    pub fn with_topics(self, topics: impl IntoIterator<Item = Topic>) -> MqttTopicManager<'a> {
        MqttTopicManager::new(self.client).with_topics(topics)
    }

    /// Unsubscribes from all subscriptions.
    pub async fn unsubscribe(self) -> Result<(), Error> {
        MqttTopicManager::new(self.client).unsubscribe().await
    }

    /// Disconnects the broker.
    /// This will clear the stored topic handlers and close the MQTT connection.
    pub async fn disconnect(self) -> Result<(), Error> {
        if let Some(client) = &*self.client.mqtt.client.write().await {
            client.disconnect().await?;
            self.client.mqtt.topic_handlers.write().await.clear();
        }

        *self.client.mqtt.client.write().await = None;

        Ok(())
    }
}

/// The MQTT topic manager.
/// Subscribes and unsubscribes from topics.
pub struct MqttTopicManager<'a> {
    client: &'a Client,
    topics: Vec<Topic>,
}

impl<'a> MqttTopicManager<'a> {
    /// Initializes a new instance of the mqtt topic manager.
    fn new(client: &'a Client) -> Self {
        Self {
            client,
            topics: Vec::new(),
        }
    }

    /// Add a new topic to the list.
    pub fn with_topic(mut self, topic: Topic) -> Self {
        self.topics.push(topic);
        self
    }

    /// Add a collection of topics to the list.
    pub fn with_topics(mut self, topics: impl IntoIterator<Item = Topic>) -> Self {
        self.topics.extend(topics);
        self
    }

    /// Subscribe to the given topics with the callback.
    pub async fn subscribe<C: Fn(&crate::client::node_api::mqtt::TopicEvent) + Send + Sync + 'static>(
        self,
        callback: C,
    ) -> Result<(), Error> {
        let cb =
            Arc::new(Box::new(callback)
                as Box<
                    dyn Fn(&crate::client::node_api::mqtt::TopicEvent) + Send + Sync + 'static,
                >);
        set_mqtt_client(self.client).await?;
        self.client
            .inner
            .mqtt
            .client
            .write()
            .await
            .as_ref()
            .ok_or(Error::ConnectionNotFound)?
            .subscribe_many(
                self.topics
                    .iter()
                    .map(|t| SubscribeFilter::new(t.as_str().to_owned(), QoS::AtLeastOnce)),
            )
            .await?;
        {
            let mut mqtt_topic_handlers = self.client.mqtt.topic_handlers.write().await;
            for topic in self.topics {
                mqtt_topic_handlers.entry(topic).or_default().push(cb.clone());
            }
        }
        Ok(())
    }

    /// Unsubscribe from the given topics.
    /// If no topics were provided, the function will unsubscribe from every subscribed topic.
    pub async fn unsubscribe(self) -> Result<(), Error> {
        let topics = {
            let mqtt_topic_handlers = self.client.mqtt.topic_handlers.read().await;
            if self.topics.is_empty() {
                mqtt_topic_handlers.keys().cloned().collect()
            } else {
                self.topics
            }
        };

        if let Some(client) = &*self.client.mqtt.client.write().await {
            for topic in &topics {
                client.unsubscribe(topic.as_str()).await?;
            }
        }

        let empty_topic_handlers = {
            let mut mqtt_topic_handlers = self.client.mqtt.topic_handlers.write().await;
            for topic in topics {
                mqtt_topic_handlers.remove(&topic);
            }
            mqtt_topic_handlers.is_empty()
        };

        if self.client.mqtt.broker_options.read().await.automatic_disconnect && empty_topic_handlers {
            MqttManager::new(self.client).disconnect().await?;
        }

        Ok(())
    }
}