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
use crate::errors::{ParsePhoneNumberError, ParsePhoneNumberPrefixError};
use perro::ensure;
use phonenumber::country::Id as CountryCode;
use phonenumber::metadata::DATABASE;
use phonenumber::ParseError;

#[derive(PartialEq, Debug)]
pub struct PhoneNumber {
    pub e164: String,
    pub country_code: CountryCode,
}

impl PhoneNumber {
    pub(crate) fn parse(number: &str) -> Result<Self, ParsePhoneNumberError> {
        let number = match phonenumber::parse(None, number) {
            Ok(number) => number,
            Err(ParseError::InvalidCountryCode) => {
                return Err(ParsePhoneNumberError::MissingCountryCode)
            }
            Err(_) => return Err(ParsePhoneNumberError::ParsingError),
        };
        ensure!(number.is_valid(), ParsePhoneNumberError::InvalidPhoneNumber);

        let e164 = number.format().mode(phonenumber::Mode::E164).to_string();
        let country_code = number
            .country()
            .id()
            .ok_or(ParsePhoneNumberError::InvalidCountryCode)?;
        Ok(Self { e164, country_code })
    }

    pub(crate) fn to_lightning_address(&self, domain: &str) -> String {
        self.e164.replacen('+', "-", 1) + domain
    }
}

pub(crate) fn lightning_address_to_phone_number(address: &str, domain: &str) -> Option<String> {
    let username = address
        .strip_prefix('-')
        .and_then(|s| s.strip_suffix(domain));
    if let Some(username) = username {
        if username.chars().all(|c| char::is_ascii_digit(&c)) {
            return Some(format!("+{username}"));
        }
    }
    None
}

pub(crate) struct PhoneNumberPrefixParser {
    allowed_country_codes: Vec<String>,
}

impl PhoneNumberPrefixParser {
    pub fn new(allowed_countries_iso_3166_1_alpha_2: &[String]) -> Self {
        // Stricly speaking *ISO 3166-1 alpha-2* is not the same as *CLDR country IDs*
        // and such conversion is not correct, but for the most contries such codes match.
        let allowed_country_codes = allowed_countries_iso_3166_1_alpha_2
            .iter()
            .flat_map(|id| DATABASE.by_id(id))
            .map(|m| m.country_code().to_string())
            .collect::<Vec<_>>();
        Self {
            allowed_country_codes,
        }
    }

