Algorithm Search⌘K

Algorithmadvanced

Unicode confusable detection

Also called confusable skeleton, homoglyph detection.

Map each string to a skeleton by NFD, removal of default ignorable code points and the prototypes of confusables.txt. Two strings are confusable when their skeletons are equal.

Time
Θ(n^2) worstΘ(n) best
Space
Θ(n) extra
Where
n = the length of the input in code points
Properties
deterministicofflineiterative

Unicode confusable detection decides whether two strings can look the same to a reader, for example "paypal" in Latin letters and "pаypаl" with U+0430 CYRILLIC SMALL LETTER A in place of both letters a. Unicode Technical Standard 39 maps each string to a skeleton: the string in NFD, without default ignorable code points, with each character replaced by a prototype from the file confusables.txt. Two strings are confusable when their skeletons are equal. Registries of domain names, user names and identifiers use this to refuse a new name that looks like an existing one. The skeleton is only a key for comparison: it is not meant for display, and it is not stable across versions of the data.

In plain words

Many characters look alike. The Cyrillic "а" and the Latin "a" look the same in most fonts, the digit one looks like a small letter l, and "rn" looks like "m" at small sizes. An attacker can use this to make a fake name that a person reads as a real one.

Unicode keeps a list that maps each such character to one chosen look-alike, its prototype. To test two strings, replace every character by its prototype, drop the invisible characters, and compare the results. If they are the same, the strings can fool a reader. A second step looks at the writing systems of the two strings, to tell a simple slip inside one script from a fake made with another script.

The problem

The input is two strings XX and YY. The output is whether XX and YY are confusable, and if so, which kind of confusable they are.

The data file confusables.txt has lines of the form

0430 ;  0061 ;  MA  # ( а → a ) CYRILLIC SMALL LETTER A → LATIN SMALL LETTER A  #

with a source code point, a prototype of one or more code points, and the type MA. The source is always one code point. The prototype can be longer: U+006D LATIN SMALL LETTER M has the prototype U+0072 U+006E ("rn"). Code points without a line are their own prototype. In the file, a tab follows each semicolon and each field; the line above shows the tabs as two spaces.

UTS 39 section 4 defines:

  • internalSkeleton(X). (1) Convert XX to NFD. (2) Remove every code point with Default_Ignorable_Code_Point (DICP), such as U+00AD SOFT HYPHEN and U+200B ZERO WIDTH SPACE. (3) Replace each code point by its prototype. (4) Convert the result to NFD again.
  • bidiSkeleton(d, X). Reorder XX for display with the bidirectional algorithm and the paragraph direction dd, through rule L2, apply L3 and the mirroring of L4, then compute internalSkeleton of the result.
  • skeleton(X) = bidiSkeleton(LTR, X). XX and YY are confusable, X≅YX \cong Y, when skeleton(XX) = skeleton(YY).

The kinds depend on the resolved script set of a string: the intersection of the script sets of its code points, where Common (digits, most punctuation) and Inherited (most combining marks) count as the set of all scripts. A string is single-script if its resolved script set is not empty.

  • Single-script confusables. X≅YX \cong Y and the resolved script sets of XX and YY have a script in common. Example: "rn" and "m", both Latin.
  • Mixed-script confusables. X≅YX \cong Y and the resolved script sets have no script in common (section 4.2).
  • Whole-script confusables. Mixed-script confusables where XX and YY are both single-script (section 4.1). Example: "сор" in Cyrillic and "cop" in Latin.

The algorithm

The implementation computes skeleton(X) for text where bidiSkeleton(LTR, X) is the same as internalSkeleton(X): text with no code point of bidi class R, AL or AN, no explicit directional formatting character, and no code point of class BN that is not default ignorable. On such text the bidirectional algorithm puts every character at level 0, so the reordering of L2 and the mirroring of L4 do nothing. Other text needs the full bidirectional algorithm, and the implementation raises an error for it.

  1. INTERNAL-SKELETON(X)
  2. 1X <- NFD(X)
  3. 2X <- X without the code points that have Default_Ignorable_Code_Point
  4. 3Y <- the concatenation of PROTOTYPE(c) for each code point c of X ▷ c if c has no line
  5. 4return NFD(Y)
  6. SKELETON(X) ▷ bidiSkeleton(LTR, X)
  7. 5if X has a code point of class R, AL or AN, or an explicit formatting character, then use the full bidiSkeleton
  8. 6return INTERNAL-SKELETON(X)
  9. CONFUSABLE(X, Y)
  10. 7return SKELETON(X) = SKELETON(Y)
  11. CLASSIFY(X, Y)
  12. 8if not CONFUSABLE(X, Y) then return none
  13. 9RX <- RESOLVED-SCRIPT-SET(X); RY <- RESOLVED-SCRIPT-SET(Y)
  14. 10if RX ∩ RY is not empty then return single-script
  15. 11if RX and RY are both not empty then return whole-script
  16. 12return mixed-script

