keep_core/descriptor.rs
1// SPDX-FileCopyrightText: (C) 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4#![forbid(unsafe_code)]
5
6//! Shared text-level helpers for output descriptor strings.
7//!
8//! These helpers live in `keep-core` so that both `keep-bitcoin` (for
9//! normalization) and `keep-nip46` (for validation) can agree on how a
10//! single-path `/0/*` or `/1/*` tail is detected.
11
12/// Returns true if the descriptor body contains a terminating `/{digit}/*`
13/// derivation suffix, i.e. a `/{digit}/*` immediately followed by `)` or `,`.
14/// The guard `bytes[i - 1] != b'/'` only rejects a doubled slash `//{digit}/*`;
15/// nested paths like `xpub.../0/0/*)` also match at the trailing segment
16/// because that segment drives external/change derivation.
17pub fn contains_tail(body: &str, digit: char) -> bool {
18 let bytes = body.as_bytes();
19 let digit_byte = digit as u8;
20 let mut i = 0;
21 while i + 4 < bytes.len() {
22 if bytes[i] == b'/'
23 && bytes[i + 1] == digit_byte
24 && bytes[i + 2] == b'/'
25 && bytes[i + 3] == b'*'
26 && matches!(bytes[i + 4], b')' | b',')
27 && (i == 0 || bytes[i - 1] != b'/')
28 {
29 return true;
30 }
31 i += 1;
32 }
33 false
34}
35
36/// Rewrite every anchored `/0/*` tail (a `/0/*` followed by `)` or `,`, whose
37/// leading `/` is not itself preceded by another `/`) to `/<0;1>/*`. Works on
38/// byte indices but copies unchanged regions as UTF-8 slices so the output
39/// stays well-formed even if the input contains non-ASCII bytes.
40pub fn rewrite_trailing_zero_star(body: &str) -> String {
41 let bytes = body.as_bytes();
42 let mut out = String::with_capacity(body.len() + 8);
43 let mut i = 0;
44 let mut run_start = 0;
45 while i < bytes.len() {
46 if i + 4 < bytes.len()
47 && bytes[i] == b'/'
48 && bytes[i + 1] == b'0'
49 && bytes[i + 2] == b'/'
50 && bytes[i + 3] == b'*'
51 && matches!(bytes[i + 4], b')' | b',')
52 && (i == 0 || bytes[i - 1] != b'/')
53 {
54 if run_start < i {
55 out.push_str(&body[run_start..i]);
56 }
57 out.push_str("/<0;1>/*");
58 i += 4;
59 run_start = i;
60 } else {
61 i += 1;
62 }
63 }
64 if run_start < bytes.len() {
65 out.push_str(&body[run_start..]);
66 }
67 out
68}
69
70/// Rewrite every anchored `/0/*` tail to `/1/*`, using the same anchoring
71/// rules as [`rewrite_trailing_zero_star`] so nested paths and origin info
72/// are left alone. Used to derive an internal (change) descriptor from an
73/// external (receive) descriptor without touching unrelated `/0/*` substrings.
74pub fn rewrite_trailing_zero_to_one(body: &str) -> String {
75 let bytes = body.as_bytes();
76 let mut out = String::with_capacity(body.len());
77 let mut i = 0;
78 let mut run_start = 0;
79 while i < bytes.len() {
80 if i + 4 < bytes.len()
81 && bytes[i] == b'/'
82 && bytes[i + 1] == b'0'
83 && bytes[i + 2] == b'/'
84 && bytes[i + 3] == b'*'
85 && matches!(bytes[i + 4], b')' | b',')
86 && (i == 0 || bytes[i - 1] != b'/')
87 {
88 if run_start < i {
89 out.push_str(&body[run_start..i]);
90 }
91 out.push_str("/1/*");
92 i += 4;
93 run_start = i;
94 } else {
95 i += 1;
96 }
97 }
98 if run_start < bytes.len() {
99 out.push_str(&body[run_start..]);
100 }
101 out
102}
103
104/// Returns true if the descriptor body contains any BIP-389 multipath
105/// placeholder (`<0;1>` or `<1;0>`).
106pub fn has_multipath_marker(body: &str) -> bool {
107 body.contains("<0;1>") || body.contains("<1;0>")
108}
109
110/// Returns true if the descriptor body contains a terminating single-path
111/// `/0/*` or `/1/*` derivation suffix on any key expression.
112pub fn has_single_path_tail(body: &str) -> bool {
113 contains_tail(body, '0') || contains_tail(body, '1')
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 #[test]
121 fn contains_tail_matches_terminating_tail_of_deeper_path() {
122 // Deeper paths like /86'/0'/0'/0/* also terminate in /0/*; the final
123 // segment drives external/change derivation and must be flagged.
124 assert!(contains_tail("xpub.../0/0/*)", '0'));
125 }
126
127 #[test]
128 fn contains_tail_ignores_non_terminating_matches() {
129 // /0/*/ is not a tail (not followed by ')' or ','): do not match.
130 assert!(!contains_tail("xpub.../0/*/0/*)", '1'));
131 // /0 not followed by /* is not a tail.
132 assert!(!contains_tail("xpub.../0/1/*)", '0'));
133 }
134
135 #[test]
136 fn contains_tail_accepts_trailing() {
137 assert!(contains_tail("xpub.../0/*)", '0'));
138 assert!(contains_tail("xpub.../0/*,", '0'));
139 }
140
141 #[test]
142 fn rewrite_targets_the_terminating_segment() {
143 let input = "tr(xpub.../0/0/*)";
144 let out = rewrite_trailing_zero_star(input);
145 assert_eq!(out, "tr(xpub.../0/<0;1>/*)");
146 }
147
148 #[test]
149 fn rewrite_handles_multiple_keys() {
150 let input = "wsh(sortedmulti(2,xpub1/0/*,xpub2/0/*))";
151 let out = rewrite_trailing_zero_star(input);
152 assert_eq!(out, "wsh(sortedmulti(2,xpub1/<0;1>/*,xpub2/<0;1>/*))");
153 }
154
155 #[test]
156 fn rewrite_ignores_origin_info() {
157 let input = "tr([deadbeef/86'/0'/0']xpub.../0/*)";
158 let out = rewrite_trailing_zero_star(input);
159 assert_eq!(out, "tr([deadbeef/86'/0'/0']xpub.../<0;1>/*)");
160 }
161
162 #[test]
163 fn rewrite_zero_to_one_targets_terminating_segment() {
164 assert_eq!(
165 rewrite_trailing_zero_to_one("tr(xpub.../0/0/*)"),
166 "tr(xpub.../0/1/*)"
167 );
168 }
169
170 #[test]
171 fn rewrite_zero_to_one_ignores_origin_info() {
172 assert_eq!(
173 rewrite_trailing_zero_to_one("tr([deadbeef/86'/0'/0']xpub.../0/*)"),
174 "tr([deadbeef/86'/0'/0']xpub.../1/*)"
175 );
176 }
177
178 #[test]
179 fn rewrite_zero_to_one_handles_multiple_keys() {
180 assert_eq!(
181 rewrite_trailing_zero_to_one("wsh(sortedmulti(2,xpub1/0/*,xpub2/0/*))"),
182 "wsh(sortedmulti(2,xpub1/1/*,xpub2/1/*))"
183 );
184 }
185
186 // === #417 round 3: targeted unit tests killing the byte-scan mutants ===
187
188 /// `contains_tail` MUST reject the doubled-slash pattern `//{digit}/*)`.
189 /// A regression on the `i == 0 || bytes[i - 1] != b'/'` guard would let a
190 /// descriptor with a bogus `//0/*)` substring drive the rewrite path,
191 /// producing nonsense output. Both the i==0 boundary and the prior-byte
192 /// check are pinned here.
193 #[test]
194 fn contains_tail_rejects_doubled_slash() {
195 assert!(!contains_tail("xpub..//0/*)", '0'));
196 assert!(!contains_tail("xpub..//1/*)", '1'));
197 // ...but a single slash with the same shape DOES match.
198 assert!(contains_tail("xpub../0/*)", '0'));
199 }
200
201 /// The `i == 0` boundary in the prior-byte guard: a descriptor body
202 /// starting with the tail itself MUST match. Mutating the equality flips
203 /// every match through the prior-byte check, which underflows or matches
204 /// the wrong byte when `i == 0`.
205 #[test]
206 fn contains_tail_matches_at_position_zero() {
207 assert!(contains_tail("/0/*)", '0'));
208 assert!(contains_tail("/1/*,", '1'));
209 }
210
211 /// The trailing byte must be `)` or `,`. Any other character (including
212 /// space, end-of-string, or `/`) MUST NOT match, otherwise the rewrite
213 /// fires on arbitrary nested paths and the descriptor becomes malformed.
214 #[test]
215 fn contains_tail_requires_close_paren_or_comma_after_star() {
216 // The five-byte window is /0/*X; X must be ) or , .
217 assert!(!contains_tail("xpub.../0/* ", '0'));
218 assert!(!contains_tail("xpub.../0/*/", '0'));
219 assert!(!contains_tail("xpub.../0/*x", '0'));
220 // Exactly at end-of-string the next byte doesn't exist — loop
221 // condition `i + 4 < bytes.len()` excludes the last 4-byte window,
222 // so a body ending in `/0/*` with no trailing byte cannot match.
223 assert!(!contains_tail("/0/*", '0'));
224 }
225
226 /// `contains_tail` MUST NOT match a wrong digit. Pin `contains_tail("/0/*)", '1')`
227 /// → false and the reverse → true so a regression that ignores the digit
228 /// parameter (e.g. replaces `bytes[i + 1] == digit_byte` with `true`) is
229 /// caught.
230 #[test]
231 fn contains_tail_only_matches_the_requested_digit() {
232 assert!(!contains_tail("xpub.../0/*)", '1'));
233 assert!(!contains_tail("xpub.../1/*)", '0'));
234 // Both digits exist as terminating tails in the body; each call
235 // matches only its own.
236 let mixed = "wsh(sortedmulti(2,xpub1/0/*,xpub2/1/*))";
237 assert!(contains_tail(mixed, '0'));
238 assert!(contains_tail(mixed, '1'));
239 }
240
241 /// `rewrite_trailing_zero_star` MUST be the identity on inputs with no
242 /// terminating `/0/*` tail. A regression that always emits the rewrite
243 /// would corrupt unrelated descriptors and any input containing a `/1/*`
244 /// (the change descriptor) would lose its derivation tail.
245 #[test]
246 fn rewrite_trailing_zero_star_is_identity_when_no_match() {
247 // No /0/* tail at all.
248 assert_eq!(
249 rewrite_trailing_zero_star("tr(xpub.../1/*)"),
250 "tr(xpub.../1/*)"
251 );
252 // Empty body.
253 assert_eq!(rewrite_trailing_zero_star(""), "");
254 // Multipath marker already present.
255 let already = "tr(xpub.../<0;1>/*)";
256 assert_eq!(rewrite_trailing_zero_star(already), already);
257 // Doubled-slash pattern — anchoring rejects.
258 let doubled = "tr(xpub..//0/*)";
259 assert_eq!(rewrite_trailing_zero_star(doubled), doubled);
260 }
261
262 /// `rewrite_trailing_zero_star` preserves content before AND after the
263 /// matched tail. A regression that drops the `out.push_str(&body[run_start..i])`
264 /// would silently truncate the prefix; one that drops the trailing copy
265 /// after the loop would silently truncate the suffix. The input is
266 /// asymmetric on purpose: a distinctive origin-info prefix and a checksum
267 /// suffix flank a single rewrite, so dropping either copy fails uniquely.
268 #[test]
269 fn rewrite_trailing_zero_star_preserves_prefix_and_suffix() {
270 let input = "tr([deadbeef/86'/0'/0']xpub.../0/*)#abcd1234";
271 let out = rewrite_trailing_zero_star(input);
272 assert_eq!(out, "tr([deadbeef/86'/0'/0']xpub.../<0;1>/*)#abcd1234");
273 }
274
275 /// `rewrite_trailing_zero_to_one` is the identity on inputs without a
276 /// terminating `/0/*`. Same anchoring as `rewrite_trailing_zero_star`;
277 /// pin both functions independently in case the implementation diverges.
278 #[test]
279 fn rewrite_trailing_zero_to_one_is_identity_when_no_match() {
280 assert_eq!(
281 rewrite_trailing_zero_to_one("tr(xpub.../1/*)"),
282 "tr(xpub.../1/*)"
283 );
284 assert_eq!(rewrite_trailing_zero_to_one(""), "");
285 let doubled = "tr(xpub..//0/*)";
286 assert_eq!(rewrite_trailing_zero_to_one(doubled), doubled);
287 }
288
289 /// `has_multipath_marker` matches the exact `<0;1>` and `<1;0>` literals,
290 /// NOT partial forms. A regression that checks for `<` alone or just
291 /// `0;1` would let any descriptor with a stray `<` slip past the marker
292 /// gate and reach the rewrite path with a malformed shape.
293 #[test]
294 fn has_multipath_marker_requires_exact_literal() {
295 assert!(has_multipath_marker("tr(xpub.../<0;1>/*)"));
296 assert!(has_multipath_marker("tr(xpub.../<1;0>/*)"));
297
298 // Partial matches must not register.
299 assert!(!has_multipath_marker("tr(xpub.../0;1/*)"));
300 assert!(!has_multipath_marker("tr(xpub.../<0;/*)"));
301 assert!(!has_multipath_marker("tr(xpub.../0;1>/*)"));
302 // Empty body.
303 assert!(!has_multipath_marker(""));
304 // Non-matching substring.
305 assert!(!has_multipath_marker("tr(xpub.../0/*)"));
306 }
307
308 /// `has_single_path_tail` MUST return true if EITHER `/0/*` or `/1/*`
309 /// terminates the body. A regression that drops one of the two
310 /// `contains_tail` checks (e.g. swaps `||` for `&&`) would let one
311 /// digit slip past, defeating the gate's purpose.
312 #[test]
313 fn has_single_path_tail_matches_either_digit() {
314 assert!(has_single_path_tail("tr(xpub.../0/*)"));
315 assert!(has_single_path_tail("tr(xpub.../1/*)"));
316 // Multipath: neither single-path tail matches.
317 assert!(!has_single_path_tail("tr(xpub.../<0;1>/*)"));
318 // Empty body.
319 assert!(!has_single_path_tail(""));
320 }
321
322 /// The inner-window bound `i + 4 < bytes.len()` MUST stay strict. With
323 /// `<=`, an input of length exactly 4 (e.g. `"/0/*"`) would let the if
324 /// chain index `bytes[i + 4]` past the end, panicking the rewrite. Pin
325 /// both rewrite functions with a length-4 input so the mutation is
326 /// caught as a test panic.
327 #[test]
328 fn rewrite_handles_minimum_length_input_without_panicking() {
329 // The body "/0/*" is exactly the 4-byte tail with no trailing
330 // ')' or ',', so neither rewrite function should match. The
331 // `< → <=` mutation on the window bound would push past the
332 // end of the slice during the `matches!(bytes[i + 4], ...)`
333 // check and panic.
334 assert_eq!(rewrite_trailing_zero_star("/0/*"), "/0/*");
335 assert_eq!(rewrite_trailing_zero_to_one("/0/*"), "/0/*");
336 // Length-4 with a non-matching prefix — exercises the same
337 // boundary at i+4 == 4.
338 assert_eq!(rewrite_trailing_zero_star("xyzw"), "xyzw");
339 assert_eq!(rewrite_trailing_zero_to_one("xyzw"), "xyzw");
340 }
341}