1
//! Functionality for encoding the inner document of an onion service descriptor.
2
//!
3
//! NOTE: `HsDescInner` is a private helper for building hidden service descriptors, and is
4
//! not meant to be used directly. Hidden services will use `HsDescBuilder` to build and encode
5
//! hidden service descriptors.
6

            
7
use crate::NetdocBuilder;
8
use crate::doc::hsdesc::IntroAuthType;
9
use crate::doc::hsdesc::IntroPointDesc;
10
use crate::doc::hsdesc::inner::HsInnerKwd;
11
use crate::doc::hsdesc::pow::PowParams;
12
use crate::doc::hsdesc::pow::v1::PowParamsV1;
13
use crate::encode::ItemArgument;
14
use crate::encode::NetdocEncoder;
15
use crate::types::misc::Iso8601TimeNoSp;
16

            
17
use rand::CryptoRng;
18
use rand::Rng;
19
use tor_bytes::{EncodeError, Writer};
20
use tor_cell::chancell::msg::HandshakeType;
21
use tor_cert::{CertType, CertifiedKey, Ed25519Cert};
22
use tor_error::internal;
23
use tor_error::{bad_api_usage, into_bad_api_usage};
24
use tor_llcrypto::pk::ed25519;
25
use tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_public;
26

            
27
use base64ct::{Base64, Encoding};
28
use tor_protover::Protocols;
29

            
30
use std::sync::LazyLock;
31
use std::time::SystemTime;
32

            
33
use smallvec::SmallVec;
34

            
35
/// The representation of the inner document of an onion service descriptor.
36
///
37
/// The plaintext format of this document is described in section 2.5.2.2. of rend-spec-v3.
38
#[derive(Debug)]
39
pub(super) struct HsDescInner<'a> {
40
    /// The descriptor signing key.
41
    pub(super) hs_desc_sign: &'a ed25519::Keypair,
42
    /// A list of recognized CREATE handshakes that this onion service supports.
43
    pub(super) create2_formats: &'a [HandshakeType],
44
    /// A list of authentication types that this onion service supports.
45
    pub(super) auth_required: Option<&'a SmallVec<[IntroAuthType; 2]>>,
46
    /// If true, this a "single onion service" and is not trying to keep its own location private.
47
    pub(super) is_single_onion_service: bool,
48
    /// One or more introduction points used to contact the onion service.
49
    pub(super) intro_points: &'a [IntroPointDesc],
50
    /// The expiration time of an introduction point authentication key certificate.
51
    pub(super) intro_auth_key_cert_expiry: SystemTime,
52
    /// The expiration time of an introduction point encryption key certificate.
53
    pub(super) intro_enc_key_cert_expiry: SystemTime,
54

            
55
    /// If present, a sendme increment and a set of FlowCtrl capabilities to
56
    /// advertise with it.
57
    ///
58
    /// If this is None, we don't advertise any flowctrl capabilities.
59
    ///
60
    /// For historical reasons, the protocols capabilities here are separate
61
    /// from `supported_protos`.    
62
    pub(super) flow_control: Option<&'a (Protocols, u8)>,
63

            
64
    /// If present, a set of subprotocol capabilities that we want to advertise.
65
    pub(super) protos: Protocols,
66

            
67
    /// Proof-of-work parameters
68
    #[cfg(feature = "hs-pow-full")]
69
    pub(super) pow_params: Option<&'a PowParams>,