To find all names in a registry that are confusable with a new name, store the skeleton of each name in a hash table. One lookup of the skeleton of the new name finds them all.

Example

The prototypes below are copied from confusables.txt 16.0.0. Take XX = "pаypаl" with U+0430 at offsets 1 and 4, and YY = "paypa1" with U+0031 DIGIT ONE at offset 5.

step XX YY
input p U+0430 y p U+0430 l p a y p a U+0031
1. NFD no change no change
2. remove DICP no change no change
3. prototypes U+0430 → a, so "paypal" U+0031 → l, so "paypal"
4. NFD "paypal" "paypal"

Both skeletons are "paypal", the skeleton of the real name "paypal", so all three strings are confusable. The kinds differ:

pair resolved script sets kind
"paypa1", "paypal" {Latin} and {Latin} (U+0031 is Common) single-script
"pаypаl", "paypal" {} and {Latin} mixed-script
"сор", "cop" {Cyrillic} and {Latin} whole-script
"rn", "m" {Latin} and {Latin} single-script

"pаypаl" mixes Cyrillic and Latin, so its resolved script set is empty. Such a string is suspicious on its own, without any comparison. A name in only Cyrillic letters that looks like a Latin name, such as "сор", passes a mixed-script check, and only the whole-script test finds it.

Some pairs that are not confusable: "paypal" and "paypai", "e" and "é", "a b" and "ab" (U+0020 is not default ignorable), and "O" and "o".

Correctness

The function INTERNAL-SKELETON is the four steps of UTS 39 written out, so it is correct by definition. Two facts need proof. First, for text with no code point of class R, AL or AN and no explicit formatting character, bidiSkeleton(LTR, X) = internalSkeleton(X). The rules of the bidirectional algorithm with paragraph level 0 then give every remaining character the level 0, so L2 reverses nothing and L4 mirrors nothing. Second, ≅\cong is an equivalence relation, because it compares the values of one function. The proof is in proofs/correctness.md. The tests check the four steps one by one, the pairs above, idempotence, a second implementation of the steps on random strings, and the equivalence on a set of random words.

Proof: SKELETON equals bidiSkeleton(LTR) on text that stays at level 0, and confusability is an equivalence relationfull

Setup. Let P(c)P(c) be the prototype of a code point cc: the target of the line of cc in confusables.txt, or cc itself if cc has no line. Let DD be the set of code points with Default_Ignorable_Code_Point. UTS 39 section 4 defines internalSkeleton(X)=NFD(P∗(NFD(X)∖D))\mathrm{internalSkeleton}(X) = \mathrm{NFD}(P^*(\mathrm{NFD}(X) \setminus D)), where X∖DX \setminus D deletes the code points of DD and P∗P^* applies PP to each code point and concatenates the results.

Claim 1. INTERNAL-SKELETON(XX) returns internalSkeleton(XX).

Proof. Line L1 computes NFD(X)\mathrm{NFD}(X). Line L2 deletes the code points of DD and keeps the order of the rest. Line L3 concatenates P(c)P(c) over the remaining code points in order, which is P∗P^*. Line L4 applies NFD. Each line is one step of the definition, in the same order. □\square

Claim 2. Let XX have no code point of bidi class R, AL or AN and no explicit directional formatting character (LRE, RLE, LRO, RLO, PDF, LRI, RLI, FSI, PDI), and let every code point of class BN in XX be in DD. Then bidiSkeleton(LTR, XX) = internalSkeleton(XX).

