# uuid58 Specification

> Plain Markdown rendering of <https://nakanoasaservice.github.io/uuid58/spec/>, generated from [`Spec.lean`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/Spec.lean).
> The Lean code blocks are copied verbatim.

 * *Version:* 1.1.1
 * *Source:* [`Spec.lean`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/Spec.lean),
   checked by Lean (Section 1.3)
 * *Test vectors:* [`vectors.json`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/vectors.json), generated by
   [`generate_vectors.py`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/generate_vectors.py)
 * *For AI assistants and other tools:* this document as Markdown,
   [`index.md`](https://nakanoasaservice.github.io/uuid58/spec/index.md), with the
   Lean code verbatim and about a tenth of the size of this page

## 1. Introduction

uuid58 is a text encoding for 128-bit UUIDs. It writes the UUID as an
unsigned integer in base 58, using the Bitcoin Base58 alphabet, always padded
to exactly 22 characters.

```
f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf  <->  XDY9dmBbcMBXqcRvYw8xJ2
```

This document defines the encoding so that independent implementations in
different languages produce identical results.

### 1.1. Conventions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
interpreted as described in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119)
and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174) when, and only when,
they appear in all capitals, as shown here.

All characters in the alphabet and in accepted inputs are ASCII. `U+002D` is the hyphen
(`-`).

### 1.2. Scope

This specification defines:

 * the alphabet (Section 2),
 * encoding a 128-bit value to a uuid58 string (Section 3),
 * decoding a uuid58 string to a 128-bit value (Section 4),
 * the textual UUID forms an implementation accepts and produces (Section 5),
 * validation (Section 6),
 * error kinds (Section 7).

Generating UUIDs is out of scope. An implementation MAY offer a function that
generates a random UUID and returns its uuid58 encoding; this specification
places no requirements on it beyond the encoding itself.

### 1.3. Formal definitions

