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
//! Advertiser trait — manages SHIP/SLAP overlay advertisements.
//!
//! The Advertiser creates, discovers, and revokes advertisements that tell
//! other overlay nodes which topics/services this node supports.
//!
//! Ported from `~/bsv/overlay-services/src/Advertiser.ts`.
use async_trait::async_trait;
use crate::types::{Advertisement, AdvertisementData, Protocol, TaggedBEEF};
/// Manages SHIP and SLAP advertisements for an overlay node.
///
/// SHIP advertisements tell other nodes "I host topic X at URL Y".
/// SLAP advertisements tell other nodes "I provide lookup service X at URL Y".
///
/// The Engine calls `sync_advertisements()` to keep ads in sync with
/// configured topic managers and lookup services.
#[async_trait(?Send)]
pub trait Advertiser {
/// Create new advertisements for the given topics/services.
///
/// Returns a TaggedBEEF transaction containing the advertisement outputs.
/// The Engine will submit this transaction to the overlay.
async fn create_advertisements(
&self,
ads: &[AdvertisementData],
) -> Result<TaggedBEEF, AdvertiserError>;
/// Find all existing advertisements for the given protocol (SHIP or SLAP).
///
/// Queries the overlay to discover this node's own published advertisements.
async fn find_all_advertisements(
&self,
protocol: Protocol,
) -> Result<Vec<Advertisement>, AdvertiserError>;
/// Revoke existing advertisements by spending their UTXOs.
///
/// Returns a TaggedBEEF transaction that spends the advertisement outputs.
async fn revoke_advertisements(
&self,
advertisements: &[Advertisement],
) -> Result<TaggedBEEF, AdvertiserError>;
/// Parse an output script to extract an advertisement.
///
/// Used when processing transactions to identify advertisement outputs.
fn parse_advertisement(&self, output_script: &[u8]) -> Option<Advertisement>;
}
/// Errors from Advertiser operations.
#[derive(Debug, thiserror::Error)]
pub enum AdvertiserError {
/// Failed to create advertisement transaction.
#[error("creation failed: {0}")]
CreationFailed(String),
/// Failed to find advertisements.
#[error("lookup failed: {0}")]
LookupFailed(String),
/// Failed to revoke advertisements.
#[error("revocation failed: {0}")]
RevocationFailed(String),
/// Failed to parse advertisement from script.
#[error("parse failed: {0}")]
ParseFailed(String),
/// Generic error.
#[error("{0}")]
Other(String),
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use crate::types::Protocol;
/// Mock advertiser that tracks calls.
struct MockAdvertiser {
ads: std::sync::Mutex<Vec<Advertisement>>,
}
impl MockAdvertiser {
fn new() -> Self {
Self {
ads: std::sync::Mutex::new(Vec::new()),
}
}
}
#[async_trait(?Send)]
impl Advertiser for MockAdvertiser {
async fn create_advertisements(
&self,
ads: &[AdvertisementData],
) -> Result<TaggedBEEF, AdvertiserError> {
let topics: Vec<String> = ads
.iter()
.map(|a| match a.protocol {
Protocol::Ship => "tm_ship".to_string(),
Protocol::Slap => "tm_slap".to_string(),
})
.collect();
for ad in ads {
self.ads.lock().unwrap().push(Advertisement {
protocol: ad.protocol,
identity_key: "02mock".to_string(),
domain: "https://mock.example.com".to_string(),
topic_or_service: ad.topic_or_service_name.clone(),
beef: None,
output_index: None,
});
}
Ok(TaggedBEEF::new(vec![0x01], topics))
}
async fn find_all_advertisements(
&self,
protocol: Protocol,
) -> Result<Vec<Advertisement>, AdvertiserError> {
Ok(self
.ads
.lock()
.unwrap()
.iter()
.filter(|a| a.protocol == protocol)
.cloned()
.collect())
}
async fn revoke_advertisements(
&self,
advertisements: &[Advertisement],
) -> Result<TaggedBEEF, AdvertiserError> {
let mut ads = self.ads.lock().unwrap();
for ad in advertisements {
ads.retain(|a| a.topic_or_service != ad.topic_or_service);
}
Ok(TaggedBEEF::new(vec![0x02], vec![]))
}
fn parse_advertisement(&self, _output_script: &[u8]) -> Option<Advertisement> {
None
}
}
#[tokio::test]
async fn test_create_and_find_advertisements() {
let adv = MockAdvertiser::new();
let data = vec![
AdvertisementData {
protocol: Protocol::Ship,
topic_or_service_name: "tm_test".to_string(),
},
AdvertisementData {
protocol: Protocol::Slap,
topic_or_service_name: "ls_test".to_string(),
},
];
let beef = adv.create_advertisements(&data).await.unwrap();
assert_eq!(beef.topics.len(), 2);
let ship_ads = adv.find_all_advertisements(Protocol::Ship).await.unwrap();
assert_eq!(ship_ads.len(), 1);
assert_eq!(ship_ads[0].topic_or_service, "tm_test");
let slap_ads = adv.find_all_advertisements(Protocol::Slap).await.unwrap();
assert_eq!(slap_ads.len(), 1);
assert_eq!(slap_ads[0].topic_or_service, "ls_test");
}
#[tokio::test]
async fn test_revoke_advertisements() {
let adv = MockAdvertiser::new();
adv.create_advertisements(&[AdvertisementData {
protocol: Protocol::Ship,
topic_or_service_name: "tm_test".to_string(),
}])
.await
.unwrap();
let ads = adv.find_all_advertisements(Protocol::Ship).await.unwrap();
assert_eq!(ads.len(), 1);
adv.revoke_advertisements(&ads).await.unwrap();
let ads = adv.find_all_advertisements(Protocol::Ship).await.unwrap();
assert!(ads.is_empty());
}
#[tokio::test]
async fn test_advertiser_is_object_safe() {
let adv: Box<dyn Advertiser> = Box::new(MockAdvertiser::new());
let result = adv.find_all_advertisements(Protocol::Ship).await.unwrap();
assert!(result.is_empty());
}
}