Proof. bidiSkeleton(LTR, XX) runs the bidirectional algorithm of UAX 9 with paragraph level 0 on XX, reorders through rule L2, applies L3 and L4, and then takes internalSkeleton. We show that every character that the algorithm keeps gets level 0.

  • With no explicit formatting characters, rules X1 to X8 give every character the paragraph embedding level 0, and the only isolating run sequence of each paragraph has sos = eos = L. Rule X9 removes the BN characters.
  • The remaining classes are L, EN, ES, ET, CS, NSM, ON, B, S and WS. Rule W1 gives each NSM the class of the character before it, or sos = L at the start. W2 changes EN to AN only after AL, and there is no AL. W3 changes AL, of which there are none. W4 to W6 change ES, ET and CS next to EN into EN or into ON. W7 changes each EN to L, because the strong class before it is L or sos = L, since there is no R. After W7 the only strong class is L.
  • Rule N0 (brackets) gives a pair the embedding direction L or the direction of the strong class inside, which is L. N1 gives a neutral run between two L the class L. N2 gives the other neutrals the embedding direction, which is L for level 0. So every character is L.
  • I1 raises only R, AN and EN at even levels, and there are none. So all levels are 0. Rule L1 sets separators and trailing white space to the paragraph level 0.

With all levels 0, rule L2 reverses no run, because it only reverses runs at level 1 or higher. Rule L3 only moves marks in right-to-left runs, and L4 mirrors only characters at odd levels, so neither changes anything. The only possible difference is that X9 removed the BN characters. These are all in DD, so step 2 of internalSkeleton removes them anyway. Hence the input to internalSkeleton in bidiSkeleton has the same code points in the same order as XX without its BN characters, and both sides give the same skeleton. □\square

Lines L5 and L6 return INTERNAL-SKELETON(XX) exactly under the conditions of Claim 2, and raise an error otherwise. So SKELETON is skeleton(XX) = bidiSkeleton(LTR, XX) wherever it returns.

Claim 3. The relation X≅YX \cong Y of line L7 is an equivalence relation.

Proof. X≅YX \cong Y holds when skeleton(XX) = skeleton(YY). Equality of the values of one function is reflexive, symmetric and transitive. □\square

Claim 4. CLASSIFY returns the kind of UTS 39.

Proof. If the skeletons differ, line L8 returns none. Otherwise, write ALL for the set of all scripts; it is the identity for intersection, and line L9 computes the resolved script sets RXR_X and RYR_Y as intersections with Common and Inherited read as ALL. Single-script confusables are confusables whose resolved script sets share a script, which is the test RX∩RY≠∅R_X \cap R_Y \ne \emptyset of line L10. Otherwise they are mixed-script confusables. Among those, whole-script confusables are the ones where both strings are single-script, RX≠∅R_X \ne \emptyset and RY≠∅R_Y \ne \emptyset, which is line L11. Line L12 returns the remaining case, mixed-script confusables where at least one string is mixed-script. □\square

Idempotence. UTS 39 states that the data is idempotent. For the subset in the implementation, this can be checked line by line: every prototype is in NFD, contains no code point of DD, and contains no code point that has a line of its own. A skeleton SS is in NFD and has no code point of DD, so steps 1 and 2 leave it unchanged. Every code point of SS comes from a prototype or is a code point without a line, so step 3 leaves it unchanged, and step 4 too. Hence skeleton(skeleton(XX)) = skeleton(XX). A test checks this on random strings.

Termination. Each of the lines L1 to L7 makes one pass over a finite string, and NFD stops on every finite input. CLASSIFY calls these a fixed number of times.

Complexity

In the word-RAM model, the lookups of DICP, of the prototype and of the script cost O(1)O(1) each, with a large constant: confusables.txt has thousands of lines. Prototypes have bounded length. So each step is linear, except the sorting of long runs of combining marks in NFD:

  • NFD is Θ(n)\Theta(n) for text with short runs of combining marks. A single run of nn combining marks costs Θ(n2)\Theta(n^2) in the worst case, as in the normalization algorithm.
  • Removing DICP and mapping by prototypes are Θ(n)\Theta(n), and the result has O(n)O(n) code points.
  • Comparing two skeletons is linear in their length.
