Cartouche.Base58 (Cartouche v0.2.0)

Copy Markdown View Source

Base58 encoding and decoding using the Bitcoin/Solana alphabet.

This is plain Base58, NOT Base58Check (no version prefix or checksum). Used by Solana for public keys (addresses) and transaction signatures.

If you use Cartouche.Base58, you get the ~B58 sigil for compile-time Base58-to-binary decoding.

Examples

iex> Cartouche.Base58.encode(<<0, 0, 0>>)
"111"

iex> Cartouche.Base58.encode(<<0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21>>)
"2NEpo7TZRRrLZSi2U"

iex> Cartouche.Base58.decode("2NEpo7TZRRrLZSi2U")
{:ok, "Hello World!"}

iex> Cartouche.Base58.decode("abc0def")
{:error, {:invalid_character, "0"}}

Summary

Functions

Decode a Base58 string to a binary.

Decode a Base58 string to a binary, raising on invalid input.

Encode a binary to a Base58 string.

Handles the sigil ~B58 for compile-time Base58 decoding.

Functions

decode(string)

@spec decode(String.t()) ::
  {:ok, binary()} | {:error, {:invalid_character, String.t()}}

Decode a Base58 string to a binary.

Returns {:ok, binary} on success, or {:error, {:invalid_character, char}} if the string contains characters outside the Base58 alphabet.

Examples

iex> Cartouche.Base58.decode("")
{:ok, <<>>}

iex> Cartouche.Base58.decode("1")
{:ok, <<0>>}

iex> Cartouche.Base58.decode("2g")
{:ok, <<0x61>>}

decode!(string)

@spec decode!(String.t()) :: binary()

Decode a Base58 string to a binary, raising on invalid input.

Examples

iex> Cartouche.Base58.decode!("2g")
<<0x61>>

encode(binary)

@spec encode(binary()) :: String.t()

Encode a binary to a Base58 string.

Each leading zero byte in the input produces a "1" character in the output.

Examples

iex> Cartouche.Base58.encode(<<>>)
""

iex> Cartouche.Base58.encode(<<0>>)
"1"

iex> Cartouche.Base58.encode(<<0x61>>)
"2g"

sigil_B58(term, modifiers)

(macro)

Handles the sigil ~B58 for compile-time Base58 decoding.

Decodes a Base58 string to binary at compile time, raising on invalid input. Uses uppercase B58 because Elixir multi-character sigils require uppercase letters.

Examples

iex> use Cartouche.Base58
iex> ~B58[11111111111111111111111111111111]
<<0::256>>

iex> use Cartouche.Base58
iex> ~B58[TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA]
<<6, 221, 246, 225, 215, 101, 161, 147, 217, 203, 225, 70, 206, 235, 121, 172, 28, 180, 133, 237, 95, 91, 55, 145, 58, 140, 245, 133, 126, 255, 0, 169>>