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
use crate::request::{execute_get, CommonOptions, RequestError};
use crate::util::{make_url, str_to_bytes, URI_SKYNET_PREFIX};
use sp_std::{str, vec::Vec};
#[derive(Debug)]
pub enum PinError {
RequestError(RequestError),
Utf8Error(str::Utf8Error),
ValidationError(Vec<u8>),
}
impl From<RequestError> for PinError {
fn from(err: RequestError) -> Self {
Self::RequestError(err)
}
}
impl From<str::Utf8Error> for PinError {
fn from(err: str::Utf8Error) -> Self {
Self::Utf8Error(err)
}
}
#[derive(Debug)]
pub struct PinOptions<'a> {
pub common: CommonOptions<'a>,
pub endpoint_pin: &'a str,
}
impl Default for PinOptions<'_> {
fn default() -> Self {
Self {
common: Default::default(),
endpoint_pin: "/skynet/pin",
}
}
}
pub fn pin_skylink(skylink: &str, opts: Option<&PinOptions>) -> Result<Vec<u8>, PinError> {
let default = Default::default();
let opts = opts.unwrap_or(&default);
let skylink = if let Some(stripped) = skylink.strip_prefix(URI_SKYNET_PREFIX) {
stripped
} else {
skylink
};
let url = make_url(&[opts.common.portal_url, opts.endpoint_pin, skylink]);
let mut response = execute_get(str::from_utf8(&url)?, &opts.common)?;
let headers = response.headers();
let skylink = headers
.find("skynet-skylink")
.or_else(|| headers.find("Skynet-Skylink"));
if let Some(skylink) = skylink {
Ok(str_to_bytes(skylink))
} else {
Err(PinError::ValidationError(str_to_bytes(
"'skynet-skylink' header not found in response",
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_core::offchain::{testing, OffchainWorkerExt};
use sp_io::TestExternalities;
const DATA_LINK: &str = "MABdWWku6YETM2zooGCjQi26Rs4a6Hb74q26i-vMMcximQ";
#[test]
fn should_pin_data_link() {
let (offchain, state) = testing::TestOffchainExt::new();
let mut t = TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain));
state.write().expect_request(testing::PendingRequest {
method: "GET".into(),
uri: "https://siasky.net/skynet/pin/MABdWWku6YETM2zooGCjQi26Rs4a6Hb74q26i-vMMcximQ"
.into(),
response: Some(br#""#.to_vec()),
response_headers: vec![("Skynet-Skylink".to_owned(), DATA_LINK.to_owned())],
sent: true,
..Default::default()
});
t.execute_with(|| {
let skylink_returned = pin_skylink(DATA_LINK, None).unwrap();
assert_eq!(skylink_returned, str_to_bytes(DATA_LINK));
})
}
}