forked from nervosnetwork/ckb
/
lib.rs
344 lines (295 loc) · 11.3 KB
/
lib.rs
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
// Shields clippy errors in generated bundled.rs
#![allow(clippy::unreadable_literal)]
mod template;
pub use self::template::{
TemplateContext, AVAILABLE_SPECS, DEFAULT_P2P_PORT, DEFAULT_RPC_PORT, DEFAULT_SPEC,
};
pub use std::io::{Error, Result};
use self::template::Template;
use std::borrow::Cow;
use std::fs;
use std::io::{self, BufReader, Read};
use std::path::{Path, PathBuf};
use tempfile::NamedTempFile;
include!(concat!(env!("OUT_DIR"), "/bundled.rs"));
pub const CKB_CONFIG_FILE_NAME: &str = "ckb.toml";
pub const MINER_CONFIG_FILE_NAME: &str = "ckb-miner.toml";
pub const SPECS_RESOURCE_DIR_NAME: &str = "specs/";
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Resource {
Bundled(String),
FileSystem(PathBuf),
}
impl Resource {
pub fn is_bundled(&self) -> bool {
match self {
Resource::Bundled(_) => true,
_ => false,
}
}
/// Gets resource content
pub fn get(&self) -> Result<Cow<'static, [u8]>> {
match self {
Resource::Bundled(key) => BUNDLED.get(key),
Resource::FileSystem(path) => {
let mut file = BufReader::new(fs::File::open(path)?);
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Ok(Cow::Owned(data))
}
}
}
/// Gets resource input stream
pub fn read(&self) -> Result<Box<dyn Read>> {
match self {
Resource::Bundled(key) => BUNDLED.read(key),
Resource::FileSystem(path) => Ok(Box::new(BufReader::new(fs::File::open(path)?))),
}
}
}
pub struct ResourceLocator {
root_dir: PathBuf,
}
impl ResourceLocator {
pub fn root_dir(&self) -> &Path {
self.root_dir.as_path()
}
/// Creates a ResourceLocator using `path` as root directory.
///
/// It returns error if the directory does not exists and current user has no permission to create it.
pub fn with_root_dir(root_dir: PathBuf) -> Result<ResourceLocator> {
fs::create_dir_all(&root_dir)?;
root_dir
.canonicalize()
.map(|root_dir| ResourceLocator { root_dir })
}
pub fn current_dir() -> Result<ResourceLocator> {
let root_dir = ::std::env::current_dir()?;
root_dir
.canonicalize()
.map(|root_dir| ResourceLocator { root_dir })
}
pub fn ckb(&self) -> Resource {
self.resolve(PathBuf::from(CKB_CONFIG_FILE_NAME)).unwrap()
}
pub fn miner(&self) -> Resource {
self.resolve(PathBuf::from(MINER_CONFIG_FILE_NAME)).unwrap()
}
/// Resolves a resource using a path.
///
/// The path may be absolute or relative. This function tries the file system first. If the file
/// is absent in the file system and it is relative, the function will search in the bundled files.
///
/// The relative path is relative to the resource root directory.
///
/// All the bundled files are assumed in the resource root directory.
///
/// It returns None when no resource with the path is found.
pub fn resolve(&self, path: PathBuf) -> Option<Resource> {
if path.is_absolute() {
return file_system(path);
}
file_system(self.root_dir.join(&path)).or_else(|| bundled(path))
}
/// Resolves a resource using a path as the path is refered in the resource `relative_to`.
///
/// This function is similar to [`ResourceLocator::resolve`]. The difference is how to resolve a relative path.
///
/// [`ResourceLocator::resolve`]: struct.ResourceLocator.html#method.open
///
/// The relative path is relative to the directory containing the resource `relative_to`.
///
/// For security reason, when `relative_to` is `Resource::Bundled`, the return value is either
/// `Some(Resource::Bundled)` or `None`. A bundled file is forbidden to reference a file in the
/// file system.
pub fn resolve_relative_to(&self, path: PathBuf, relative_to: &Resource) -> Option<Resource> {
match relative_to {
Resource::Bundled(key) => {
// Bundled file can only refer to bundled files.
let relative_start_dir = parent_dir(PathBuf::from(key)).join(&path);
bundled(relative_start_dir)
}
Resource::FileSystem(relative_to_path) => {
if path.is_absolute() {
return file_system(path);
}
let start_dir = parent_dir(relative_to_path.clone());
file_system(start_dir.join(&path)).or_else(|| {
start_dir
.strip_prefix(&self.root_dir)
.ok()
.and_then(|relative_start_dir| bundled(relative_start_dir.join(path)))
})
}
}
}
pub fn exported(&self) -> bool {
BUNDLED
.file_names()
.any(|name| self.root_dir.join(name).exists())
}
pub fn export_ckb<'a>(&self, context: &TemplateContext<'a>) -> Result<()> {
let ckb = Resource::Bundled(CKB_CONFIG_FILE_NAME.to_string());
let template = Template::new(from_utf8(ckb.get()?)?);
let mut out = NamedTempFile::new_in(&self.root_dir)?;
template.write_to(&mut out, context)?;
out.persist(self.root_dir.join(CKB_CONFIG_FILE_NAME))?;
Ok(())
}
pub fn export_miner<'a>(&self, context: &TemplateContext<'a>) -> Result<()> {
let miner = Resource::Bundled(MINER_CONFIG_FILE_NAME.to_string());
let template = Template::new(from_utf8(miner.get()?)?);
let mut out = NamedTempFile::new_in(&self.root_dir)?;
template.write_to(&mut out, context)?;
out.persist(self.root_dir.join(MINER_CONFIG_FILE_NAME))?;
Ok(())
}
pub fn export_specs(&self) -> Result<()> {
for name in BUNDLED.file_names() {
if name.starts_with(SPECS_RESOURCE_DIR_NAME) {
let path = self.root_dir.join(name);
fs::create_dir_all(path.parent().unwrap())?;
let mut out = NamedTempFile::new_in(&self.root_dir)?;
io::copy(&mut BUNDLED.read(name)?, &mut out)?;
out.into_temp_path().persist(path)?;
}
}
Ok(())
}
}
#[cfg(windows)]
fn path_as_key(path: &PathBuf) -> Cow<str> {
Cow::Owned(path.to_string_lossy().replace("\\", "/"))
}
#[cfg(not(windows))]
fn path_as_key(path: &PathBuf) -> Cow<str> {
path.to_string_lossy()
}
fn file_system(path: PathBuf) -> Option<Resource> {
path.canonicalize().ok().map(Resource::FileSystem)
}
fn bundled(path: PathBuf) -> Option<Resource> {
let key = path_as_key(&path);
if BUNDLED.is_available(&key) {
Some(Resource::Bundled(key.into_owned()))
} else {
None
}
}
fn parent_dir(mut path: PathBuf) -> PathBuf {
path.pop();
path
}
fn from_utf8(data: Cow<[u8]>) -> Result<String> {
String::from_utf8(data.to_vec()).map_err(|err| Error::new(io::ErrorKind::Other, err))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::{Path, PathBuf};
fn mkdir() -> tempfile::TempDir {
tempfile::Builder::new()
.prefix("ckb_resource_test")
.tempdir()
.unwrap()
}
fn touch<P: AsRef<Path>>(path: P) -> PathBuf {
fs::create_dir_all(path.as_ref().parent().unwrap()).expect("create dir in test");
fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.expect("touch file in test");
path.as_ref().canonicalize().expect("touch file in test")
}
#[test]
fn test_resource_locator_resolve() {
let dir = mkdir();
let spec_dev_path = touch(dir.path().join("specs/dev.toml"));
let locator = ResourceLocator::with_root_dir(dir.path().to_path_buf())
.expect("resource root dir exists");
assert_eq!(
locator.resolve("ckb.toml".into()),
Some(Resource::Bundled("ckb.toml".into()))
);
assert_eq!(
locator.resolve("specs/testnet.toml".into()),
Some(Resource::Bundled("specs/testnet.toml".into()))
);
assert_eq!(
locator.resolve("specs/dev.toml".into()),
Some(Resource::FileSystem(spec_dev_path.clone()))
);
assert_eq!(locator.resolve(dir.path().join("ckb.toml")), None);
assert_eq!(locator.resolve("x.toml".into()), None);
}
#[test]
fn test_resource_locator_resolve_relative_to() {
let dir = mkdir();
let spec_dev_path = touch(dir.path().join("specs/dev.toml"));
let always_success_path = touch(dir.path().join("specs/cells/always_success"));
let locator = ResourceLocator::with_root_dir(dir.path().to_path_buf())
.expect("resource root dir exists");
// Relative to Bundled("ckb.toml")
{
let ckb = Resource::Bundled("ckb.toml".into());
assert_eq!(
locator.resolve_relative_to("specs/dev.toml".into(), &ckb),
Some(Resource::Bundled("specs/dev.toml".into()))
);
assert_eq!(
locator.resolve_relative_to("specs/testnet.toml".into(), &ckb),
Some(Resource::Bundled("specs/testnet.toml".into()))
);
assert_eq!(locator.resolve_relative_to("x".into(), &ckb), None);
assert_eq!(
locator.resolve_relative_to(spec_dev_path.clone(), &ckb),
None,
);
}
// Relative to Bundled("specs/dev.toml")
{
let ckb = Resource::Bundled("specs/dev.toml".into());
assert_eq!(
locator.resolve_relative_to("cells/always_success".into(), &ckb),
Some(Resource::Bundled("specs/cells/always_success".into()))
);
assert_eq!(
locator.resolve_relative_to("cells/secp256k1_blake2b_sighash_all".into(), &ckb),
Some(Resource::Bundled(
"specs/cells/secp256k1_blake2b_sighash_all".into()
))
);
assert_eq!(locator.resolve_relative_to("x".into(), &ckb), None);
assert_eq!(
locator.resolve_relative_to(always_success_path.clone(), &ckb),
None,
);
}
// Relative to FileSystem("specs/dev.toml")
{
let spec_dev = Resource::FileSystem(spec_dev_path.clone());
assert_eq!(
locator.resolve_relative_to("cells/always_success".into(), &spec_dev),
Some(Resource::FileSystem(always_success_path.clone()))
);
assert_eq!(
locator
.resolve_relative_to("cells/secp256k1_blake2b_sighash_all".into(), &spec_dev),
Some(Resource::Bundled(
"specs/cells/secp256k1_blake2b_sighash_all".into()
))
);
assert_eq!(locator.resolve_relative_to("x".into(), &spec_dev), None);
assert_eq!(
locator.resolve_relative_to(always_success_path.clone(), &spec_dev),
Some(Resource::FileSystem(always_success_path.clone())),
);
assert_eq!(
locator.resolve_relative_to(dir.path().join("ckb.toml"), &spec_dev),
None,
);
}
}
}