This specification is a [Lean 4](https://lean-lang.org) file,
[`Spec.lean`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/Spec.lean), written as a
[Verso](https://verso.lean-lang.org) document. Lean checks every code block
in it, in order, and this page is generated from the same file
(Section 8.3). In a code block, a name links
to its definition and shows its type.

Sections 2 to 6 state their requirements twice: in prose and as Lean
definitions. The two are meant to say the same thing. If they disagree, that
is a defect of this document, and until it is corrected the Lean definition
governs. A requirement with no definition beside it, such as the byte order
of a native UUID type or the content of error messages, is stated in prose
only.

The code blocks contain three kinds of statement:

 * A definition (`def`, `abbrev`, or `inductive`) introduces a name that the
   prose and later definitions use.
 * An `example` is a fact about the definitions that Lean has checked. The
   worked examples of this document are written this way, so they cannot
   drift from the definitions.
 * A definition of type `Prop` whose comment begins with "Claim" states a
   property that holds for every input. Each claim is proved in
   [`formal/Proofs.lean`](https://github.com/nakanoasaservice/uuid58/blob/main/formal/Proofs.lean), and the
   [formal check](https://github.com/nakanoasaservice/uuid58/blob/main/formal/README.md) fails if a claim has no proof.

The definitions treat a string as its sequence of bytes, one of the units
that Section 4.1 allows, and a 128-bit value as a natural number below
`2^128`. For input that is entirely ASCII they give the required result
exactly. For other input, Section 4.1 allows either of two error kinds, the
definitions give one of them, and `Allowed` in that section states the
choice.

Little Lean is needed to read them. `Fin n` is the type of natural numbers
below `n`. `List α` is a finite sequence, written `[a, b, c]` or
`a :: rest`. `Option α` is either `some x` or `none`. `Except Error α` is
either `.ok x` or `.error e`.

```lean
namespace Uuid58
```

## 2. Alphabet

The alphabet is the following 58 characters, in this order:

```
123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz
```

The character at position `i` (zero-based) is the digit with value `i`. So
`1` is 0, `A` is 9, and `z` is 57.

```lean
/-- A byte: a natural number in `0..255`. -/
abbrev Byte := Fin 256

/-- A digit value in `0..57`. -/
abbrev Digit := Fin 58

/-- The bytes of a string literal. -/
def bytes (s : String) : List Byte := s.toUTF8.data.toList.map UInt8.toFin

def alphabet :=
  bytes "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

/-- The character that writes a digit. -/
def symbol (d : Digit) : Byte := alphabet[d.val]!

/-- The digit that a character writes, or `none` if it is not in the
alphabet. -/
def digit? (b : Byte) : Option Digit :=
  let i := alphabet.idxOf b
  if h : i < 58 then some ⟨i, h⟩ else none

example : alphabet.length = 58 := by decide
example : (bytes "1Az").map digit? = [some 0, some 9, some 57] := by decide
```

The alphabet is the Bitcoin Base58 alphabet. It consists of the digits
`1`–`9`, the uppercase letters `A`–`Z` except `I` and `O`, and the lowercase
letters `a`–`z` except `l`. The digit `0` is not included either. These four
characters (`0`, `O`, `I`, `l`) are left out because they are easily confused
with each other.

```lean
example : (bytes "0OIl").map digit? = [none, none, none, none] := by decide
```

The alphabet is in ascending ASCII order. Section 3.2 relies on this.

```lean
example : alphabet.Pairwise (· < ·) := by decide
```

## 3. Encoding

### 3.1. Algorithm

The input is a 128-bit value `V`: either 16 bytes read as an unsigned
big-endian integer, or an unsigned integer with `0 <= V <= 2^128 - 1`.

The output is the 22-character string `d[0] d[1] ... d[21]` such that:

```
V = d[0] * 58^21 + d[1] * 58^20 + ... + d[21] * 58^0
```

where each `d[i]` is a digit value in `0..57`, written as the corresponding
alphabet character. Because `58^22 > 2^128`, 22 digits are always enough.
Leading digits with value 0 are written as `1`; they MUST NOT be omitted.

```lean
/-- A 128-bit value. -/
abbrev UUID := Fin (2^128)

/-- The value of a digit sequence, most significant digit first. -/
def value : List Digit → Nat
  | [] => 0
  | d :: ds => d.val * 58^ds.length + value ds

/-- The `k` least significant base-58 digits of `n`, most significant first,
including leading zero digits. -/
def digits : Nat → Nat → List Digit
  | 0, _ => []
  | k+1, n => ⟨n / 58^k % 58, Nat.mod_lt _ (by decide)⟩ :: digits k (n % 58^k)

def encode (v : UUID) : List Byte := (digits 22 v.val).map symbol

example : 2^128 < 58^22 := by decide
```

Encoding a 128-bit value never fails. The output is always exactly 22
characters. Section 3.3 covers inputs whose type can hold other values.

```lean
/-- Claim: every encoding is 22 characters of the alphabet. -/
def EncodingShape : Prop :=
  ∀ v : UUID, (encode v).length = 22 ∧ ∀ b ∈ encode v, b ∈ alphabet
```

Examples:

```
00000000-0000-0000-0000-000000000000  <->  1111111111111111111111
00000000-0000-0000-0000-000000000001  <->  1111111111111111111112
f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf  <->  XDY9dmBbcMBXqcRvYw8xJ2
ffffffff-ffff-ffff-ffff-ffffffffffff  <->  YcVfxkQb6JRzqk5kF2tNLv
```

`YcVfxkQb6JRzqk5kF2tNLv` is the largest valid uuid58 string. It is called
`MAX_UUID58` below.

```lean
/-- `MAX_UUID58`. -/
def maxUuid58 := bytes "YcVfxkQb6JRzqk5kF2tNLv"

example : encode 0x00000000000000000000000000000000 =
    bytes "1111111111111111111111" := by decide
example : encode 0x00000000000000000000000000000001 =
    bytes "1111111111111111111112" := by decide
example : encode 0xf4b247fd1f8745d4aa061c6fc0a8dfaf =
    bytes "XDY9dmBbcMBXqcRvYw8xJ2" := by decide
example : encode 0xffffffffffffffffffffffffffffffff = maxUuid58 := by decide
```

### 3.2. Ordering

For any two 128-bit values `A` and `B`, comparing `encode(A)` and `encode(B)`
character by character in ASCII order gives the same result as comparing `A`
and `B` as integers. This holds because the alphabet is in ascending ASCII
order and every encoding has the same length.

```lean
/-- Claim: encoding preserves order. On lists of bytes, `<` compares the first
position at which the lists differ, as unsigned bytes. -/
def OrderPreserved : Prop :=
  ∀ a b : UUID, encode a < encode b ↔ a < b
```

Implementations MUST NOT change the alphabet or the padding in a way that
breaks this property.

The comparison must be by character code (or byte), as in a binary or `C`
collation. Locale-aware or case-insensitive collations, common as database
defaults, do not preserve this order.

> *Note (non-normative).* The order of a platform's native UUID type may
  differ from this order. For example, Java's `UUID.compareTo` compares the
  two halves as signed 64-bit integers, so it sorts
  `ffffffff-ffff-ffff-ffff-ffffffffffff` before
  `00000000-0000-0000-0000-000000000001`, while their encodings sort the other
  way.

### 3.3. Inputs that are not exactly 128 bits

Some input types can hold values that are not a 128-bit value: a byte
sequence of arbitrary length, or an arbitrary-precision or signed integer.
An implementation that encodes from such a type MUST NOT truncate, wrap, or
pad the input, and MUST reject it as follows:

 * A byte sequence whose length is not exactly 16 fails with
   `invalid_length`.
 * An integer less than 0 or greater than `2^128 - 1` fails with `overflow`.

```lean
/-- The error kinds of Section 7: `invalid_length`, `invalid_character`, and
`overflow`. -/
inductive Error where
  | invalidLength | invalidCharacter | overflow
  deriving DecidableEq, Repr

deriving instance DecidableEq for Except

/-- The value of a byte sequence, most significant byte first. -/
def bytesValue : List Byte → Nat
  | [] => 0
  | b :: bs => b.val * 256^bs.length + bytesValue bs

/-- The value to encode, from a byte sequence. `Fin.ofNat` reduces a number
modulo `2^128`, which leaves the value of 16 bytes unchanged. -/
def fromBytes (bs : List Byte) : Except Error UUID :=
  if bs.length = 16 then .ok (Fin.ofNat _ (bytesValue bs))
  else .error .invalidLength

/-- The value to encode, from an integer. -/
def fromInt (n : Int) : Except Error UUID :=
  if h : 0 ≤ n ∧ n ≤ 2^128 - 1 then .ok ⟨n.toNat, by omega⟩
  else .error .overflow

/-- Claim: 16 bytes have a value below `2^128`. -/
def BytesFit : Prop :=
  ∀ bs : List Byte, bs.length = 16 → bytesValue bs < 2^128

example : fromBytes [0xf4, 0xb2, 0x47, 0xfd, 0x1f, 0x87, 0x45, 0xd4,
    0xaa, 0x06, 0x1c, 0x6f, 0xc0, 0xa8, 0xdf, 0xaf]
    = .ok 0xf4b247fd1f8745d4aa061c6fc0a8dfaf := by decide
example : fromBytes (List.replicate 15 0) = .error .invalidLength := by decide
example : fromBytes (List.replicate 17 0) = .error .invalidLength := by decide
example : fromInt 0xf4b247fd1f8745d4aa061c6fc0a8dfaf =
    .ok 0xf4b247fd1f8745d4aa061c6fc0a8dfaf := by decide
example : fromInt (-1) = .error .overflow := by decide
example : fromInt (2^128) = .error .overflow := by decide
```

Types that can only hold 128-bit values, such as a 16-byte array, an
unsigned 128-bit integer, a pair of 64-bit integers taken as the high and low
halves, or a native UUID type, need no checks.

When converting from a native UUID type, use the 16 bytes in the order of
RFC 9562 (network byte order). Some platforms store UUIDs in a different
byte order internally; for example, .NET `Guid.ToByteArray()` returns the
first three fields in little-endian order.

## 4. Decoding

The input is a string `S`. Decoding either produces a 128-bit value or fails
with an error kind from Section 7. An implementation MUST perform the
following checks in this order and report the first one that fails:

1. *Length.* If `S` is not exactly 22 characters long, fail with
   `invalid_length`.
2. *Characters.* If any character of `S` is not in the alphabet, fail with
   `invalid_character`. Matching is case-sensitive.
3. *Range.* Compute `V = d[0] * 58^21 + ... + d[21] * 58^0`. If
   `V > 2^128 - 1`, fail with `overflow`. Equivalently, since all inputs at
   this step have the same length, fail if `S` is greater than `MAX_UUID58`
   in ASCII order (Section 3.2).

Otherwise the result is `V`.

```lean
/-- The digits of a string, or `none` if a character is not in the alphabet. -/
def parse : List Byte → Option (List Digit)
  | [] => some []
  | b :: bs => do return (← digit? b) :: (← parse bs)

def decode (s : List Byte) : Except Error UUID :=
  if s.length ≠ 22 then .error .invalidLength
  else match parse s with
    | none => .error .invalidCharacter
    | some ds =>
      if h : value ds < 2^128 then .ok ⟨value ds, h⟩ else .error .overflow

/-- Claim: decoding an encoding returns the value that was encoded. -/
def RoundTrip : Prop :=
  ∀ v : UUID, decode (encode v) = .ok v

/-- Claim: a value has no other valid spelling than its encoding. -/
def Canonical : Prop :=
  ∀ (s : List Byte) (v : UUID), decode s = .ok v → encode v = s

/-- Claim: the range check of step 3 is a comparison with `MAX_UUID58`. -/
def RangeByOrder : Prop :=
  ∀ s : List Byte, s.length = 22 → (∀ b ∈ s, b ∈ alphabet) →
    (decode s = .error .overflow ↔ maxUuid58 < s)
```

An implementation that returns bytes MUST return `V` as 16 bytes in
big-endian order. An implementation that returns a native UUID type MUST
build it from those bytes in the order of RFC 9562 (see Section 3.3 for
platforms whose native byte order differs).

```lean
/-- The `k` least significant bytes of `n`, most significant first, including
leading zero bytes. -/
def bytesOf : Nat → Nat → List Byte
  | 0, _ => []
  | k+1, n =>
    ⟨n / 256^k % 256, Nat.mod_lt _ (by decide)⟩ :: bytesOf k (n % 256^k)

def toBytes (v : UUID) : List Byte := bytesOf 16 v.val

/-- Claim: `toBytes` and `fromBytes` are inverse to each other on the 16-byte
sequences. -/
def BytesRoundTrip : Prop :=
  (∀ v : UUID, fromBytes (toBytes v) = .ok v) ∧
    ∀ (bs : List Byte) (v : UUID), fromBytes bs = .ok v → toBytes v = bs

example : toBytes 0xf4b247fd1f8745d4aa061c6fc0a8dfaf =
    [0xf4, 0xb2, 0x47, 0xfd, 0x1f, 0x87, 0x45, 0xd4,
      0xaa, 0x06, 0x1c, 0x6f, 0xc0, 0xa8, 0xdf, 0xaf] := by decide
```

The order matters when an input fails more than one check. For example,
`Zzzzzzzzzzzzzzzzzzzzz0` has digits that overflow, but its last character is
not in the alphabet, so it fails with `invalid_character`. An implementation
that rejects early, for example by comparing a prefix of `S` with
`MAX_UUID58` or by checking whether the first character is greater than `Y`,
MUST still report `invalid_character` if a later character is not in the
alphabet. (An implementation that accumulates `V` exactly cannot overflow
before the last digit, because `58^21 - 1 < 2^128`, so it gets this right
without special handling.)

```lean
example : decode (bytes "Zzzzzzzzzzzzzzzzzzzzz0") =
    .error .invalidCharacter := by decide
example : decode (bytes "Zzzzzzzzzzzzzzzzzzzzzz") =
    .error .overflow := by decide
example : 58^21 - 1 < 2^128 := by decide
```

Decoding MUST NOT trim whitespace, ignore unknown characters, or accept
strings shorter than 22 characters.

```lean
example : decode (bytes " XDY9dmBbcMBXqcRvYw8xJ2") =
    .error .invalidLength := by decide
example : decode (bytes "XDY9dmBbcMBXqcRvYw8xJ") =
    .error .invalidLength := by decide
```

### 4.1. Measuring length

Implementations MUST measure the length of `S` in one of these units: UTF-16
code units, Unicode code points, or bytes of UTF-8. They MUST NOT measure it
in grapheme clusters (user-perceived characters), which count some ASCII
sequences such as `\r\n` as one.

The three allowed units agree for ASCII input. Any input that contains a
non-ASCII character is invalid, but depending on the unit it fails either the
length check or the character check. For any input that contains a non-ASCII
character, an implementation MAY report either `invalid_length` or
`invalid_character`, whatever unit it uses. This also allows an
implementation to reject non-ASCII input before checking the length.

For string types that can hold arbitrary bytes or ill-formed text (such as
Go `string`, Rust `&[u8]`, or PHP and Ruby strings), any byte `0x80` or above,
any unpaired surrogate, and any ill-formed UTF-8 or UTF-16 sequence counts as
a non-ASCII character: the input MUST be rejected, with either kind.

The definitions below take the input as bytes: the bytes of a byte string,
and otherwise the UTF-8 encoding of the text. A string that has no UTF-8
encoding, such as one with an unpaired surrogate, is not ASCII.

```lean
/-- Whether every byte of an input is ASCII. -/
def isAscii (s : List Byte) : Bool := s.all (·.val < 128)

/-- The results that this section allows for the input `s`, where `exact` is
`decode` or `parseUuid` of Section 5: the result of `exact` for ASCII input,
and either of the two kinds for any other input. -/
abbrev Allowed (exact : List Byte → Except Error UUID) (s : List Byte)
    (r : Except Error UUID) : Prop :=
  if isAscii s then r = exact s
  else r = .error .invalidLength ∨ r = .error .invalidCharacter

/-- Claim: `decode`, which measures the length in bytes, returns an allowed
result for every input. -/
def DecodeAllowed : Prop :=
  ∀ s : List Byte, Allowed decode s (decode s)

example : Allowed decode (bytes "XDY9dmBbcMBXqcRvYw8xJŁ")
    (.error .invalidLength) := by decide
example : Allowed decode (bytes "XDY9dmBbcMBXqcRvYw8xJŁ")
    (.error .invalidCharacter) := by decide
example : ¬ Allowed decode (bytes "XDY9dmBbcMBXqcRvYw8xJ\r\n")
    (.error .invalidCharacter) := by decide
```

An implementation MUST NOT map a non-ASCII character to an ASCII one. This
includes keeping only its low 7 or 8 bits (U+0141 `Ł` is not `A`, even though
its low byte is `0x41`), applying Unicode normalization, comparing under
canonical or compatibility equivalence (U+212A KELVIN SIGN is not `K`, even
though Swift's `Character` comparison treats them as equal), and classifying
digits with Unicode-aware functions (U+FF10 FULLWIDTH DIGIT ZERO is not
`0`). Compare code units, code points, or bytes directly.

```lean
example : ¬ Allowed decode (bytes "XDY9dmBbcMBXqcRvYw8xJŁ")
    (decode (bytes "XDY9dmBbcMBXqcRvYw8xJA")) := by decide
```

## 5. UUID Strings

Implementations usually accept and produce UUIDs as text. This section
defines those forms. An implementation that only works with 16-byte or
128-bit integer values does not need to implement it.

### 5.1. Accepted forms

An implementation that encodes from a UUID string MUST accept exactly these
two forms, and MUST reject every other input:

 * *Hyphenated:* 36 characters. The characters at zero-based positions 8,
   13, 18, and 23 are `-`. Every other character is a hexadecimal digit.

   ```
   f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf
   ```

 * *Plain:* 32 hexadecimal digits.

   ```
   f4b247fd1f8745d4aa061c6fc0a8dfaf
   ```

A hexadecimal digit is `0`–`9`, `a`–`f`, or `A`–`F`. Upper and lower case
MUST both be accepted, including mixed case within one string.

The 32 hexadecimal digits, read left to right, are the 16 bytes of the UUID in
big-endian order.

```lean
def lowerHex := bytes "0123456789abcdef"
def upperHex := bytes "0123456789ABCDEF"

/-- A hexadecimal digit value in `0..15`. -/
abbrev HexDigit := Fin 16

/-- The lowercase character that writes a digit. -/
def hexSymbol (d : HexDigit) : Byte := lowerHex[d.val]!

/-- The digit that a character writes in either case, or `none` if it is not
a hexadecimal digit. -/
def hexDigit? (b : Byte) : Option HexDigit :=
  let i := min (lowerHex.idxOf b) (upperHex.idxOf b)
  if h : i < 16 then some ⟨i, h⟩ else none

/-- The digits of a string, or `none` if a character is not a hexadecimal
digit. -/
def parseHex : List Byte → Option (List HexDigit)
  | [] => some []
  | b :: bs => do return (← hexDigit? b) :: (← parseHex bs)

/-- The value of a hexadecimal digit sequence, most significant digit first. -/
def hexValue : List HexDigit → Nat
  | [] => 0
  | d :: ds => d.val * 16^ds.length + hexValue ds

/-- Claim: two hexadecimal digits for each byte, high digit first, have the
value of the bytes. -/
def HexIsBytes : Prop :=
  ∀ bs : List Byte,
    hexValue (bs.flatMap fun b =>
      [Fin.ofNat _ (b.val / 16), Fin.ofNat _ b.val]) = bytesValue bs

example : (bytes "09afAF").map hexDigit? =
    [some 0, some 9, some 10, some 15, some 10, some 15] := by decide
example : (bytes "gG-").map hexDigit? = [none, none, none] := by decide
```

Other notations, such as braces (`{...}`), the `urn:uuid:` prefix, or
surrounding whitespace, MUST be rejected. An implementation MAY offer a
separate, clearly named function that accepts them.

Parsing a UUID string MUST perform the following checks in this order:

1. If the length is neither 32 nor 36, fail with `invalid_length`.
2. If the string does not match the form for its length, fail with
   `invalid_character`. This includes a hyphen in the wrong position and, for
   a 36-character input, a missing hyphen.

```lean
/-- `U+002D`. -/
def hyphen : Byte := 0x2D

/-- The positions of the hyphens in the hyphenated form. -/
def hyphenAt : List Nat := [8, 13, 18, 23]

/-- A 36-character string without the characters at `hyphenAt`. -/
def unhyphenate (s : List Byte) : List Byte :=
  s.take 8 ++ (s.drop 9).take 4 ++ (s.drop 14).take 4 ++ (s.drop 19).take 4 ++
    s.drop 24

/-- The value of a string of 32 hexadecimal digits. `Fin.ofNat` reduces a
number modulo `2^128`, which leaves the value of 32 digits unchanged. -/
def hexUuid (s : List Byte) : Except Error UUID :=
  match parseHex s with
  | none => .error .invalidCharacter
  | some ds => .ok (Fin.ofNat _ (hexValue ds))

def parseUuid (s : List Byte) : Except Error UUID :=
  if s.length = 32 then hexUuid s
  else if s.length = 36 then
    if hyphenAt.all (fun i => s[i]? = some hyphen) then hexUuid (unhyphenate s)
    else .error .invalidCharacter
  else .error .invalidLength

/-- Claim: 32 hexadecimal digits have a value below `2^128`. -/
def HexFits : Prop :=
  ∀ ds : List HexDigit, ds.length = 32 → hexValue ds < 2^128

example : parseUuid (bytes "f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf") =
    .ok 0xf4b247fd1f8745d4aa061c6fc0a8dfaf := by decide
example : parseUuid (bytes "f4b247fd1f8745d4aa061c6fc0a8dfaf") =
    .ok 0xf4b247fd1f8745d4aa061c6fc0a8dfaf := by decide
example : parseUuid (bytes "F4B247FD-1f87-45D4-aa06-1C6FC0A8DFAF") =
    .ok 0xf4b247fd1f8745d4aa061c6fc0a8dfaf := by decide
example : parseUuid (bytes "{f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf}") =
    .error .invalidLength := by decide
example : parseUuid (bytes "urn:uuid:f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf") =
    .error .invalidLength := by decide
example : parseUuid (bytes "f4b247f-d1f87-45d4-aa06-1c6fc0a8dfaf") =
    .error .invalidCharacter := by decide
example : parseUuid (bytes "f4b247fd1f8745d4aa061c6fc0a8dfaf0000") =
    .error .invalidCharacter := by decide
```

Section 4.1 applies here too: length is measured the same way, and for input
that contains a non-ASCII character, an implementation MAY report either
`invalid_length` or `invalid_character`.

```lean
/-- Claim: `parseUuid` returns an allowed result for every input. -/
def ParseUuidAllowed : Prop :=
  ∀ s : List Byte, Allowed parseUuid s (parseUuid s)
```

> *Note (non-normative).* Standard-library UUID and integer parsers are
  usually more lenient than this section allows, so an implementation should
  not rely on them for validation. For example, Python's `uuid.UUID` accepts
  braces, the `urn:uuid:` prefix, and misplaced hyphens; Python's
  `int(s, 16)` accepts a leading `+` or `-` and `_` between digits; Java's
  `UUID.fromString` accepts groups shorter than their normal width; Rust's
  `u128::from_str_radix(s, 16)` accepts a leading `+`, and the `uuid` crate's
  `Uuid::parse_str` accepts braces and the `urn:uuid:` prefix; and in many
  regular expression engines `$` also matches before a trailing newline.
  Check every character explicitly instead.

### 5.2. Produced form

An implementation that decodes to a UUID string MUST produce the hyphenated
form in lowercase:

```
f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf
```

```lean
/-- The `k` least significant hexadecimal digits of `n`, most significant
first, including leading zero digits. -/
def hexDigits : Nat → Nat → List HexDigit
  | 0, _ => []
  | k+1, n =>
    ⟨n / 16^k % 16, Nat.mod_lt _ (by decide)⟩ :: hexDigits k (n % 16^k)

/-- A 32-character string with a hyphen inserted at each position in
`hyphenAt`. -/
def hyphenate (p : List Byte) : List Byte :=
  p.take 8 ++ hyphen :: (p.drop 8).take 4 ++ hyphen :: (p.drop 12).take 4 ++
    hyphen :: (p.drop 16).take 4 ++ hyphen :: p.drop 20

def formatUuid (v : UUID) : List Byte :=
  hyphenate ((hexDigits 32 v.val).map hexSymbol)

example : formatUuid 0xf4b247fd1f8745d4aa061c6fc0a8dfaf =
    bytes "f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf" := by decide
example : formatUuid 0x00000000000000000000000000000001 =
    bytes "00000000-0000-0000-0000-000000000001" := by decide

/-- Claim: parsing the produced form returns the value that was formatted. -/
def UuidRoundTrip : Prop :=
  ∀ v : UUID, parseUuid (formatUuid v) = .ok v

/-- Claim: the plain and the hyphenated form of the same digits have the same
result. -/
def HyphensOptional : Prop :=
  ∀ p : List Byte, p.length = 32 → parseUuid (hyphenate p) = parseUuid p
```

## 6. Validation

An implementation MAY offer a function that checks whether a string is a
valid uuid58 string without returning the value. If it does, the function
MUST return true exactly when decoding (Section 4) would succeed.

```lean
def isValid (s : List Byte) : Bool := (decode s).isOk
```

A pattern that checks only the length and the alphabet, such as the regular
expression `[1-9A-HJ-NP-Za-km-z]{22}` matched against the whole string, is
not sufficient on its own, because it accepts strings greater than
`MAX_UUID58`. It can serve as the first step, followed by an ASCII comparison
with `MAX_UUID58` (Section 4, step 3).

```lean
/-- Claim: a string is valid exactly when it has 22 characters of the alphabet
and is not greater than `MAX_UUID58`. -/
def ValidByPattern : Prop :=
  ∀ s : List Byte, isValid s = true ↔
    s.length = 22 ∧ (∀ b ∈ s, b ∈ alphabet) ∧ s ≤ maxUuid58
```

When using such a pattern, make sure it matches the entire input. In many
regular expression engines, `^...$` also matches when the input ends with a
newline, and in some (such as Ruby) `^` and `$` match at every line. Use a
full-match API or anchors such as `\A...\z` where available.

## 7. Errors

This specification defines the following error kinds. The Lean definitions
call them `invalidLength`, `invalidCharacter`, and `overflow`.

**`invalid_length`**

  Raised by UUID parsing, decoding, and encoding from bytes. The input has
  the wrong length (or contains a non-ASCII character; see Section 4.1).

**`invalid_character`**

  Raised by UUID parsing and decoding. The input has the right length but
  contains a character that is not allowed in its position (or, for input of
  any length, contains a non-ASCII character; see Section 4.1).

**`overflow`**

  Raised by decoding and by encoding from an integer. The input is well
  formed but its value is outside `0..2^128 - 1`.

How errors are reported (exceptions, result types, error values) is up to
each implementation. An implementation SHOULD let callers distinguish the
kinds. The wording of error messages is not specified.

Inputs are untrusted, and error messages commonly end up in logs, terminals,
and error trackers. An error message SHOULD NOT include the input itself; it
MAY include facts about it, such as its length or the position of the first
invalid character. An implementation that does include the input SHOULD
escape control and non-ASCII characters and SHOULD truncate long input, so
that an error message can neither span several lines nor grow with the input.

```lean
end Uuid58
```

## 8. Conformance

An implementation conforms to this specification if it passes every case in
[`vectors.json`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/vectors.json) that applies to the operations it implements.

### 8.1. Test vector format

```
{
  "spec_version": "1.1.1",
  "alphabet": "123456789ABC...",
  // Pairs that MUST round-trip in both directions.
  // `uuid` is the produced form (Section 5.2).
  "roundtrip": [
    { "description": "...", "uuid": "00000000-...", "uuid58": "1111..." },
  ],
  "encode": {
    // Additional accepted UUID strings and the uuid58 they encode to.
    "valid": [
      { "description": "...", "input": "F4B2...", "output": "XDY9..." },
    ],
    // UUID strings that MUST be rejected.
    "invalid": [
      {
        "description": "...",
        "input": "...",
        // The input MUST fail with one of these kinds.
        "errors": ["invalid_length"],
        // Optional. Present only on inputs that JavaScript 1.x accepts
        // (Section 9.1), together with the value it returns for them.
        "lenient": true,
        "lenient_output": "XDY9...",
      },
    ],
    // For APIs that encode from a byte sequence of any length (Section 3.3).
    // APIs that take a fixed 16-byte array skip these.
    // `bytes` is the byte sequence written as hexadecimal.
    "invalid_bytes": [
      {
        "description": "...",
        "bytes": "0000...",
        "errors": ["invalid_length"],
      },
    ],
    // For APIs that encode from an arbitrary-precision or signed integer
    // (Section 3.3). `integer` is written in decimal.
    "invalid_integers": [
      { "description": "...", "integer": "-1", "errors": ["overflow"] },
    ],
  },
  "decode": {
    // uuid58 strings that MUST be rejected. Valid ones are in `roundtrip`.
    "invalid": [
      { "description": "...", "input": "...", "errors": ["overflow"] },
    ],
  },
}
```

An implementation that does not report error kinds only needs to check that
each invalid input fails.

JSON strings cannot hold ill-formed text, so `vectors.json` cannot express
the inputs of Section 4.1 that are not valid Unicode. An implementation whose
string type can hold arbitrary bytes or unpaired surrogates MUST also test
such inputs itself, both for decoding and for UUID string parsing. Examples
are a 22-byte input containing `0xFF`, an input containing a lone `0x80` or
`0xC1` byte, a 36-byte UUID string with `0xFF` in place of a hexadecimal
digit, or a lone surrogate.

An implementation that works with 16-byte or integer values instead of UUID
strings (Section 5) can still use `roundtrip`: remove the hyphens from `uuid`
and read the 32 hexadecimal digits as 16 bytes in big-endian order (or as an
unsigned integer in base 16).

An implementation that works with a native UUID type MUST NOT test only by
round-tripping its own values, which would hide a byte-order mistake.
It MUST compare the decoded value against `uuid`, either through the type's
canonical text form or through the 16 bytes derived from `uuid` as above.

`encode.valid` and `encode.invalid` test UUID string parsing (Section 5). An
implementation that does not parse UUID strings, for example one that only
works with a native UUID type, bytes, or integers, skips them. An
implementation that parses UUID strings in addition to other inputs MUST
test them.

An implementation of validation (Section 6) MUST return true for every
`uuid58` in `roundtrip` and false for every `input` in `decode.invalid`.

### 8.2. Regenerating the vectors

`vectors.json` is generated by `generate_vectors.py`, an independent reference
implementation that uses only the Python standard library. Do not edit
`vectors.json` by hand.

```
python3 spec/generate_vectors.py          # rewrite vectors.json
python3 spec/generate_vectors.py --check  # fail if vectors.json is stale
```

The [formal check](https://github.com/nakanoasaservice/uuid58/blob/main/formal/README.md) also runs every vector through the
definitions of this document.

### 8.3. Building this document

This page is generated from `Spec.lean` by [`build.sh`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/build.sh),
which needs the Lean version in
[`formal/lean-toolchain`](https://github.com/nakanoasaservice/uuid58/blob/main/formal/lean-toolchain). The build fails if Lean
rejects a code block. The page leaves out the proof states of the code
blocks, so that tools reading it as text see only the code. The build also
writes the Markdown version with
[`markdown.py`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/markdown.py), which copies
the prose and the code blocks and drops the Verso markup.

```
spec/build.sh      # write the page to spec/_out/html-single
```

## 9. Known Deviations

### 9.1. JavaScript `@nakanoaas/uuid58` 1.x

Before this specification, the JavaScript package accepted any string that
becomes 32 hexadecimal digits after removing every `-`, wherever the hyphens
are and however many there are (for example
`f4b247f-d1f87-45d4-aa06-1c6fc0a8dfaf`). This violates Section 5.1.

To stay compatible, 1.x keeps this behavior. The test vectors mark these
inputs with `"lenient": true` and give the value 1.x returns in
`lenient_output`. Version 2.0 and later of the JavaScript package reject them
as this specification requires, and expose error kinds through the `kind`
property of their errors. New implementations MUST NOT accept them.

1.x also differs from Section 7 in how it reports errors:

 * It does not expose error kinds. It throws (or, in the `Safe` variants,
   returns) `Uuid58EncodeError` or `Uuid58DecodeError`, distinguished only by
   their messages.
 * Its encoder checks the length after removing the hyphens. So for any input
   whose length changes when hyphens are removed, or that is 36 characters
   long without being hyphenated, the wording of its messages may not match
   the kind this specification assigns. For example, 36 hexadecimal digits
   without hyphens, `f4b247fd_1f87_45d4_aa06_1c6fc0a8dfaf`, and
   `-4b247fd1f8745d4aa061c6fc0a8dfaf` get a message about the length, where
   Section 5.1 assigns `invalid_character`.

The wording of error messages is not part of this specification, so these
are not conformance failures, but they should not be mapped to kinds by
parsing the message.

## 10. Change History

**1.1.1 (2026-11-30)**

  The specification became a Lean file, which Lean checks. Sections 2 to 6
  gained Lean definitions, which govern if prose and definition disagree
  (Section 1.3). Section 4.1
  says how those definitions read an input as bytes. No requirement on
  implementations changed, and the test cases are the same.

**1.1.0 (2026-11-18)**

  Section 7 recommends that error messages leave the input
  out. Conformance did not change.

**1.0.0 (2026-11-15)**

  First release.