operation time extra space
skeleton Θ(n)\Theta(n) for short runs of combining marks, Θ(n2)\Theta(n^2) in the worst case Θ(n)\Theta(n)
CONFUSABLE, CLASSIFY Θ(n)\Theta(n) for strings of total length nn Θ(n)\Theta(n)
test a new name against a registry of NN names Θ(n)\Theta(n) expected with a hash table of skeletons Θ(Nn)\Theta(N n) for the table

Properties

  • An equivalence relation. ≅\cong is reflexive, symmetric and transitive. UTS 39 notes that this imposes transitivity on the data: if "a" looks like "b" and "b" like "c", then "a" and "c" are confusable, even if they do not look alike. So the test can be too broad.
  • Idempotent mapping. The data maps each prototype to itself, so skeleton(skeleton(X)) = skeleton(X).
  • Not about case or accents. The skeleton keeps case: "O" and "o" have different skeletons. It keeps combining marks that have no line in the data. Use case folding first if case must not count.
  • Not for display, not stable. Skeletons can contain odd prototypes ("m" becomes "rn"), and they change when the data changes. Store the names, and recompute the skeletons after an update.

Variants and improvements

  • Restriction levels and mixed-script detection. UTS 39 also defines restriction levels for identifiers, from ASCII-only to unrestricted, based on the resolved script sets. Many registries combine them with the confusable test.
  • Augmented script sets. For Han, Hiragana, Katakana and Hangul, UTS 39 adds the sets for Japanese and Korean writing, so that text that mixes Han and Kana counts as single-script.
  • Bidirectional text. bidiSkeleton exists because a string with right-to-left characters can display in a different order from its logical order. Two strings with different logical orders can then look the same.
  • Fuzzy matching. For names that differ by one character, a registry can add an edit distance test on the skeletons.
  • Domain names. IDNA processing maps the labels of a domain name and encodes them with Punycode. The confusable test is a separate policy check of the registry or of the browser.

When to use it

Use the skeleton test when a system gives out unique names that people read: domain names, user names, package names, file names in a shared folder. Compute the skeleton of each new name and refuse the name if the skeleton is taken. Add a check that refuses mixed-script names unless there is a good reason. Do not use the skeleton as a normal form for search or for display; use NFC and case folding for that.

Pitfalls

  • Skipping the NFD steps. Without step 1, "é" as U+00E9 and as U+0065 U+0301 give different skeletons. Without step 4, a prototype that decomposes can stay composed. The test test_four_steps_of_internal_skeleton checks each step.
  • Comparing internalSkeleton on right-to-left text. Display order differs from logical order there. Use bidiSkeleton, or reject the text, as the implementation does with ValueError.
  • Showing the skeleton. The skeleton of "mom" is "rnorn". It is a key, not a name.
  • Old data. The data changes with every version, so skeletons in a database must be recomputed after an upgrade.
  • Expecting accents to count as confusable. "e" and "é" are not confusable by this test. If a font makes a mark hard to see, that needs another rule.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

unicode_confusable_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-confusable-detection/. The authors are listed in prov/N2QXMJ.jsonl.
"""Confusable detection of UTS 39 section 4 with a subset of confusables.txt.

internal_skeleton is the four steps of internalSkeleton. skeleton is bidiSkeleton(LTR, X)
for text where the bidirectional algorithm gives every character level 0, which is the
case when the text has no character of bidi class R, AL or AN and no explicit
directional formatting character. For such text bidiSkeleton(LTR, X) equals
internalSkeleton(X) (see proofs/correctness.md). Other text raises ValueError.

The tables are short subsets of the Unicode 16.0.0 data files. A code point that is not
in a table is treated as if it had no line there.
"""

import unicodedata

