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
use std::collections::HashMap;

use rand_core::OsRng;

use ciphersuite::{
  group::{ff::Field, GroupEncoding},
  Ciphersuite, Ristretto,
};

use serai_primitives::{ExternalNetworkId, EXTERNAL_NETWORKS};

use dockertest::{
  PullPolicy, Image, LogAction, LogPolicy, LogSource, LogOptions, TestBodySpecification,
};

pub type MessageQueuePrivateKey = <Ristretto as Ciphersuite>::F;
pub fn instance() -> (
  MessageQueuePrivateKey,
  HashMap<ExternalNetworkId, MessageQueuePrivateKey>,
  TestBodySpecification,
) {
  serai_docker_tests::build("message-queue".to_string());

  let coord_key = <Ristretto as Ciphersuite>::F::random(&mut OsRng);
  let priv_keys = EXTERNAL_NETWORKS
    .into_iter()
    .map(|n| (n, <Ristretto as Ciphersuite>::F::random(&mut OsRng)))
    .collect::<HashMap<_, _>>();

  let composition = TestBodySpecification::with_image(
    Image::with_repository("serai-dev-message-queue").pull_policy(PullPolicy::Never),
  )
  .set_log_options(Some(LogOptions {
    action: LogAction::Forward,
    policy: LogPolicy::Always,
    source: LogSource::Both,
  }))
  .replace_env(
    [
      ("COORDINATOR_KEY".to_string(), hex::encode((Ristretto::generator() * coord_key).to_bytes())),
      (
        "BITCOIN_KEY".to_string(),
        hex::encode((Ristretto::generator() * priv_keys[&ExternalNetworkId::Bitcoin]).to_bytes()),
      ),
      (
        "ETHEREUM_KEY".to_string(),
        hex::encode((Ristretto::generator() * priv_keys[&ExternalNetworkId::Ethereum]).to_bytes()),
      ),
      (
        "MONERO_KEY".to_string(),
        hex::encode((Ristretto::generator() * priv_keys[&ExternalNetworkId::Monero]).to_bytes()),
      ),
      ("DB_PATH".to_string(), "./message-queue-db".to_string()),
      ("RUST_LOG".to_string(), "serai_message_queue=trace,".to_string()),
    ]
    .into(),
  )
  .set_publish_all_ports(true);

  (coord_key, priv_keys, composition)
}

#[test]
fn basic_functionality() {
  use zeroize::Zeroizing;

  use dockertest::DockerTest;

  use serai_message_queue::{Service, Metadata, client::MessageQueue};

  let mut test = DockerTest::new().with_network(dockertest::Network::Isolated);
  let (coord_key, priv_keys, composition) = instance();
  test.provide_container(composition);
  test.run(|ops| async move {
    tokio::time::timeout(core::time::Duration::from_secs(60), async move {
      // Sleep for a second for the message-queue to boot
      // It isn't an error to start immediately, it just silences an error
      tokio::time::sleep(core::time::Duration::from_secs(1)).await;

      let rpc = ops.handle("serai-dev-message-queue").host_port(2287).unwrap();
      let rpc = rpc.0.to_string() + ":" + &rpc.1.to_string();

      // Queue some messages
      let coordinator =
        MessageQueue::new(Service::Coordinator, rpc.clone(), Zeroizing::new(coord_key));
      coordinator
        .queue(
          Metadata {
            from: Service::Coordinator,
            to: Service::Processor(ExternalNetworkId::Bitcoin),
            intent: b"intent".to_vec(),
          },
          b"Hello, World!".to_vec(),
        )
        .await;

      // Queue this twice, which message-queue should de-duplicate
      for _ in 0 .. 2 {
        coordinator
          .queue(
            Metadata {
              from: Service::Coordinator,
              to: Service::Processor(ExternalNetworkId::Bitcoin),
              intent: b"intent 2".to_vec(),
            },
            b"Hello, World, again!".to_vec(),
          )
          .await;
      }

      // Successfully get it
      let bitcoin = MessageQueue::new(
        Service::Processor(ExternalNetworkId::Bitcoin),
        rpc.clone(),
        Zeroizing::new(priv_keys[&ExternalNetworkId::Bitcoin]),
      );
      let msg = bitcoin.next(Service::Coordinator).await;
      assert_eq!(msg.from, Service::Coordinator);
      assert_eq!(msg.id, 0);
      assert_eq!(&msg.msg, b"Hello, World!");

      // If we don't ack it, it should continue to be returned
      assert_eq!(msg, bitcoin.next(Service::Coordinator).await);

      // Acknowledging it should yield the next message
      bitcoin.ack(Service::Coordinator, 0).await;

      let next_msg = bitcoin.next(Service::Coordinator).await;
      assert!(msg != next_msg);
      assert_eq!(next_msg.from, Service::Coordinator);
      assert_eq!(next_msg.id, 1);
      assert_eq!(&next_msg.msg, b"Hello, World, again!");
      bitcoin.ack(Service::Coordinator, 1).await;

      // No further messages should be available
      tokio::time::timeout(core::time::Duration::from_secs(10), bitcoin.next(Service::Coordinator))
        .await
        .unwrap_err();

      // Queueing to a distinct processor should work, with a unique ID
      coordinator
        .queue(
          Metadata {
            from: Service::Coordinator,
            to: Service::Processor(ExternalNetworkId::Monero),
            // Intents should be per-from-to, making this valid
            intent: b"intent".to_vec(),
          },
          b"Hello, World!".to_vec(),
        )
        .await;

      let monero = MessageQueue::new(
        Service::Processor(ExternalNetworkId::Monero),
        rpc,
        Zeroizing::new(priv_keys[&ExternalNetworkId::Monero]),
      );
      assert_eq!(monero.next(Service::Coordinator).await.id, 0);
      monero.ack(Service::Coordinator, 0).await;
      tokio::time::timeout(core::time::Duration::from_secs(10), monero.next(Service::Coordinator))
        .await
        .unwrap_err();
    })
    .await
    .unwrap();
  });
}