    pub fn parse(&self, prefix: &str) -> Result<(), ParsePhoneNumberPrefixError> {
        match parser::parse_phone_number(prefix) {
            Ok(digits) => {
                if self
                    .allowed_country_codes
                    .iter()
                    .any(|c| digits.starts_with(c))
                {
                    Ok(())
                } else if self
                    .allowed_country_codes
                    .iter()
                    .any(|c| c.starts_with(&digits))
                {
                    Err(ParsePhoneNumberPrefixError::Incomplete)
                } else {
                    Err(ParsePhoneNumberPrefixError::UnsupportedCountry)
                }
            }
            Err(parser::ParseError::Incomplete) => Err(ParsePhoneNumberPrefixError::Incomplete),
            Err(
                parser::ParseError::UnexpectedCharacter(index)
                | parser::ParseError::ExcessSuffix(index),
            ) => Err(ParsePhoneNumberPrefixError::InvalidCharacter { at: index as u32 }),
        }
    }
}

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

    static LIPA_DOMAIN: &str = "@lipa.swiss";

    #[test]
    fn test_parse_phone_number_prefix() {
        let ch = PhoneNumberPrefixParser::new(&["CH".to_string()]);
        assert_eq!(ch.parse(""), Err(ParsePhoneNumberPrefixError::Incomplete));
        assert_eq!(ch.parse("+"), Err(ParsePhoneNumberPrefixError::Incomplete));
        assert_eq!(
            ch.parse("+3"),
            Err(ParsePhoneNumberPrefixError::UnsupportedCountry)
        );
        assert_eq!(ch.parse("+4"), Err(ParsePhoneNumberPrefixError::Incomplete));
        assert_eq!(
            ch.parse("+4 "),
            Err(ParsePhoneNumberPrefixError::Incomplete)
        );
        assert_eq!(
            ch.parse("+44"),
            Err(ParsePhoneNumberPrefixError::UnsupportedCountry)
        );
        assert_eq!(ch.parse("+41"), Ok(()));
        assert_eq!(ch.parse("+41 ("), Ok(()));
        assert_eq!(ch.parse("+41 (935"), Ok(()));
        assert_eq!(
            ch.parse("+41a"),
            Err(ParsePhoneNumberPrefixError::InvalidCharacter { at: 3 })
        );

        let us = PhoneNumberPrefixParser::new(&["US".to_string()]);
        assert_eq!(us.parse("+"), Err(ParsePhoneNumberPrefixError::Incomplete));
        assert_eq!(us.parse("+1"), Ok(()));
        assert_eq!(us.parse("+12"), Ok(()));

        let us_and_ch = PhoneNumberPrefixParser::new(&["US".to_string(), "CH".to_string()]);
        assert_eq!(
            us_and_ch.parse("+"),
            Err(ParsePhoneNumberPrefixError::Incomplete)
        );
        assert_eq!(us_and_ch.parse("+1"), Ok(()));
        assert_eq!(us_and_ch.parse("+12"), Ok(()));
        assert_eq!(
            us_and_ch.parse("+3"),
            Err(ParsePhoneNumberPrefixError::UnsupportedCountry)
        );
        assert_eq!(
            us_and_ch.parse("+4"),
            Err(ParsePhoneNumberPrefixError::Incomplete)
        );
        assert_eq!(
            us_and_ch.parse("+44"),
            Err(ParsePhoneNumberPrefixError::UnsupportedCountry)
        );
        assert_eq!(us_and_ch.parse("+41"), Ok(()));
    }

    #[test]
    fn test_parse_phone_number() {
        let expected = PhoneNumber {
            e164: "+41446681800".to_string(),
            country_code: CountryCode::CH,
        };
        assert_eq!(PhoneNumber::parse("+41 44 668 18 00").unwrap(), expected);
        assert_eq!(
            PhoneNumber::parse("tel:+41-44-668-18-00").unwrap(),
            expected,
        );
        assert_eq!(PhoneNumber::parse("+41446681800").unwrap(), expected);

        assert_eq!(
            PhoneNumber::parse("044 668 18 00").unwrap_err(),
            ParsePhoneNumberError::MissingCountryCode
        );
        assert_eq!(
            PhoneNumber::parse("446681800").unwrap_err(),
            ParsePhoneNumberError::MissingCountryCode
        );
        // Missing the last digit.
        assert_eq!(
            PhoneNumber::parse("+41 44 668 18 0").unwrap_err(),
            ParsePhoneNumberError::InvalidPhoneNumber
        );
    }

    #[test]
    fn test_to_from_lightning_address_e2e() {
        let original = PhoneNumber::parse("+41 44 668 18 00").unwrap();
        let address = original.to_lightning_address(LIPA_DOMAIN);
        let e164 = lightning_address_to_phone_number(&address, LIPA_DOMAIN).unwrap();
        let result = PhoneNumber::parse(&e164).unwrap();
        assert_eq!(original.e164, result.e164);
    }

    #[test]
    fn test_to_from_lightning_address() {
        assert_eq!(
            PhoneNumber::parse("+41 44 668 18 00")
                .unwrap()
                .to_lightning_address(LIPA_DOMAIN),
            "-41446681800@lipa.swiss",
        );

        assert_eq!(
            lightning_address_to_phone_number("-41446681800@lipa.swiss", LIPA_DOMAIN).unwrap(),
            "+41446681800"
        );
        assert_eq!(
            lightning_address_to_phone_number("41446681800@lipa.swiss", LIPA_DOMAIN),
            None
        );
        assert_eq!(
            lightning_address_to_phone_number("-41446681800@other.domain", LIPA_DOMAIN),
            None
        );
        assert_eq!(
            lightning_address_to_phone_number("-4144668aa1800@lipa.swiss", LIPA_DOMAIN),
            None
        );
    }
}