# confusables.txt 16.0.0 (Date: 2024-08-14, 23:39:57 GMT). The first three fields of each
# line are copied; the comments after "#" are shortened to the source name.
CONFUSABLES_LINES = (
    "FF41 ;\t0061 ;\tMA\t# FULLWIDTH LATIN SMALL LETTER A\n"
    "0251 ;\t0061 ;\tMA\t# LATIN SMALL LETTER ALPHA\n"
    "0430 ;\t0061 ;\tMA\t# CYRILLIC SMALL LETTER A\n"
    "0391 ;\t0041 ;\tMA\t# GREEK CAPITAL LETTER ALPHA\n"
    "0410 ;\t0041 ;\tMA\t# CYRILLIC CAPITAL LETTER A\n"
    "0392 ;\t0042 ;\tMA\t# GREEK CAPITAL LETTER BETA\n"
    "0412 ;\t0042 ;\tMA\t# CYRILLIC CAPITAL LETTER VE\n"
    "0435 ;\t0065 ;\tMA\t# CYRILLIC SMALL LETTER IE\n"
    "0415 ;\t0045 ;\tMA\t# CYRILLIC CAPITAL LETTER IE\n"
    "0441 ;\t0063 ;\tMA\t# CYRILLIC SMALL LETTER ES\n"
    "0421 ;\t0043 ;\tMA\t# CYRILLIC CAPITAL LETTER ES\n"
    "0501 ;\t0064 ;\tMA\t# CYRILLIC SMALL LETTER KOMI DE\n"
    "13A0 ;\t0044 ;\tMA\t# CHEROKEE LETTER A\n"
    "0456 ;\t0069 ;\tMA\t# CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I\n"
    "04CF ;\t0069 ;\tMA\t# CYRILLIC SMALL LETTER PALOCHKA\n"
    "0131 ;\t0069 ;\tMA\t# LATIN SMALL LETTER DOTLESS I\n"
    "0269 ;\t0069 ;\tMA\t# LATIN SMALL LETTER IOTA\n"
    "0458 ;\t006A ;\tMA\t# CYRILLIC SMALL LETTER JE\n"
    "0261 ;\t0067 ;\tMA\t# LATIN SMALL LETTER SCRIPT G\n"
    "007C ;\t006C ;\tMA\t# VERTICAL LINE\n"
    "0031 ;\t006C ;\tMA\t# DIGIT ONE\n"
    "0049 ;\t006C ;\tMA\t# LATIN CAPITAL LETTER I\n"
    "2160 ;\t006C ;\tMA\t# ROMAN NUMERAL ONE\n"
    "217C ;\t006C ;\tMA\t# SMALL ROMAN NUMERAL FIFTY\n"
    "FF4C ;\t006C ;\tMA\t# FULLWIDTH LATIN SMALL LETTER L\n"
    "2113 ;\t006C ;\tMA\t# SCRIPT SMALL L\n"
    "1D5C5 ;\t006C ;\tMA\t# MATHEMATICAL SANS-SERIF SMALL L\n"
    "01C0 ;\t006C ;\tMA\t# LATIN LETTER DENTAL CLICK\n"
    "0399 ;\t006C ;\tMA\t# GREEK CAPITAL LETTER IOTA\n"
    "0406 ;\t006C ;\tMA\t# CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I\n"
    "03BF ;\t006F ;\tMA\t# GREEK SMALL LETTER OMICRON\n"
    "043E ;\t006F ;\tMA\t# CYRILLIC SMALL LETTER O\n"
    "0D20 ;\t006F ;\tMA\t# MALAYALAM LETTER TTHA\n"
    "0A66 ;\t006F ;\tMA\t# GURMUKHI DIGIT ZERO\n"
    "0030 ;\t004F ;\tMA\t# DIGIT ZERO\n"
    "039F ;\t004F ;\tMA\t# GREEK CAPITAL LETTER OMICRON\n"
    "0B20 ;\t004F ;\tMA\t# ORIYA LETTER TTHA\n"
    "0440 ;\t0070 ;\tMA\t# CYRILLIC SMALL LETTER ER\n"
    "006D ;\t0072 006E ;\tMA\t# LATIN SMALL LETTER M\n"
    "0445 ;\t0078 ;\tMA\t# CYRILLIC SMALL LETTER HA\n"
    "0443 ;\t0079 ;\tMA\t# CYRILLIC SMALL LETTER U\n"
    "2010 ;\t002D ;\tMA\t# HYPHEN\n"
    "2212 ;\t002D ;\tMA\t# MINUS SIGN\n"
    "01C3 ;\t0021 ;\tMA\t# LATIN LETTER RETROFLEX CLICK\n"
    "0060 ;\t0027 ;\tMA\t# GRAVE ACCENT\n"
)

