BitcoinElixir.CashAddr (bitcoin_elixir v0.1.0)

Copy Markdown View Source

Encode and decode Bitcoin Cash addresses (CashAddr), including the token-aware types from CHIP-2022-02 CashTokens.

An address is a prefix ("bitcoincash", "bchtest" or "bchreg"), a type and a payload: a 20-byte hash for P2PKH, a 20- or 32-byte hash for P2SH.

iex> {:ok, addr} = BitcoinElixir.CashAddr.decode("bitcoincash:qq8hepxlmyfelgyfy985tw80r8pe805gfv230d2ufw")
iex> {addr.prefix, addr.type}
{"bitcoincash", :p2pkh}
iex> BitcoinElixir.CashAddr.to_token_aware("bitcoincash:qq8hepxlmyfelgyfy985tw80r8pe805gfv230d2ufw")
{:ok, "bitcoincash:zq8hepxlmyfelgyfy985tw80r8pe805gfvdmuny6ka"}

Summary

Functions

Decode an address. Without a prefix in the text, default_prefix is used ("bitcoincash" unless given). Upper case is accepted; mixed case is not.

Encode a prefix, type and hash as an address.

Like encode/3 but raises on bad input.

The prefix for a network.

The same address with its plain type (q… or p…).

The same address with its token-aware type (z… or r…).

True for types that can receive CashTokens.

True if the text is a valid address. With a prefix, it must also match it.

Types

prefix()

@type prefix() :: String.t()

t()

@type t() :: %BitcoinElixir.CashAddr{hash: binary(), prefix: prefix(), type: type()}

type()

@type type() :: :p2pkh | :p2sh | :p2pkh_with_tokens | :p2sh_with_tokens

Functions

decode(text, default_prefix \\ "bitcoincash")

@spec decode(String.t(), prefix()) :: {:ok, t()} | {:error, atom()}

Decode an address. Without a prefix in the text, default_prefix is used ("bitcoincash" unless given). Upper case is accepted; mixed case is not.

encode(prefix, type, hash)

@spec encode(prefix(), type(), binary()) :: {:ok, String.t()} | {:error, atom()}

Encode a prefix, type and hash as an address.

encode!(prefix, type, hash)

@spec encode!(prefix(), type(), binary()) :: String.t()

Like encode/3 but raises on bad input.

prefix(atom)

@spec prefix(:mainnet | :testnet | :regtest) :: prefix()

The prefix for a network.

to_plain(text)

@spec to_plain(String.t()) :: {:ok, String.t()} | {:error, atom()}

The same address with its plain type (q… or p…).

to_token_aware(text)

@spec to_token_aware(String.t()) :: {:ok, String.t()} | {:error, atom()}

The same address with its token-aware type (z… or r…).

token_aware?(type)

@spec token_aware?(t() | type()) :: boolean()

True for types that can receive CashTokens.

valid?(text, prefix \\ nil)

@spec valid?(String.t(), prefix() | nil) :: boolean()

True if the text is a valid address. With a prefix, it must also match it.