70
}
71

            
72
/// Encode the pow-params line.
73
#[cfg(feature = "hs-pow-full")]
74
2
fn encode_pow_params(
75
2
    encoder: &mut NetdocEncoder,
76
2
    pow_params: &PowParamsV1,
77
2
) -> Result<(), EncodeError> {
78
2
    let mut pow_params_enc = encoder.item(HsInnerKwd::POW_PARAMS);
79
2
    pow_params_enc.add_arg(&"v1");
80

            
81
    // It's safe to call dangerously_into_parts here, since we encode the
82
    // expiration alongside the value.
83
2
    let (seed, (_, expiration)) = pow_params.seed().clone().dangerously_into_parts();
84

            
85
2
    seed.write_arg_onto(&mut pow_params_enc)?;
86

            
87
2
    pow_params
88
2
        .suggested_effort()
89
2
        .write_arg_onto(&mut pow_params_enc)?;
90

            
91
2
    let expiration = if let Some(expiration) = expiration {
92
2
        expiration
93
    } else {
94
        return Err(internal!("PoW seed should always have expiration").into());
95
    };
96

            
97
2
    Iso8601TimeNoSp::from(expiration).write_arg_onto(&mut pow_params_enc)?;
98

            
99
2
    Ok(())
100
2
}
101

            
102
impl<'a> NetdocBuilder for HsDescInner<'a> {
103
182
    fn build_sign<R: Rng + CryptoRng>(self, _: &mut R) -> Result<String, EncodeError> {
104
        use HsInnerKwd::*;
105

            
106
        let HsDescInner {
107
182
            hs_desc_sign,
108
182
            create2_formats,
109
182
            auth_required,
110
182
            is_single_onion_service,
111
182
            intro_points,
112
182
            intro_auth_key_cert_expiry,
113
182
            intro_enc_key_cert_expiry,
114
182
            flow_control,
115
182
            protos,
116
            #[cfg(feature = "hs-pow-full")]
117
182
            pow_params,
118
182
        } = self;
119

            
120
182
        let mut encoder = NetdocEncoder::new();
121

            
122
        {
123
182
            let mut create2_formats_enc = encoder.item(CREATE2_FORMATS);
124
194
            for fmt in create2_formats {
125
194
                let fmt: u16 = (*fmt).into();
126
194
                create2_formats_enc = create2_formats_enc.arg(&fmt);
127
194
            }
128
        }
129

            
130
        {
131
182
            if let Some(auth_required) = auth_required {
132
2
                let mut auth_required_enc = encoder.item(INTRO_AUTH_REQUIRED);
133
4
                for auth in auth_required {
134
4
                    auth_required_enc = auth_required_enc.arg(&auth.to_string());
135
4
                }
136
180
            }
137
        }
138

            
139
182
        if is_single_onion_service {
140
10
            encoder.item(SINGLE_ONION_SERVICE);
141
172
        }
142

            
143
182
        if let Some((fcp, inc)) = flow_control {
144
162
            let fcp = flowctrl_protocols(fcp);
145
162
            encoder.item(FLOW_CONTROL).arg(&fcp).arg(inc);
146
180
        }
147

            
148
182
        if !protos.is_empty() {
149
162
            encoder.item(PROTO).args_raw_string(&protos.to_string());
150
180
        }
151

            
152
        #[cfg(feature = "hs-pow-full")]
153
182
        if let Some(pow_params) = pow_params {
154
2
            match pow_params {
155
                #[cfg(feature = "hs-pow-full")]
156
2
                PowParams::V1(pow_params) => encode_pow_params(&mut encoder, pow_params)?,
157
                #[cfg(not(feature = "hs-pow-full"))]
158
                PowParams::V1(_) => {
159
                    return Err(internal!(
160
                        "Got a V1 PoW params but support for V1 is disabled."
161
                    ));
162
                }
163
            }
164
180
        }
165

            
166
        // We sort the introduction points here so as not to expose
167
        // detail about the order in which they were added, which might
168
        // be useful to an attacker somehow.  The choice of ntor
169
        // key is arbitrary; we could sort by anything, really.
170
        //
171
        // TODO SPEC: Either specify that we should sort by ntor key,
172
        // or sort by something else and specify that.
173
182
        let mut sorted_ip: Vec<_> = intro_points.iter().collect();
174
662
        sorted_ip.sort_by_key(|key| key.ipt_ntor_key.as_bytes());
175
502
        for intro_point in sorted_ip {
176
            // rend-spec-v3 0.4. "Protocol building blocks [BUILDING-BLOCKS]": the number of link
177
            // specifiers (NPSEC) must fit in a single byte.
178
502
            let nspec: u8 = intro_point
179
502
                .link_specifiers
180
502
                .len()
181
502
                .try_into()
182
502
                .map_err(into_bad_api_usage!("Too many link specifiers."))?;
183

            
184
500
            let mut link_specifiers = vec![];
185
500
            link_specifiers.write_u8(nspec);
186

            
187
1460
            for link_spec in &intro_point.link_specifiers {
188
1460
                link_specifiers.write(link_spec)?;
189
            }
190

            
191
500
            encoder
192
500
                .item(INTRODUCTION_POINT)
193
500
                .arg(&Base64::encode_string(&link_specifiers));
194
500
            encoder
195
500
                .item(ONION_KEY)
196
500
                .arg(&"ntor")
197
500
                .arg(&Base64::encode_string(&intro_point.ipt_ntor_key.to_bytes()));
198

            
199
            // For compatibility with c-tor, the introduction point authentication key is signed by
200
            // the descriptor signing key.
201
500
            let signed_auth_key = Ed25519Cert::builder()
202
500
                .cert_type(CertType::HS_IP_V_SIGNING)
203
500
                .expiration(intro_auth_key_cert_expiry)
204
500
                .signing_key(ed25519::Ed25519Identity::from(hs_desc_sign.verifying_key()))
205
500
                .cert_key(CertifiedKey::Ed25519((*intro_point.ipt_sid_key).into()))
206
500
                .encode_and_sign(hs_desc_sign)
207
500
                .map_err(into_bad_api_usage!("failed to sign the intro auth key"))?;
208

            
209
500
            encoder
210
500
                .item(AUTH_KEY)
211
500
                .object_bytes("ED25519 CERT", signed_auth_key.as_ref());
212

            
213
            // "The key is a base64 encoded curve25519 public key used to encrypt the introduction
214
            // request to service. (`KP_hss_ntor`)"
215
            //
216
            // TODO: The spec allows for multiple enc-key lines, but we currently only ever encode
217
            // a single one.
218
500
            encoder
219
500
                .item(ENC_KEY)
220
500
                .arg(&"ntor")
221
500
                .arg(&Base64::encode_string(
222
500
                    &intro_point.svc_ntor_key.as_bytes()[..],
223
500
                ));
224

            
225
            // The subject key is the ed25519 equivalent of the svc_ntor_key
226
            // curve25519 public encryption key, with its sign bit set to 0.
227
            //
228
            // (Setting the sign bit to zero has a 50% chance of making the
229
            // ed25519 public key useless for checking signatures, but that's
230
            // okay: since this cert is generated with its signing/subject keys
231
            // reversed (for compatibility reasons), we never actually generate
232
            // or check any signatures using this key.)
233
500
            let signbit = 0;
234
500
            let ed_svc_ntor_key =
235
500
                convert_curve25519_to_ed25519_public(&intro_point.svc_ntor_key, signbit)
236
500
                    .ok_or_else(|| {
237
                        bad_api_usage!("failed to convert curve25519 pk to ed25519 pk")
238
                    })?;
239

            
240
            // For compatibility with c-tor, the encryption key is signed with the descriptor
241
            // signing key.
242
500
            let signed_enc_key = Ed25519Cert::builder()
243
500
                .cert_type(CertType::HS_IP_CC_SIGNING)
244
500
                .expiration(intro_enc_key_cert_expiry)
245
500
                .signing_key(ed25519::Ed25519Identity::from(hs_desc_sign.verifying_key()))
246
500
                .cert_key(CertifiedKey::Ed25519(ed25519::Ed25519Identity::from(
247
500
                    &ed_svc_ntor_key,
248
500
                )))
249
500
                .encode_and_sign(hs_desc_sign)
250
500
                .map_err(into_bad_api_usage!(
251
                    "failed to sign the intro encryption key"
252
                ))?;
253

            
254
500
            encoder
255
500
                .item(ENC_KEY_CERT)
256
500
                .object_bytes("ED25519 CERT", signed_enc_key.as_ref());
257
        }
258

            
259
180
        encoder.finish().map_err(|e| e.into())
260
182
    }
261
}
262

            
263
/// Return a string encoding all of the `FlowCtrl` protocols in `p` that we should
264
/// encode in a `flow-control` item.
265
///
266
/// This is an inelegant function because the `flow-control` item pre-dates
267
/// the `proto` item by some time.  Don't make any more functions like this one!
268
/// Instead, put new subprotocol capabilities into the `proto` item.
269
4162
fn flowctrl_protocols(p: &Protocols) -> String {
270
    use tor_protover::ProtoKind;
271
    // We only encode FlowCtrl protocols 1-2 here.  If we decide that we would like to implement
272
    // more, we will decide later whether to advertise them in a flow-control line or in a 'proto'
273
    // line.
274
54
    static ALL_FLOWCTRL: LazyLock<Protocols> = LazyLock::new(|| {
275
54
        Protocols::from_kind_and_versions(ProtoKind::FlowCtrl, "1-2")
276
54
            .expect("Internal protocol list could not be parsed")
277
54
    });
278

            
279
4162
    ALL_FLOWCTRL
280
4162
        .intersection(p)
281
4162
        .to_string()
282
4162
        .strip_prefix("FlowCtrl=")
283
4162
        .expect("FlowCtrl protocols were not encoded correctly.")
284
4162
        .to_string()
285
4162
}
286

            
287
#[cfg(test)]
288
mod test {
289
    // @@ begin test lint list maintained by maint/add_warning @@
290
    #![allow(clippy::bool_assert_comparison)]
291
    #![allow(clippy::clone_on_copy)]
292
    #![allow(clippy::dbg_macro)]
293
    #![allow(clippy::mixed_attributes_style)]
294
    #![allow(clippy::print_stderr)]
295
    #![allow(clippy::print_stdout)]
296
    #![allow(clippy::single_char_pattern)]
297
    #![allow(clippy::unwrap_used)]
298
    #![allow(clippy::unchecked_time_subtraction)]
299
    #![allow(clippy::useless_vec)]
300
    #![allow(clippy::needless_pass_by_value)]
301
    #![allow(clippy::string_slice)] // See arti#2571
302
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
303

            
304
    use super::*;
305
    use crate::doc::hsdesc::IntroAuthType;
306
    use crate::doc::hsdesc::build::test::{create_intro_point_descriptor, expect_bug};
307
    use crate::doc::hsdesc::pow::v1::PowParamsV1;
308

            
309
    use smallvec::SmallVec;
310
    use std::net::Ipv4Addr;
311
    use std::time::UNIX_EPOCH;
312
    use tor_basic_utils::test_rng::Config;
313
    use tor_checkable::timed::TimerangeBound;
314
    #[cfg(feature = "hs-pow-full")]
315
    use tor_hscrypto::pow::v1::{Effort, Seed};
316
    use tor_linkspec::LinkSpec;
317

            
318
    /// Build an inner document using the specified parameters.
319
    fn create_inner_desc(
320
        create2_formats: &[HandshakeType],
321
        auth_required: Option<&SmallVec<[IntroAuthType; 2]>>,
322
        is_single_onion_service: bool,
323
        intro_points: &[IntroPointDesc],
324
        flow_control: Option<(Protocols, u8)>,
325
        protos: Protocols,
326
        pow_params: Option<&PowParams>,
327
    ) -> Result<String, EncodeError> {
328
        let hs_desc_sign = ed25519::Keypair::generate(&mut Config::Deterministic.into_rng());
329

            
330
        HsDescInner {
331
            hs_desc_sign: &hs_desc_sign,
332
            create2_formats,
333
            auth_required,
334
            is_single_onion_service,
335
            intro_points,
336
            intro_auth_key_cert_expiry: UNIX_EPOCH,
337
            intro_enc_key_cert_expiry: UNIX_EPOCH,
338
            flow_control: flow_control.as_ref(),
339
            protos,
340
            #[cfg(feature = "hs-pow-full")]
341
            pow_params,
342
        }
343
        .build_sign(&mut rand::rng())
344
    }
345

            
346
    #[test]
347
    fn inner_hsdesc_no_intro_auth() {
348
        // A descriptor for a "single onion service"
349
        let hs_desc = create_inner_desc(
350
            &[HandshakeType::NTOR], /* create2_formats */
351
            None,                   /* auth_required */
352
            true,                   /* is_single_onion_service */
353
            &[],                    /* intro_points */
354
            None,
355
            Default::default(),
356
            None,
357
        )
358
        .unwrap();
359

            
360
        assert_eq!(hs_desc, "create2-formats 2\nsingle-onion-service\n");
361

            
362
        // A descriptor for a location-hidden service
363
        let hs_desc = create_inner_desc(
364
            &[HandshakeType::NTOR], /* create2_formats */
365
            None,                   /* auth_required */
366
            false,                  /* is_single_onion_service */
367
            &[],                    /* intro_points */
368
            None,
369
            Default::default(),
370
            None,
371
        )
372
        .unwrap();
373

            
374
        assert_eq!(hs_desc, "create2-formats 2\n");
375

            
376
        let link_specs1 = &[LinkSpec::OrPort(Ipv4Addr::LOCALHOST.into(), 1234)];
377
        let link_specs2 = &[LinkSpec::OrPort(Ipv4Addr::LOCALHOST.into(), 5679)];
378
        let link_specs3 = &[LinkSpec::OrPort(Ipv4Addr::LOCALHOST.into(), 8901)];
379

            
380
        let mut rng = Config::Deterministic.into_rng();
381
        let intros = &[
382
            create_intro_point_descriptor(&mut rng, link_specs1),
383
            create_intro_point_descriptor(&mut rng, link_specs2),
384
            create_intro_point_descriptor(&mut rng, link_specs3),
385
        ];
386

            
387
        let hs_desc = create_inner_desc(
388
            &[
389
                HandshakeType::TAP,
390
                HandshakeType::NTOR,
391
                HandshakeType::NTOR_V3,
392
            ], /* create2_formats */
393
            None,   /* auth_required */
394
            false,  /* is_single_onion_service */
395
            intros, /* intro_points */
396
            None,
397
            Default::default(),
398
            None,
399
        )
400
        .unwrap();
401

            
402
        assert_eq!(
403
            hs_desc,
404
            r#"create2-formats 0 2 3
405
introduction-point AQAGfwAAASLF
406
onion-key ntor CJi8nDPhIFA7X9Q+oP7+jzxNo044cblmagk/d7oKWGc=
407
auth-key
408
-----BEGIN ED25519 CERT-----
409
AQkAAAAAAU4J4xGrMt9q5eHYZSmbOZTi1iKl59nd3ItYXAa/ASlRAQAgBACQKRtN
410
eNThmyleMYdmFucrbgPcZNDO6S81MZD1r7q61CGkJzc/ECYHzJeeAKIkRFV/6jr9
411
zAB5XnEFghZmXdDTQdqcPXAFydyeHWW4uR+Uii0wPI8VokbU0NoLTNYJGAM=
412
-----END ED25519 CERT-----
413
enc-key ntor TL7GcN+B++pB6eRN/0nBZGmWe125qh7ccQJ/Hhku+x8=
414
enc-key-cert
415
-----BEGIN ED25519 CERT-----
416
AQsAAAAAAabaCv4gv9ddyIztD1J8my9mgotmWnkHX94buLAtt15aAQAgBACQKRtN
417
eNThmyleMYdmFucrbgPcZNDO6S81MZD1r7q61GxlI6caS8iFp2bLmg1+Pkgij47f
418
eetKn+yDC5Q3eo/hJLDBGAQNOX7jFMdr9HjotjXIt6/Khfmg58CZC/gKhAw=
419
-----END ED25519 CERT-----
420
introduction-point AQAGfwAAAQTS
421
onion-key ntor HWIigEAdcOgqgHPDFmzhhkeqvYP/GcMT2fKb5JY6ey8=
422
auth-key
423
-----BEGIN ED25519 CERT-----
424
AQkAAAAAAZZVJwNlzVw1ZQGO7MTzC5MsySASd+fswAcjdTJJOifXAQAgBACQKRtN
425
eNThmyleMYdmFucrbgPcZNDO6S81MZD1r7q61IVW0XivcAKhvUvNUsU1CFznk3Mz
426
KSsp/mBoKi2iY4f4eN2SXx8U6pmnxnXFxYP6obi+tc5QWj1Jbfl1Aci3TAA=
427
-----END ED25519 CERT-----
428
enc-key ntor 9Upi9XNWyqx3ZwHeQ5r3+Dh116k+C4yHeE9BcM68HDc=
429
enc-key-cert
430
-----BEGIN ED25519 CERT-----
431
AQsAAAAAAcH+1K5m7pRnMc01mPp5AYVnJK1iZ/fKHwK0tVR/jtBvAQAgBACQKRtN
432
eNThmyleMYdmFucrbgPcZNDO6S81MZD1r7q61Hectpha37ioha85fpNt+/yDfebh
433
6BKUUQ0jf3SMXuNgX8SV9NSabn14WCSdKG/8RoYBCTR+yRJX0dy55mjg+go=
434
-----END ED25519 CERT-----
435
introduction-point AQAGfwAAARYv
436
onion-key ntor x/stThC6cVWJJUR7WERZj5VYVPTAOA/UDjHdtprJkiE=
437
auth-key
438
-----BEGIN ED25519 CERT-----
439
AQkAAAAAAVMhalzZJ8txKHuCX8TEhmO3LbCvDgV0zMT4eQ49SDpBAQAgBACQKRtN
440
eNThmyleMYdmFucrbgPcZNDO6S81MZD1r7q61GdVAiMag0dquEx4IywKDLEhxA7N
441
2RZFTS2QI+Sk3dyz46WO+epj1YBlgfOYCZlBEx+oFkRlUJdOc0Eu0sDlAw8=
442
-----END ED25519 CERT-----
443
enc-key ntor XI/a9NGh/7ClaFcKqtdI9DoP8da5ovwPDdgCHUr3xX0=
444
enc-key-cert
445
-----BEGIN ED25519 CERT-----
446
AQsAAAAAAZYGETSx12Og2xqJNMS9kGOHTEFeBkFPi7k0UaFv5HNKAQAgBACQKRtN
447
eNThmyleMYdmFucrbgPcZNDO6S81MZD1r7q61E8vxB5lB83+rQnWmHLzpfuMUZjG
448
o7Ct/ZB0j8YRB5lKSd07YAjA6Zo8kMnuZYX2Mb67TxWDQ/zlYJGOwLlj7A8=
449
-----END ED25519 CERT-----
450
"#
451
        );
452
    }
453

            
454
    #[test]
455
    fn inner_hsdesc_too_many_link_specifiers() {
456
        let link_spec = LinkSpec::OrPort(Ipv4Addr::LOCALHOST.into(), 9999);
457
        let link_specifiers =
458
            std::iter::repeat_n(link_spec, u8::MAX as usize + 1).collect::<Vec<_>>();
459

            
460
        let intros = &[create_intro_point_descriptor(
461
            &mut Config::Deterministic.into_rng(),
462
            &link_specifiers,
463
        )];
464

            
465
        // A descriptor for a location-hidden service with an introduction point with too many link
466
        // specifiers
467
        let err = create_inner_desc(
468
            &[HandshakeType::NTOR], /* create2_formats */
469
            None,                   /* auth_required */
470
            false,                  /* is_single_onion_service */
471
            intros,                 /* intro_points */
472
            None,
473
            Default::default(),
474
            None,
475
        )
476
        .unwrap_err();
477

            
478
        assert!(expect_bug(err).contains("Too many link specifiers."));
479
    }
480

            
481
    #[test]
482
    fn inner_hsdesc_intro_auth() {
483
        let mut rng = Config::Deterministic.into_rng();
484
        let link_specs = &[LinkSpec::OrPort(Ipv4Addr::LOCALHOST.into(), 8080)];
485
        let intros = &[create_intro_point_descriptor(&mut rng, link_specs)];
486
        let auth = SmallVec::from([IntroAuthType::Ed25519, IntroAuthType::Ed25519]);
487

            
488
        // A descriptor for a location-hidden service with 1 introduction points which requires
489
        // auth.
490
        let hs_desc = create_inner_desc(
491
            &[HandshakeType::NTOR], /* create2_formats */
492
            Some(&auth),            /* auth_required */
493
            false,                  /* is_single_onion_service */
494
            intros,                 /* intro_points */
495
            None,
496
            Default::default(),
497
            None,
498
        )
499
        .unwrap();
500

            
501
        assert_eq!(
502
            hs_desc,
503
            r#"create2-formats 2
504
intro-auth-required ed25519 ed25519
505
introduction-point AQAGfwAAAR+Q
506
onion-key ntor HWIigEAdcOgqgHPDFmzhhkeqvYP/GcMT2fKb5JY6ey8=
507
auth-key
508
-----BEGIN ED25519 CERT-----
509
AQkAAAAAAZZVJwNlzVw1ZQGO7MTzC5MsySASd+fswAcjdTJJOifXAQAgBACQKRtN
510
eNThmyleMYdmFucrbgPcZNDO6S81MZD1r7q61IVW0XivcAKhvUvNUsU1CFznk3Mz
511
KSsp/mBoKi2iY4f4eN2SXx8U6pmnxnXFxYP6obi+tc5QWj1Jbfl1Aci3TAA=
512
-----END ED25519 CERT-----
513
enc-key ntor 9Upi9XNWyqx3ZwHeQ5r3+Dh116k+C4yHeE9BcM68HDc=
514
enc-key-cert
515
-----BEGIN ED25519 CERT-----
516
AQsAAAAAAcH+1K5m7pRnMc01mPp5AYVnJK1iZ/fKHwK0tVR/jtBvAQAgBACQKRtN
517
eNThmyleMYdmFucrbgPcZNDO6S81MZD1r7q61Hectpha37ioha85fpNt+/yDfebh
518
6BKUUQ0jf3SMXuNgX8SV9NSabn14WCSdKG/8RoYBCTR+yRJX0dy55mjg+go=
519
-----END ED25519 CERT-----
520
"#
521
        );
522
    }
523

            
524
    #[test]
525
    #[cfg(feature = "hs-pow-full")]
526
    fn inner_hsdesc_pow_params() {
527
        use humantime::parse_rfc3339;
528

            
529
        let mut rng = Config::Deterministic.into_rng();
530
        let link_specs = &[LinkSpec::OrPort(Ipv4Addr::LOCALHOST.into(), 8080)];
531
        let intros = &[create_intro_point_descriptor(&mut rng, link_specs)];
532

            
533
        let pow_expiration = parse_rfc3339("1994-04-29T00:00:00Z").unwrap();
534
        let pow_params = PowParams::V1(PowParamsV1::new(
535
            TimerangeBound::new(Seed::from([0; 32]), ..pow_expiration),
536
            Effort::new(64),
537
        ));
538

            
539
        let hs_desc = create_inner_desc(
540
            &[HandshakeType::NTOR], /* create2_formats */
541
            None,                   /* auth_required */
542
            false,                  /* is_single_onion_service */
543
            intros,                 /* intro_points */
544
            None,
545
            Default::default(),
546
            Some(&pow_params),
547
        )
548
        .unwrap();
549

            
550
        assert!(hs_desc.contains(
551
            "\npow-params v1 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 64 1994-04-29T00:00:00\n"
552
        ));
553
    }
554

            
555
    #[test]
556
    fn inner_hsdesc_protos_flowctl() {
557
        let mut rng = Config::Deterministic.into_rng();
558
        let link_specs = &[LinkSpec::OrPort(Ipv4Addr::LOCALHOST.into(), 8080)];
559
        let intros = &[create_intro_point_descriptor(&mut rng, link_specs)];
560

            
561
        let protos = "Relay=1-20 Wombat=12 Link=4".parse().unwrap();
562
        let fcp = "FlowCtrl=1-6".parse().unwrap();
563
        let flow_control = Some((fcp, 33));
564

            
565
        let hs_desc = create_inner_desc(
566
            &[HandshakeType::NTOR],
567
            None,
568
            false,
569
            intros,
570
            flow_control,
571
            protos,
572
            None,
573
        )
574
        .unwrap();
575

            
576
        // Only FlowCtrl 1-2 can make it through.
577
        assert!(hs_desc.contains("\nflow-control 1-2 33\n"));
578
        // All declared protocols make it into the `proto` line.
579
        assert!(hs_desc.contains("\nproto Link=4 Relay=1-20 Wombat=12\n"));
580
    }
581
}