# DerivedCoreProperties-16.0.0.txt, lines of Default_Ignorable_Code_Point (a subset).
DICP_LINES = """\
00AD          ; Default_Ignorable_Code_Point # Cf       SOFT HYPHEN
034F          ; Default_Ignorable_Code_Point # Mn       COMBINING GRAPHEME JOINER
061C          ; Default_Ignorable_Code_Point # Cf       ARABIC LETTER MARK
115F..1160    ; Default_Ignorable_Code_Point # Lo   [2] HANGUL CHOSEONG FILLER..HANGUL JUNGSEONG FILLER
17B4..17B5    ; Default_Ignorable_Code_Point # Mn   [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA
180B..180D    ; Default_Ignorable_Code_Point # Mn   [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE
180E          ; Default_Ignorable_Code_Point # Cf       MONGOLIAN VOWEL SEPARATOR
180F          ; Default_Ignorable_Code_Point # Mn       MONGOLIAN FREE VARIATION SELECTOR FOUR
200B..200F    ; Default_Ignorable_Code_Point # Cf   [5] ZERO WIDTH SPACE..RIGHT-TO-LEFT MARK
202A..202E    ; Default_Ignorable_Code_Point # Cf   [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE
2060..2064    ; Default_Ignorable_Code_Point # Cf   [5] WORD JOINER..INVISIBLE PLUS
2065          ; Default_Ignorable_Code_Point # Cn       <reserved-2065>
2066..206F    ; Default_Ignorable_Code_Point # Cf  [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES
3164          ; Default_Ignorable_Code_Point # Lo       HANGUL FILLER
FE00..FE0F    ; Default_Ignorable_Code_Point # Mn  [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16
FEFF          ; Default_Ignorable_Code_Point # Cf       ZERO WIDTH NO-BREAK SPACE
"""

# Scripts-16.0.0.txt (Date: 2024-04-30, 21:48:40 GMT), a subset.
SCRIPTS_LINES = """\
0020          ; Common # Zs       SPACE
002D          ; Common # Pd       HYPHEN-MINUS
0030..0039    ; Common # Nd  [10] DIGIT ZERO..DIGIT NINE
0041..005A    ; Latin # L&  [26] LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z
0061..007A    ; Latin # L&  [26] LATIN SMALL LETTER A..LATIN SMALL LETTER Z
038E..03A1    ; Greek # L&  [20] GREEK CAPITAL LETTER UPSILON WITH TONOS..GREEK CAPITAL LETTER RHO
03A3..03E1    ; Greek # L&  [63] GREEK CAPITAL LETTER SIGMA..GREEK SMALL LETTER SAMPI
0400..0481    ; Cyrillic # L& [130] CYRILLIC CAPITAL LETTER IE WITH GRAVE..CYRILLIC SMALL LETTER KOPPA
"""


def parse_confusables(text: str) -> dict:
    """Map each source code point to its prototype string."""
    table = {}
    for line in text.splitlines():
        line = line.split("#", 1)[0].strip()
        if not line:
            continue
        src, tgt = (f.strip() for f in line.split(";")[:2])
        table[chr(int(src, 16))] = "".join(chr(int(h, 16)) for h in tgt.split())
    return table


def parse_ranges(text: str) -> list:
    """Parse lines "XXXX..YYYY ; value" into a list of (lo, hi, value)."""
    out = []
    for line in text.splitlines():
        line = line.split("#", 1)[0].strip()
        if not line:
            continue
        cps, value = (f.strip() for f in line.split(";"))
        lo, _, hi = cps.partition("..")
        out.append((int(lo, 16), int(hi or lo, 16), value))
    return out


PROTOTYPES = parse_confusables(CONFUSABLES_LINES)
_DICP = parse_ranges(DICP_LINES)
_SCRIPTS = parse_ranges(SCRIPTS_LINES)
_EXPLICIT = {"LRE", "RLE", "LRO", "RLO", "PDF", "LRI", "RLI", "FSI", "PDI"}


def is_default_ignorable(c: str) -> bool:
    cp = ord(c)
    return any(lo <= cp <= hi for lo, hi, _ in _DICP)


def internal_skeleton(x: str) -> str:
    """internalSkeleton(X) of UTS 39 section 4."""
    x = unicodedata.normalize("NFD", x)  # @line L1
    x = "".join(c for c in x if not is_default_ignorable(c))  # @line L2
    y = "".join(PROTOTYPES.get(c, c) for c in x)  # @line L3
    return unicodedata.normalize("NFD", y)  # @line L4


