ping-rust 0.2.1

Menu-driven installer and manager for the shoes proxy server
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
use std::{
    collections::BTreeMap,
    net::{TcpListener, TcpStream, ToSocketAddrs},
    process::Stdio,
    time::{Duration, Instant},
};

use anyhow::{bail, Context, Result};
use base64::{
    engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD},
    Engine,
};
use percent_encoding::percent_decode_str;
use serde::{Deserialize, Serialize};
use url::Url;
use uuid::Uuid;

use crate::h2mux::H2MuxOptions;
use crate::utils;

mod state;
#[allow(unused_imports)]
pub use state::{
    ChainDefinition, ChainHop, ChainPool, ChainProxyChange, ChainProxyState, RouteTarget,
    RoutingRule,
};

const DEFAULT_PROXY_PROBE_URL: &str = "https://www.gstatic.com/generate_204";

fn validate_mask(mask: &str) -> Result<()> {
    if mask.is_empty() || mask.len() > 255 || mask.chars().any(char::is_control) {
        bail!("路由 mask 必须为 1..=255 字节且不能包含控制字符");
    }
    if let Some((ip, bits)) = mask.split_once('/') {
        let ip: std::net::IpAddr = ip.parse().context("CIDR 地址无效")?;
        let bits: u8 = bits.parse().context("CIDR 前缀无效")?;
        if bits > if ip.is_ipv4() { 32 } else { 128 } {
            bail!("CIDR 前缀超过地址长度");
        }
    }
    Ok(())
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ChainNode {
    pub id: Uuid,
    pub name: String,
    pub client: ShoesClientConfig,
    #[serde(default, skip_serializing_if = "H2MuxOptions::is_disabled")]
    pub h2mux: H2MuxOptions,
}

impl ChainNode {
    pub fn h2mux_eligible(&self) -> bool {
        self.client.protocol.validate_h2mux_eligibility().is_ok()
    }

    pub fn validate_h2mux(&self) -> Result<()> {
        self.h2mux.validate()?;
        if self.h2mux.enabled {
            self.client.protocol.validate_h2mux_eligibility()?;
        }
        Ok(())
    }

    pub fn shoes_value(&self) -> Result<serde_yaml::Value> {
        self.validate_h2mux()?;
        let mut value = serde_yaml::to_value(&self.client)?;
        if self.h2mux.enabled {
            self.client
                .protocol
                .insert_h2mux(&mut value["protocol"], self.h2mux.shoes_value()?)?;
        }
        Ok(value)
    }

    pub fn with_name(mut self, name: String) -> Result<Self> {
        validate_node_name(&name)?;
        self.name = name;
        Ok(self)
    }

    pub fn protocol_name(&self) -> &'static str {
        self.client.protocol.protocol_name()
    }

    pub fn address(&self) -> &str {
        &self.client.address
    }

    pub fn supports_udp_over_tcp(&self) -> bool {
        self.client.protocol.supports_udp_over_tcp()
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ShoesClientConfig {
    pub address: String,
    pub protocol: ShoesClientProtocol,
}

#[derive(Serialize)]
struct ProbeServer {
    address: String,
    protocol: ProbeSocksProtocol,
    rules: Vec<ProbeRule>,
}

#[derive(Serialize)]
struct ProbeSocksProtocol {
    #[serde(rename = "type")]
    kind: &'static str,
    udp_enabled: bool,
}

#[derive(Serialize)]
struct ProbeRule {
    masks: &'static str,
    action: &'static str,
    client_chains: serde_yaml::Value,
}

#[derive(Serialize)]
struct ChainProbeRule {
    masks: &'static str,
    action: &'static str,
    client_chains: serde_yaml::Value,
}

#[derive(Serialize)]
struct ChainProbeServer {
    address: String,
    protocol: ProbeSocksProtocol,
    rules: Vec<ChainProbeRule>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ShoesClientProtocol {
    Direct,
    Http {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        username: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        password: Option<String>,
    },
    Socks {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        username: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        password: Option<String>,
    },
    Shadowsocks {
        cipher: String,
        password: String,
        #[serde(default = "default_true")]
        udp_enabled: bool,
    },
    Vless {
        user_id: String,
        #[serde(default = "default_true")]
        udp_enabled: bool,
    },
    Vmess {
        cipher: String,
        user_id: String,
        #[serde(default = "default_true")]
        udp_enabled: bool,
    },
    Trojan {
        password: String,
    },
    Reality {
        public_key: String,
        short_id: String,
        sni_hostname: String,
        #[serde(default, skip_serializing_if = "is_false")]
        vision: bool,
        protocol: Box<ShoesClientProtocol>,
    },
    Tls {
        #[serde(default = "default_true")]
        verify: bool,
        sni_hostname: String,
        #[serde(default, skip_serializing_if = "is_false")]
        vision: bool,
        protocol: Box<ShoesClientProtocol>,
    },
    Websocket {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        matching_path: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        matching_headers: Option<BTreeMap<String, String>>,
        protocol: Box<ShoesClientProtocol>,
    },
}

impl ShoesClientProtocol {
    fn validate_h2mux_eligibility(&self) -> Result<()> {
        match self {
            Self::Vless { .. } | Self::Vmess { .. } | Self::Trojan { .. } => Ok(()),
            Self::Reality { vision: true, .. } | Self::Tls { vision: true, .. } => {
                bail!("H2MUX cannot be enabled with VLESS Vision")
            }
            Self::Reality { protocol, .. }
            | Self::Tls { protocol, .. }
            | Self::Websocket { protocol, .. } => protocol.validate_h2mux_eligibility(),
            _ => bail!("该链式节点协议不支持 H2MUX"),
        }
    }

    fn insert_h2mux(
        &self,
        value: &mut serde_yaml::Value,
        options: serde_yaml::Value,
    ) -> Result<()> {
        match self {
            Self::Vless { .. } | Self::Vmess { .. } | Self::Trojan { .. } => {
                value["h2mux"] = options;
                Ok(())
            }
            Self::Reality { protocol, .. }
            | Self::Tls { protocol, .. }
            | Self::Websocket { protocol, .. } => {
                protocol.insert_h2mux(&mut value["protocol"], options)
            }
            _ => bail!("该链式节点协议不支持 H2MUX"),
        }
    }

    fn protocol_name(&self) -> &'static str {
        match self {
            Self::Direct => "DIRECT",
            Self::Http { .. } => "HTTP",
            Self::Socks { .. } => "SOCKS5",
            Self::Shadowsocks { .. } => "Shadowsocks",
            Self::Vless { .. } => "VLESS",
            Self::Vmess { .. } => "VMess",
            Self::Trojan { .. } => "Trojan",
            Self::Reality { protocol, .. } => match protocol.as_ref() {
                Self::Vless { .. } => "VLESS-Reality",
                _ => "Reality",
            },
            Self::Tls { protocol, .. } => match protocol.as_ref() {
                Self::Websocket { protocol, .. } => match protocol.as_ref() {
                    Self::Vless { .. } => "VLESS-WS-TLS",
                    Self::Vmess { .. } => "VMess-WS-TLS",
                    Self::Trojan { .. } => "Trojan-WS-TLS",
                    _ => "WebSocket-TLS",
                },
                Self::Vless { .. } => "VLESS-TLS",
                Self::Trojan { .. } => "Trojan-TLS",
                Self::Http { .. } => "HTTPS",
                _ => "TLS",
            },
            Self::Websocket { protocol, .. } => protocol.protocol_name(),
        }
    }

    fn supports_udp_over_tcp(&self) -> bool {
        match self {
            Self::Direct => true,
            Self::Shadowsocks { udp_enabled, .. }
            | Self::Vless { udp_enabled, .. }
            | Self::Vmess { udp_enabled, .. } => *udp_enabled,
            // shoes 0.2.8 still leaves Trojan UDP client handling unimplemented.
            Self::Trojan { .. } => false,
            Self::Reality { protocol, .. }
            | Self::Tls { protocol, .. }
            | Self::Websocket { protocol, .. } => protocol.supports_udp_over_tcp(),
            Self::Http { .. } | Self::Socks { .. } => false,
        }
    }
}

fn default_true() -> bool {
    true
}

fn is_false(value: &bool) -> bool {
    !*value
}

pub fn parse_share_uri(input: &str) -> Result<ChainNode> {
    let input = input.trim();
    if input.is_empty() || input.len() > 8192 || input.chars().any(char::is_control) {
        bail!("分享链接不能为空、包含控制字符或超过 8192 字节");
    }
    let scheme = input
        .split_once("://")
        .map(|(scheme, _)| scheme.to_ascii_lowercase())
        .context("分享链接必须包含 ://")?;
    match scheme.as_str() {
        "hy2" | "hysteria2" => bail!("当前 shoes 内核不支持将 Hysteria2 作为链式代理出口"),
        "tuic" => bail!("当前 shoes 内核不支持将 TUIC 作为链式代理出口"),
        "wireguard" | "wg" | "warp" => {
            bail!("当前 shoes 内核不支持将 WireGuard/WARP 作为链式代理出口")
        }
        "socks" | "socks5" => parse_url_proxy(input, ProxyKind::Socks),
        "http" => parse_url_proxy(input, ProxyKind::Http),
        "https" => parse_url_proxy(input, ProxyKind::Https),
        "ss" => parse_shadowsocks(input),
        "vless" => parse_vless(input),
        "trojan" => parse_trojan(input),
        "vmess" => parse_vmess(input),
        "anytls" => bail!(
            "当前版本尚未启用 {} 分享链接导入;未验证的格式不会被近似转换",
            scheme
        ),
        _ => bail!("不支持的链式代理分享链接协议:{scheme}"),
    }
}

fn parse_vmess(input: &str) -> Result<ChainNode> {
    let encoded = input
        .strip_prefix("vmess://")
        .context("VMess 分享链接格式无效")?;
    let decoded = decode_base64_text(encoded).context("VMess 分享链接 Base64 无效")?;
    let value: serde_json::Value =
        serde_json::from_str(&decoded).context("VMess 分享链接 JSON 无效")?;
    let field = |key: &str| -> Result<&str> {
        value
            .get(key)
            .and_then(serde_json::Value::as_str)
            .with_context(|| format!("VMess 分享链接缺少 {key}"))
    };
    if value.get("v").and_then(serde_json::Value::as_u64) != Some(2)
        || !matches!(
            value.get("aid").and_then(serde_json::Value::as_u64),
            Some(0)
        )
        || !matches!(field("scy")?, "auto" | "")
        || field("net")? != "ws"
        || field("type")? != "none"
        || field("tls")? != "tls"
    {
        bail!("VMess 链式导入仅支持本项目的 AEAD + WebSocket + TLS 分享链接");
    }
    let user_id = field("id")?.to_owned();
    Uuid::parse_str(&user_id).context("VMess 用户 ID 必须是有效 UUID")?;
    let port = value
        .get("port")
        .and_then(serde_json::Value::as_u64)
        .or_else(|| {
            value
                .get("port")
                .and_then(serde_json::Value::as_str)
                .and_then(|text| text.parse::<u64>().ok())
        })
        .filter(|port| (1..=65535).contains(port))
        .context("VMess 端口必须在 1..=65535 范围内")?;
    let host = field("add")?;
    let url = Url::parse(&format!(
        "http://{}:{port}",
        if host.contains(':') {
            format!("[{host}]")
        } else {
            host.to_owned()
        }
    ))
    .context("VMess 服务器地址无效")?;
    let path = field("path")?;
    if !path.starts_with('/') || path.contains(['?', '#']) || path.chars().any(char::is_control) {
        bail!("VMess WebSocket 路径无效");
    }
    let ws_host = field("host")?;
    let sni = field("sni")?;
    if sni.is_empty() || sni.chars().any(char::is_control) || ws_host.chars().any(char::is_control)
    {
        bail!("VMess SNI 或 WebSocket Host 无效");
    }
    let insecure = field("insecure")?;
    let verify = match insecure {
        "0" => true,
        "1" => false,
        _ => bail!("VMess insecure 必须为 0 或 1"),
    };
    let protocol = ShoesClientProtocol::Tls {
        verify,
        sni_hostname: sni.to_owned(),
        vision: false,
        protocol: Box::new(ShoesClientProtocol::Websocket {
            matching_path: Some(path.to_owned()),
            matching_headers: (!ws_host.is_empty())
                .then(|| BTreeMap::from([("Host".to_owned(), ws_host.to_owned())])),
            protocol: Box::new(ShoesClientProtocol::Vmess {
                cipher: "any".to_owned(),
                user_id,
                udp_enabled: true,
            }),
        }),
    };
    let mut node = build_node(&url, protocol)?;
    if let Some(name) = value.get("ps").and_then(serde_json::Value::as_str) {
        if !name.trim().is_empty() {
            node = node.with_name(name.to_owned())?;
        }
    }
    Ok(node)
}

enum ProxyKind {
    Socks,
    Http,
    Https,
}

fn parse_url_proxy(input: &str, kind: ProxyKind) -> Result<ChainNode> {
    let url = Url::parse(input).context("代理分享链接格式无效")?;
    url_address(&url)?;
    let default_sni = url_host(&url)?.to_owned();
    let username = optional_decoded(url.username())?;
    let password = url.password().map(decode_component).transpose()?;
    let base = match kind {
        ProxyKind::Socks => ShoesClientProtocol::Socks { username, password },
        ProxyKind::Http | ProxyKind::Https => ShoesClientProtocol::Http { username, password },
    };
    let protocol = if matches!(kind, ProxyKind::Https) {
        ShoesClientProtocol::Tls {
            verify: !query_flag(&url, &["insecure", "allowinsecure"]),
            sni_hostname: query_value(&url, "sni").unwrap_or(default_sni),
            vision: false,
            protocol: Box::new(base),
        }
    } else {
        base
    };
    build_node(&url, protocol)
}

fn parse_shadowsocks(input: &str) -> Result<ChainNode> {
    let without_scheme = input
        .strip_prefix("ss://")
        .context("Shadowsocks 链接格式无效")?;
    let payload = without_scheme
        .split('#')
        .next()
        .unwrap_or(without_scheme)
        .split('?')
        .next()
        .unwrap_or(without_scheme);
    if !payload.contains('@') {
        let decoded = decode_base64_text(payload).context("Shadowsocks Base64 主体无效")?;
        let suffix = &without_scheme[payload.len()..];
        return parse_shadowsocks(&format!("ss://{decoded}{suffix}"));
    }

    let url = Url::parse(input).context("Shadowsocks 分享链接格式无效")?;
    if url.query_pairs().any(|(key, _)| key == "plugin") {
        bail!("当前 shoes 内核不支持 Shadowsocks SIP003 插件链式出口");
    }
    let raw_user = decode_component(url.username())?;
    let (cipher, password) = if let Some(password) = url.password() {
        (raw_user, decode_component(password)?)
    } else {
        let decoded = decode_base64_text(&raw_user).context("Shadowsocks 用户信息 Base64 无效")?;
        decoded
            .split_once(':')
            .map(|(cipher, password)| (cipher.to_owned(), password.to_owned()))
            .context("Shadowsocks 用户信息必须包含 加密方式:密码")?
    };
    validate_shadowsocks(&cipher, &password)?;
    let protocol = ShoesClientProtocol::Shadowsocks {
        cipher,
        password,
        udp_enabled: true,
    };
    build_node(&url, protocol)
}

fn parse_vless(input: &str) -> Result<ChainNode> {
    let url = Url::parse(input).context("VLESS 分享链接格式无效")?;
    let user_id = decode_component(url.username())?;
    Uuid::parse_str(&user_id).context("VLESS 用户 ID 必须是有效 UUID")?;
    let query = query_map(&url);
    if query.get("encryption").is_some_and(|value| value != "none") {
        bail!("VLESS encryption 只支持 none");
    }
    let transport = query.get("type").map(String::as_str).unwrap_or("tcp");
    let security = query.get("security").map(String::as_str).unwrap_or("none");
    let flow = query.get("flow").map(String::as_str).unwrap_or("");
    let vision = match flow {
        "" => false,
        "xtls-rprx-vision" => true,
        other => bail!("不支持的 VLESS flow:{other}"),
    };
    let mut protocol = ShoesClientProtocol::Vless {
        user_id,
        udp_enabled: true,
    };
    protocol = wrap_transport(protocol, transport, &query)?;
    protocol = match security {
        "none" => {
            if vision {
                bail!("VLESS Vision 必须搭配 TLS 或 Reality");
            }
            protocol
        }
        "tls" => {
            if vision && transport != "tcp" {
                bail!("VLESS Vision 只能搭配 TCP 传输");
            }
            ShoesClientProtocol::Tls {
                verify: !query_flag_map(&query, &["insecure", "allowinsecure"]),
                sni_hostname: required_sni(&url, &query)?,
                vision,
                protocol: Box::new(protocol),
            }
        }
        "reality" => {
            if transport != "tcp" {
                bail!("Reality 链式节点当前只支持 TCP 传输");
            }
            let public_key = query
                .get("pbk")
                .filter(|value| !value.is_empty())
                .cloned()
                .context("Reality 分享链接缺少 pbk 公钥")?;
            validate_reality_public_key(&public_key)?;
            let short_id = query.get("sid").cloned().unwrap_or_default();
            validate_reality_short_id(&short_id)?;
            ShoesClientProtocol::Reality {
                public_key,
                short_id,
                sni_hostname: required_sni(&url, &query)?,
                vision,
                protocol: Box::new(protocol),
            }
        }
        other => bail!("不支持的 VLESS security:{other}"),
    };
    build_node(&url, protocol)
}

fn parse_trojan(input: &str) -> Result<ChainNode> {
    let url = Url::parse(input).context("Trojan 分享链接格式无效")?;
    let password = decode_component(url.username())?;
    if password.is_empty() {
        bail!("Trojan 密码不能为空");
    }
    let query = query_map(&url);
    if query
        .get("security")
        .is_some_and(|value| !matches!(value.as_str(), "tls" | "reality"))
    {
        bail!("Trojan 链式节点只支持 TLS;不能把 security=none 近似转换为 TLS");
    }
    if query
        .get("security")
        .is_some_and(|value| value == "reality")
    {
        bail!("当前版本尚未验证 Trojan-Reality 分享链接导入");
    }
    let transport = query.get("type").map(String::as_str).unwrap_or("tcp");
    let protocol = wrap_transport(ShoesClientProtocol::Trojan { password }, transport, &query)?;
    let protocol = ShoesClientProtocol::Tls {
        verify: !query_flag_map(&query, &["insecure", "allowinsecure"]),
        sni_hostname: required_sni(&url, &query)?,
        vision: false,
        protocol: Box::new(protocol),
    };
    build_node(&url, protocol)
}

fn wrap_transport(
    protocol: ShoesClientProtocol,
    transport: &str,
    query: &BTreeMap<String, String>,
) -> Result<ShoesClientProtocol> {
    match transport {
        "tcp" => Ok(protocol),
        "ws" | "websocket" => {
            let path = query.get("path").cloned().unwrap_or_else(|| "/".to_owned());
            if !path.starts_with('/')
                || path.contains(['?', '#'])
                || path.chars().any(char::is_control)
            {
                bail!("WebSocket 路径必须以 / 开头,且不能包含 ?、# 或控制字符");
            }
            let headers = query
                .get("host")
                .filter(|host| !host.is_empty())
                .map(|host| BTreeMap::from([("Host".to_owned(), host.clone())]));
            Ok(ShoesClientProtocol::Websocket {
                matching_path: Some(path),
                matching_headers: headers,
                protocol: Box::new(protocol),
            })
        }
        other => bail!("当前链式代理不支持传输类型:{other}"),
    }
}

fn build_node(url: &Url, protocol: ShoesClientProtocol) -> Result<ChainNode> {
    let address = url_address(url)?;
    let name = url
        .fragment()
        .map(decode_component)
        .transpose()?
        .filter(|name| !name.trim().is_empty())
        .unwrap_or_else(|| {
            format!(
                "{}-{}",
                protocol.protocol_name().to_ascii_lowercase(),
                address
            )
        });
    validate_node_name(&name)?;
    Ok(ChainNode {
        id: Uuid::new_v4(),
        name,
        client: ShoesClientConfig { address, protocol },
        h2mux: H2MuxOptions::default(),
    })
}

fn url_address(url: &Url) -> Result<String> {
    let host = url_host(url)?;
    let port = url
        .port_or_known_default()
        .context("分享链接缺少服务器端口")?;
    if port == 0 {
        bail!("分享链接端口必须在 1..=65535 范围内");
    }
    Ok(if host.contains(':') {
        format!("[{host}]:{port}")
    } else {
        format!("{host}:{port}")
    })
}

fn url_host(url: &Url) -> Result<&str> {
    url.host_str().context("分享链接缺少服务器地址")
}

fn query_map(url: &Url) -> BTreeMap<String, String> {
    url.query_pairs()
        .map(|(key, value)| (key.to_ascii_lowercase(), value.into_owned()))
        .collect()
}

fn query_value(url: &Url, key: &str) -> Option<String> {
    url.query_pairs()
        .find(|(candidate, _)| candidate.eq_ignore_ascii_case(key))
        .map(|(_, value)| value.into_owned())
}

fn query_flag(url: &Url, keys: &[&str]) -> bool {
    query_flag_map(&query_map(url), keys)
}

fn query_flag_map(query: &BTreeMap<String, String>, keys: &[&str]) -> bool {
    keys.iter().any(|key| {
        query
            .get(*key)
            .is_some_and(|value| matches!(value.as_str(), "1" | "true" | "yes"))
    })
}

fn required_sni(url: &Url, query: &BTreeMap<String, String>) -> Result<String> {
    if let Some(server_name) = query
        .get("sni")
        .or_else(|| query.get("servername"))
        .filter(|value| !value.is_empty())
    {
        return Ok(server_name.clone());
    }
    url_host(url).map(ToOwned::to_owned)
}

fn validate_reality_public_key(public_key: &str) -> Result<()> {
    let decoded = URL_SAFE_NO_PAD
        .decode(public_key)
        .context("Reality pbk 必须是不带填充的 Base64URL")?;
    if decoded.len() != 32 {
        bail!("Reality pbk 解码后必须为 32 字节");
    }
    Ok(())
}

fn validate_reality_short_id(short_id: &str) -> Result<()> {
    if short_id.len() > 16
        || !short_id
            .chars()
            .all(|character| character.is_ascii_hexdigit())
    {
        bail!("Reality sid 必须是 0..=16 个十六进制字符");
    }
    Ok(())
}

fn optional_decoded(value: &str) -> Result<Option<String>> {
    if value.is_empty() {
        Ok(None)
    } else {
        decode_component(value).map(Some)
    }
}

fn decode_component(value: &str) -> Result<String> {
    percent_decode_str(value)
        .decode_utf8()
        .map(|value| value.into_owned())
        .context("分享链接包含无效的 UTF-8 转义")
}

fn decode_base64_text(value: &str) -> Result<String> {
    for engine in [&STANDARD, &STANDARD_NO_PAD, &URL_SAFE, &URL_SAFE_NO_PAD] {
        if let Ok(bytes) = engine.decode(value) {
            return String::from_utf8(bytes).context("Base64 解码结果不是 UTF-8");
        }
    }
    bail!("Base64 编码无效")
}

fn validate_shadowsocks(cipher: &str, password: &str) -> Result<()> {
    let expected_key_len = match cipher {
        "aes-128-gcm" | "aes-256-gcm" | "chacha20-ietf-poly1305" | "chacha20-poly1305" => None,
        "2022-blake3-aes-128-gcm" => Some(16),
        "2022-blake3-aes-256-gcm"
        | "2022-blake3-chacha20-ietf-poly1305"
        | "2022-blake3-chacha20-poly1305" => Some(32),
        _ => bail!("当前 shoes 内核不支持 Shadowsocks 加密方式:{cipher}"),
    };
    if password.is_empty() || password.chars().any(char::is_control) {
        bail!("Shadowsocks 密码不能为空或包含控制字符");
    }
    if let Some(expected) = expected_key_len {
        let decoded = STANDARD
            .decode(password)
            .context("Shadowsocks 2022 密码必须使用标准 Base64 编码")?;
        if decoded.len() != expected {
            bail!("{cipher} 密码解码后必须为 {expected} 字节");
        }
    }
    Ok(())
}

fn validate_node_name(name: &str) -> Result<()> {
    let name = name.trim();
    if name.is_empty() || name.len() > 64 || name.chars().any(char::is_control) {
        bail!("链式节点名称必须为 1..=64 个非控制字符");
    }
    Ok(())
}

fn probe_config(node: &ChainNode, port: u16) -> Result<String> {
    let servers = [ProbeServer {
        address: format!("127.0.0.1:{port}"),
        protocol: ProbeSocksProtocol {
            kind: "socks",
            udp_enabled: false,
        },
        rules: vec![ProbeRule {
            masks: "0.0.0.0/0",
            action: "allow",
            client_chains: node.shoes_value()?,
        }],
    }];
    serde_yaml::to_string(&servers).context("生成链式节点测试配置失败")
}

fn probe_chain_config(state: &ChainProxyState, chain_id: Uuid, port: u16) -> Result<String> {
    state.validate()?;
    let chain = state
        .chains
        .iter()
        .find(|chain| chain.id == chain_id)
        .with_context(|| format!("未找到 Chain {chain_id}"))?;
    let servers = [ChainProbeServer {
        address: format!("127.0.0.1:{port}"),
        protocol: ProbeSocksProtocol {
            kind: "socks",
            udp_enabled: false,
        },
        rules: vec![ChainProbeRule {
            masks: "0.0.0.0/0",
            action: "allow",
            client_chains: crate::config::chain_value(state, chain.id),
        }],
    }];
    serde_yaml::to_string(&servers).context("生成完整 Chain 测试配置失败")
}

fn reserve_loopback_port() -> Result<u16> {
    let listener = TcpListener::bind(("127.0.0.1", 0)).context("无法分配链式节点测试端口")?;
    listener
        .local_addr()
        .map(|address| address.port())
        .context("无法读取链式节点测试端口")
}

fn wait_for_loopback_port(port: u16, timeout: Duration) -> Result<()> {
    let address = ("127.0.0.1", port)
        .to_socket_addrs()
        .context("无法解析链式节点测试监听地址")?
        .next()
        .context("链式节点测试监听地址为空")?;
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if TcpStream::connect_timeout(&address, Duration::from_millis(100)).is_ok() {
            return Ok(());
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    bail!("临时 shoes 测试入口未能在限定时间内启动")
}

fn validate_probe_status(status: reqwest::StatusCode, node_name: &str) -> Result<()> {
    if status != reqwest::StatusCode::NO_CONTENT {
        bail!("完整代理请求返回 HTTP {status},期望 204 No Content;节点 {node_name} 不可用");
    }
    Ok(())
}

pub async fn test_proxy_handshake(node: &ChainNode, timeout: Duration) -> Result<Duration> {
    let port = reserve_loopback_port()?;
    test_proxy_yaml(&node.name, probe_config(node, port)?, port, timeout).await
}

/// Probe every member of a Pool in declaration order. Each member gets its own
/// temporary SOCKS5 entry; failures are collected so one offline node does not
/// hide the result of the remaining nodes.
pub async fn test_pool(
    state: &ChainProxyState,
    pool_id: Uuid,
    timeout: Duration,
) -> Result<Vec<PoolProbeResult>> {
    let pool = state
        .pools
        .iter()
        .find(|pool| pool.id == pool_id)
        .with_context(|| format!("未找到 Pool {pool_id}"))?;
    let mut results = Vec::with_capacity(pool.members.len());
    for member_id in &pool.members {
        let started = Instant::now();
        let Some(node) = state.nodes.iter().find(|node| node.id == *member_id) else {
            results.push(PoolProbeResult {
                node: member_id.to_string(),
                elapsed: started.elapsed(),
                error: Some("Pool 引用了不存在的节点".to_owned()),
            });
            continue;
        };
        match test_proxy_handshake(node, timeout).await {
            Ok(elapsed) => results.push(PoolProbeResult {
                node: node.name.clone(),
                elapsed,
                error: None,
            }),
            Err(error) => results.push(PoolProbeResult {
                node: node.name.clone(),
                elapsed: started.elapsed(),
                error: Some(format!("{error:#}")),
            }),
        }
    }
    Ok(results)
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PoolProbeResult {
    pub node: String,
    pub elapsed: Duration,
    pub error: Option<String>,
}

pub fn pool_probe_summary(results: &[PoolProbeResult]) -> String {
    results
        .iter()
        .map(|result| match &result.error {
            None => format!("{}: 可用 ({} ms)", result.node, result.elapsed.as_millis()),
            Some(error) => format!(
                "{}: 失败 ({error}; {} ms)",
                result.node,
                result.elapsed.as_millis()
            ),
        })
        .collect::<Vec<_>>()
        .join("\n")
}

pub async fn test_chain(
    state: &ChainProxyState,
    chain_id: Uuid,
    timeout: Duration,
) -> Result<Duration> {
    let name = state
        .chains
        .iter()
        .find(|chain| chain.id == chain_id)
        .with_context(|| format!("未找到 Chain {chain_id}"))?
        .name
        .clone();
    let port = reserve_loopback_port()?;
    test_proxy_yaml(
        &name,
        probe_chain_config(state, chain_id, port)?,
        port,
        timeout,
    )
    .await
}

async fn test_proxy_yaml(
    name: &str,
    yaml: String,
    port: u16,
    timeout: Duration,
) -> Result<Duration> {
    utils::require_linux_root()?;
    if !std::path::Path::new(utils::SHOES_BIN).is_file() {
        bail!("未找到 shoes:{}", utils::SHOES_BIN);
    }

    let directory = tempfile::tempdir().context("创建链式节点测试目录失败")?;
    let config_path = directory.path().join("probe.yaml");
    utils::atomic_write(&config_path, yaml.as_bytes(), 0o600)?;

    let dry_run = tokio::process::Command::new(utils::SHOES_BIN)
        .arg("--dry-run")
        .arg(&config_path)
        .output()
        .await
        .context("无法执行临时 shoes 配置校验")?;
    if !dry_run.status.success() {
        let error = String::from_utf8_lossy(&dry_run.stderr);
        bail!("shoes 拒绝链式节点测试配置:{}", error.trim());
    }

    let mut child = tokio::process::Command::new(utils::SHOES_BIN)
        .arg(&config_path)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .kill_on_drop(true)
        .spawn()
        .context("无法启动临时 shoes 节点测试进程")?;

    let result = async {
        tokio::task::spawn_blocking(move || wait_for_loopback_port(port, Duration::from_secs(3)))
            .await
            .context("等待临时 shoes 测试入口的任务异常退出")??;

        let probe_url = std::env::var("PING_RUST_CHAIN_TEST_URL")
            .unwrap_or_else(|_| DEFAULT_PROXY_PROBE_URL.to_owned());
        let proxy = reqwest::Proxy::all(format!("socks5h://127.0.0.1:{port}"))
            .context("创建链式节点测试代理失败")?;
        let client = reqwest::Client::builder()
            .proxy(proxy)
            .timeout(timeout)
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .context("创建链式节点测试客户端失败")?;
        let started = Instant::now();
        let response = client
            .get(&probe_url)
            .send()
            .await
            .with_context(|| format!("完整代理请求失败,{} 未通过协议握手", name))?;
        validate_probe_status(response.status(), name)?;
        Ok(started.elapsed())
    }
    .await;

    let _ = child.kill().await;
    let _ = child.wait().await;
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_socks_and_http_credentials() {
        let socks = parse_share_uri("socks5://alice:p%40ss@127.0.0.1:1080#edge").unwrap();
        assert_eq!(socks.name, "edge");
        assert_eq!(socks.address(), "127.0.0.1:1080");
        assert!(matches!(
            socks.client.protocol,
            ShoesClientProtocol::Socks {
                username: Some(ref user),
                password: Some(ref password)
            } if user == "alice" && password == "p@ss"
        ));
        assert!(!socks.supports_udp_over_tcp());

        let https = parse_share_uri("https://proxy.example.com:443?sni=edge.example.com").unwrap();
        assert!(matches!(
            https.client.protocol,
            ShoesClientProtocol::Tls { .. }
        ));
    }

    #[test]
    fn rejects_proxy_urls_without_a_server_address_without_panicking() {
        let error = parse_share_uri("socks5:///missing-host")
            .unwrap_err()
            .to_string();
        assert!(error.contains("服务器地址"), "{error}");
    }

    #[test]
    fn proxy_probe_requires_exactly_http_204() {
        validate_probe_status(reqwest::StatusCode::NO_CONTENT, "edge").unwrap();
        let error = validate_probe_status(reqwest::StatusCode::OK, "edge")
            .unwrap_err()
            .to_string();
        assert!(error.contains("HTTP 200"), "{error}");
        assert!(error.contains("204 No Content"), "{error}");
    }

    #[test]
    fn pool_probe_summary_reports_success_and_failure() {
        let results = vec![
            PoolProbeResult {
                node: "online".to_owned(),
                elapsed: Duration::from_millis(12),
                error: None,
            },
            PoolProbeResult {
                node: "offline".to_owned(),
                elapsed: Duration::from_millis(8),
                error: Some("连接超时".to_owned()),
            },
        ];
        let summary = pool_probe_summary(&results);
        assert!(summary.contains("online: 可用 (12 ms)"));
        assert!(summary.contains("offline: 失败 (连接超时; 8 ms)"));
    }

    #[tokio::test]
    async fn pool_probe_reports_missing_member_without_network() {
        let pool_id = Uuid::new_v4();
        let missing_id = Uuid::new_v4();
        let state = ChainProxyState {
            pools: vec![ChainPool {
                id: pool_id,
                name: "stale".to_owned(),
                members: vec![missing_id],
            }],
            ..ChainProxyState::default()
        };

        let results = test_pool(&state, pool_id, Duration::from_secs(1))
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].node, missing_id.to_string());
        assert_eq!(results[0].error.as_deref(), Some("Pool 引用了不存在的节点"));
    }

    #[test]
    fn parses_both_sip002_shadowsocks_forms() {
        let user = URL_SAFE_NO_PAD.encode("aes-128-gcm:secret");
        let first = parse_share_uri(&format!("ss://{user}@example.com:8388#ss-one")).unwrap();
        assert_eq!(first.protocol_name(), "Shadowsocks");

        let whole = URL_SAFE_NO_PAD.encode("aes-256-gcm:secret@example.com:8389");
        let second = parse_share_uri(&format!("ss://{whole}#whole-form")).unwrap();
        assert_eq!(second.address(), "example.com:8389");
        assert_eq!(second.name, "whole-form");
    }

    #[test]
    fn parses_vless_reality_and_trojan_websocket() {
        let public_key = URL_SAFE_NO_PAD.encode([7_u8; 32]);
        let vless = parse_share_uri(
            &format!("vless://b85798ef-e9dc-46a4-9a87-8da4499d36d0@example.com:443?security=reality&type=tcp&sni=www.cloudflare.com&pbk={public_key}&sid=0123456789abcdef&flow=xtls-rprx-vision#reality"),
        )
        .unwrap();
        assert_eq!(vless.protocol_name(), "VLESS-Reality");
        assert!(vless.supports_udp_over_tcp());

        let trojan = parse_share_uri(
            "trojan://secret@example.com:443?security=tls&type=ws&path=%2Fws&host=cdn.example.com&sni=example.com#trojan",
        )
        .unwrap();
        assert_eq!(trojan.protocol_name(), "Trojan-WS-TLS");
        assert!(!trojan.supports_udp_over_tcp());
    }

    #[test]
    fn rejects_unimplemented_outbounds_and_invalid_combinations() {
        for uri in [
            "hysteria2://secret@example.com:443",
            "tuic://id:secret@example.com:443",
            "wireguard://example.com:51820",
        ] {
            assert!(parse_share_uri(uri).is_err(), "accepted {uri}");
        }
        let invalid = "vless://b85798ef-e9dc-46a4-9a87-8da4499d36d0@example.com:443?security=reality&type=ws&sni=example.com&pbk=public";
        assert!(parse_share_uri(invalid).is_err());
        let invalid_public_key = "vless://b85798ef-e9dc-46a4-9a87-8da4499d36d0@example.com:443?security=reality&type=tcp&sni=example.com&pbk=short&sid=0123456789abcdef";
        assert!(parse_share_uri(invalid_public_key).is_err());
        let invalid_short_id = format!(
            "vless://b85798ef-e9dc-46a4-9a87-8da4499d36d0@example.com:443?security=reality&type=tcp&sni=example.com&pbk={}&sid=not-hex",
            URL_SAFE_NO_PAD.encode([7_u8; 32])
        );
        assert!(parse_share_uri(&invalid_short_id).is_err());
        assert!(parse_share_uri("trojan://secret@example.com:443?security=none&type=tcp").is_err());
    }

    #[test]
    fn node_h2mux_is_nested_at_proxy_protocol_and_old_nodes_default_off() {
        let mut node = parse_share_uri("vless://b85798ef-e9dc-46a4-9a87-8da4499d36d0@example.com:443?security=tls&type=ws&path=%2Fvless&sni=example.com#edge").unwrap();
        let old_json = serde_json::to_value(&node).unwrap();
        assert!(old_json.get("h2mux").is_none());
        let old: ChainNode = serde_json::from_value(old_json).unwrap();
        assert!(!old.h2mux.enabled);
        node.h2mux.enabled = true;
        let value = node.shoes_value().unwrap();
        let nested = &value["protocol"]["protocol"]["protocol"]["h2mux"];
        assert_eq!(nested["max_connections"].as_u64(), Some(4));
        assert_eq!(nested["padding"].as_bool(), Some(false));
        assert!(value["protocol"]["h2mux"].is_null());
        let saved = serde_json::to_vec(&node).unwrap();
        let restored: ChainNode = serde_json::from_slice(&saved).unwrap();
        assert_eq!(restored.h2mux, node.h2mux);
        let mut vision = parse_share_uri("vless://b85798ef-e9dc-46a4-9a87-8da4499d36d0@example.com:443?security=tls&type=tcp&flow=xtls-rprx-vision&sni=example.com#vision").unwrap();
        vision.h2mux.enabled = true;
        assert!(vision.shoes_value().is_err());
        let mut unsupported = parse_share_uri("socks5://127.0.0.1:1080#socks").unwrap();
        unsupported.h2mux.enabled = true;
        assert!(unsupported.shoes_value().is_err());
    }

    #[test]
    fn imports_only_supported_vmess_ws_tls_shape() {
        let payload = serde_json::json!({
            "v": 2, "ps": "vmess-edge", "add": "example.com", "port": 443,
            "id": "b85798ef-e9dc-46a4-9a87-8da4499d36d0", "aid": 0,
            "scy": "auto", "net": "ws", "type": "none", "host": "example.com",
            "path": "/vmess", "tls": "tls", "sni": "example.com", "insecure": "0"
        });
        let uri = format!("vmess://{}", STANDARD.encode(payload.to_string()));
        let mut node = parse_share_uri(&uri).unwrap();
        assert_eq!(node.name, "vmess-edge");
        assert_eq!(node.protocol_name(), "VMess-WS-TLS");
        node.h2mux.enabled = true;
        let rendered = node.shoes_value().unwrap();
        assert_eq!(
            rendered["protocol"]["protocol"]["protocol"]["h2mux"]["max_connections"].as_u64(),
            Some(4)
        );
        for (field, replacement) in [
            ("aid", serde_json::json!(1)),
            ("net", serde_json::json!("tcp")),
            ("tls", serde_json::json!("none")),
            ("insecure", serde_json::json!("maybe")),
        ] {
            let mut invalid = payload.clone();
            invalid[field] = replacement;
            let uri = format!("vmess://{}", STANDARD.encode(invalid.to_string()));
            assert!(parse_share_uri(&uri).is_err(), "accepted invalid {field}");
        }
    }

    #[test]
    fn state_selects_a_single_hop_default_and_protects_references() {
        let mut state = ChainProxyState::default();
        assert_eq!(state.default_route, RouteTarget::Direct);
        let node = parse_share_uri("socks5://127.0.0.1:1080#edge").unwrap();
        let id = node.id;
        state.apply(ChainProxyChange::Add(node)).unwrap();
        state.apply(ChainProxyChange::Select(id)).unwrap();
        state.apply(ChainProxyChange::SetEnabled(true)).unwrap();
        assert!(state.effective().is_some());
        assert!(state.apply(ChainProxyChange::Delete(id)).is_err());
        let RouteTarget::Chain(chain_id) = state.default_route else {
            panic!("expected selected chain")
        };
        state
            .apply(ChainProxyChange::SetDefault(RouteTarget::Direct))
            .unwrap();
        state
            .apply(ChainProxyChange::DeleteChain(chain_id))
            .unwrap();
        state.apply(ChainProxyChange::Delete(id)).unwrap();
    }

    #[test]
    fn proxy_probe_uses_the_selected_node_as_client_chain() {
        let node = parse_share_uri("socks5://alice:secret@127.0.0.1:1080#edge").unwrap();
        let yaml = probe_config(&node, 19080).unwrap();
        assert!(yaml.contains("address: 127.0.0.1:19080"));
        assert!(yaml.contains("client_chains:"));
        assert!(yaml.contains("address: 127.0.0.1:1080"));
        assert!(yaml.contains("username: alice"));
        assert!(yaml.contains("password: secret"));
    }

    #[test]
    fn chain_probe_contains_every_ordered_hop() {
        let first = parse_share_uri("socks5://127.0.0.1:1081#first").unwrap();
        let second = parse_share_uri("socks5://127.0.0.1:1082#second").unwrap();
        let chain = ChainDefinition {
            id: Uuid::new_v4(),
            name: "two hops".to_owned(),
            hops: vec![ChainHop::Node(first.id), ChainHop::Node(second.id)],
        };
        let state = ChainProxyState {
            nodes: vec![first, second],
            chains: vec![chain.clone()],
            ..ChainProxyState::default()
        };
        let yaml = probe_chain_config(&state, chain.id, 19080).unwrap();
        let first_offset = yaml.find("address: 127.0.0.1:1081").unwrap();
        let second_offset = yaml.find("address: 127.0.0.1:1082").unwrap();
        assert!(first_offset < second_offset);
        assert!(yaml.contains("chain:"));
    }
}