def skeleton(x: str) -> str:
    """skeleton(X) = bidiSkeleton(LTR, X), for text that stays at level 0."""
    for c in x:  # @line L5
        bc = unicodedata.bidirectional(c)
        if bc in ("R", "AL", "AN") or bc in _EXPLICIT:
            raise ValueError(f"U+{ord(c):04X} has bidi class {bc}; the full bidiSkeleton is needed")
        if bc == "BN" and not is_default_ignorable(c):
            raise ValueError(f"U+{ord(c):04X} is BN but not default ignorable")
    return internal_skeleton(x)  # @line L6


def confusable(x: str, y: str) -> bool:
    """X and Y are confusable when their skeletons are equal."""
    return skeleton(x) == skeleton(y)  # @line L7


def resolved_script_set(x: str):
    """The intersection of the script sets of the code points of x.

    Common and Inherited stand for the set of all scripts, written None here.
    Return None for ALL, or a frozenset of script names.
    """
    result = None
    for c in x:
        cp = ord(c)
        found = [v for lo, hi, v in _SCRIPTS if lo <= cp <= hi]
        if not found:
            raise ValueError(f"U+{cp:04X} is not in the script subset")
        if found[0] in ("Common", "Inherited"):
            continue
        s = frozenset([found[0]])
        result = s if result is None else result & s
    return result


def _meet(a, b):
    if a is None:
        return b
    if b is None:
        return a
    return a & b


def classify(x: str, y: str):
    """Return None, "single-script", "whole-script" or "mixed-script"."""
    if not confusable(x, y):  # @line L8
        return None
    rx, ry = resolved_script_set(x), resolved_script_set(y)  # @line L9
    both = _meet(rx, ry)
    if both is None or both:  # @line L10
        return "single-script"
    if (rx is None or rx) and (ry is None or ry):  # @line L11
        return "whole-script"
    return "mixed-script"  # @line L12
test_unicode_confusable_detection.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-confusable-detection/. The authors are listed in prov/N2QXMJ.jsonl.
# NFD and the bidi classes come from unicodedata (unidata_version 16.0.0 with Python 3.14).
# The tests use only characters that are assigned in Unicode 3.2.
import random

import pytest

from unicode_confusable_detection import (PROTOTYPES, classify, confusable, internal_skeleton,
                                          is_default_ignorable, parse_confusables,
                                          resolved_script_set, skeleton)


def test_parse_confusables_line():
    t = parse_confusables("0430 ;\t0061 ;\tMA\t# ( а → a ) CYRILLIC SMALL LETTER A → LATIN SMALL LETTER A\t# \n")
    assert t == {"а": "a"}
    assert PROTOTYPES["m"] == "rn"
    assert PROTOTYPES["1"] == "l" and PROTOTYPES["I"] == "l" and PROTOTYPES["|"] == "l"
    assert PROTOTYPES["0"] == "O" and PROTOTYPES["о"] == "o"


def test_four_steps_of_internal_skeleton():
    # Step 1, NFD: U+00E9 and U+0065 U+0301 give the same skeleton.
    assert internal_skeleton("é") == internal_skeleton("é") == "é"
    # Step 2: default ignorable code points are removed.
    assert internal_skeleton("pay­pal") == internal_skeleton("pay​pal") == "paypal"
    # Step 3: the prototypes. U+0430 CYRILLIC SMALL LETTER A becomes U+0061.
    assert internal_skeleton("pаypаl") == "paypal"
    assert internal_skeleton("m") == "rn"
    # Step 4: NFD again. U+0131 DOTLESS I becomes i, and i + U+0307 stays decomposed.
    assert internal_skeleton("ı̇") == "i̇"
    assert internal_skeleton("ı̇") == internal_skeleton("i̇")


def test_confusable_pairs():
    must = [("paypal", "pаypаl"), ("paypal", "paypa1"), ("paypal", "paypaI"), ("rn", "m"),
            ("сор", "cop"), ("Ο0", "OO"), ("a-b", "a‐b"), ("pay​pal", "paypal"),
            ("é", "é")]
    for x, y in must:
        assert confusable(x, y), (x, y)
    must_not = [("paypal", "paypai"), ("cat", "cot"), ("e", "é"), ("rm", "rn"), ("O", "o"),
                ("a b", "ab")]
    for x, y in must_not:
        assert not confusable(x, y), (x, y)


def test_classes_of_confusables():
    assert classify("rn", "m") == "single-script"
    assert classify("paypa1", "paypal") == "single-script"  # U+0031 is Common
    assert classify("сор", "cop") == "whole-script"  # Cyrillic and Latin
    assert classify("pаypаl", "paypal") == "mixed-script"  # the first string mixes scripts
    assert classify("cat", "dog") is None


def test_resolved_script_sets():
    assert resolved_script_set("abc") == frozenset({"Latin"})
    assert resolved_script_set("123") is None  # Common only: all scripts
    assert resolved_script_set("a1") == frozenset({"Latin"})
    assert resolved_script_set("pаypаl") == frozenset()
    assert resolved_script_set("сор") == frozenset({"Cyrillic"})


def test_skeleton_rejects_text_that_needs_bidi_reordering():
    for x in ["אb", "aا", "1١", "a‮b", "a‏b", "a\u0001"]:
        with pytest.raises(ValueError):
            skeleton(x)
    assert internal_skeleton("a‏b") == "ab"


def test_skeleton_is_idempotent_and_ignores_dicp():
    rng = random.Random(39)
    alphabet = "aceilmnoprxy01I|-`" + "аеорсху" + "ΑΟ" + "é"
    ignorables = ["­", "​", "⁠", "", "͏"]
    for _ in range(400):
        x = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 8)))
        s = skeleton(x)
        assert skeleton(s) == s
        y = list(x)
        for _ in range(rng.randint(0, 3)):
            y.insert(rng.randint(0, len(y)), rng.choice(ignorables))
        assert skeleton("".join(y)) == s
        assert not any(is_default_ignorable(c) for c in s)


def _reference_skeleton(x):
    """A second implementation of the four steps, from the raw lines and code point lists."""
    import unicodedata
    ignorable = set(range(0x200B, 0x2010)) | {0x00AD, 0x034F, 0x2060, 0x2061, 0x2062, 0x2063,
                                              0x2064, 0xFEFF} | set(range(0xFE00, 0xFE10))
    x = [c for c in unicodedata.normalize("NFD", x) if ord(c) not in ignorable]
    out = []
    for c in x:
        out.append(PROTOTYPES[c] if c in PROTOTYPES else c)
    return unicodedata.normalize("NFD", "".join(out))


def test_against_reference_on_random_strings():
    rng = random.Random(2024)
    alphabet = "abcdeilmnorIO01|" + "аеіјорсху" + "ΑΒΟοι" + "­​́" + "ñåé"
    for _ in range(400):
        x = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 10)))
        assert internal_skeleton(x) == _reference_skeleton(x)


def test_confusable_is_an_equivalence():
    rng = random.Random(7)
    alphabet = "aolI1m" + "ао" + "rn"
    words = ["".join(rng.choice(alphabet) for _ in range(rng.randint(1, 3))) for _ in range(60)]
    for x in words:
        assert confusable(x, x)
        for y in words:
            assert confusable(x, y) == confusable(y, x)
            if confusable(x, y):
                for z in words:
                    if confusable(y, z):
                        assert confusable(x, z)

History

UTS 39 and confusables.txt are published with each version of the Unicode Standard. Older versions of the file had four tables with the types SL, SA, ML and MA; the current file has one table, and every line has the type MA. Since Unicode 7.0 the mapping is idempotent. Recent revisions added bidiSkeleton, and skeleton is now defined as bidiSkeleton with a left-to-right paragraph. Revision 30 is the version for Unicode 16.0.0.

References

  1. Mark Davis and Michel Suignard (editors), Unicode Technical Standard 39, Unicode Security Mechanisms, revision 30, 2024-09-03, Section 4 Confusable Detection (internalSkeleton, bidiSkeleton and skeleton), Section 4.1 Whole-Script Confusables and Section 4.2 Mixed-Script Confusables
  2. confusables.txt, Unicode security data, version 16.0.0, 2024-08-14, the header (the format of the lines) and the data lines
  3. DerivedCoreProperties-16.0.0.txt, Unicode Character Database, the lines of Default_Ignorable_Code_Point
  4. Unicode Technical Report 36, Unicode Security Considerations, the discussion of visual spoofing

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example