Packages
Bitcoin Cash for Elixir: addresses, HD keys and BIP39, transactions with CashTokens, building and signing, a payment watcher, token metadata (BCMR), prices, and an Electrum/Fulcrum client.
Current section
Files
Jump to
Current section
Files
bitcoin_elixir
README.md
README.md
# BitcoinElixir
Bitcoin Cash for Elixir.
- **CashAddr**: encode and decode every address type, including the
token-aware `z…` and `r…` forms from CashTokens.
- **HD keys**: derive receive addresses from an `xpub` with no private key, so
a server can give every invoice its own address; or use private keys from an
`xprv`, a WIF, or a BIP39 recovery phrase.
- **Scripts**: locking scripts and the Electrum scripthash of an address.
- **Electrum / Fulcrum client**: batch requests with failover, and a
long-lived connection with live address and block notifications.
- **Payment links**: build and parse `bitcoincash:` URIs with exact amounts.
- **Transactions**: decode and encode transactions, including CashTokens on
outputs (category, amount, NFT commitment and capability), and block headers.
- **Send**: choose coins, pay the fee, add change, keep every CashToken (the
builder refuses to burn any), sign with SIGHASH_ALL|FORKID|UTXOS, and
broadcast with readable errors.
- **Signed messages**: sign and verify the "Bitcoin Signed Message" format.
- **Token metadata (BCMR)**: names, symbols, decimals, icons and NFT types,
found through each token's authchain and checked against the hash on chain.
- **Prices**: exact conversion between fiat and satoshis (no floats), and the
BCH price from public sources with failover.
- **Legacy addresses**: convert `1…`/`3…` addresses to CashAddr and back.
- **Payment watcher**: give it an address and an amount; get events when the
payment is seen, confirmed, short, over, expired or double-spent. It uses
live subscriptions, double-spend proofs and polling as a fallback.
No native dependencies: everything runs on Erlang's `:crypto` and `:ssl`.
Private-key operations (public keys, ECDSA signing) are done by `:crypto`
(OpenSSL); the library's own curve arithmetic only touches public data.
Tested against [libauth](https://libauth.org) vectors.
## Install
```elixir
def deps do
[{:bitcoin_elixir, "~> 0.1"}]
end
```
## Examples
```elixir
alias BitcoinElixir.{CashAddr, HD, Script, PaymentURI, Electrum}
# A fresh receive address for invoice 42, from the shop's account xpub
{:ok, account} = HD.parse("xpub6C…")
address = HD.address(account, [0, 42])
token_address = HD.address(account, [0, 42], tokens: true)
# Addresses
{:ok, %CashAddr{type: :p2pkh, hash: hash}} = CashAddr.decode(address)
{:ok, z} = CashAddr.to_token_aware(address)
# A payment link for 0.0015 BCH (amounts are whole satoshis)
PaymentURI.build(address, amount: 150_000, label: "Order 42")
# Look the address up on Electrum servers
servers = Electrum.default_servers(:mainnet)
{:ok, utxos} =
Electrum.request("blockchain.scripthash.listunspent", [Script.scripthash!(address)], servers: servers)
# Send from a recovery phrase
seed = BitcoinElixir.BIP39.to_seed("abandon abandon … about")
{:ok, wallet} = HD.derive_path(HD.from_seed(seed), "m/44'/145'/0'")
key = HD.derive!(wallet, [0, 0]).private_key
from = HD.address(wallet, [0, 0])
{:ok, utxos} = Electrum.request("blockchain.scripthash.listunspent", [Script.scripthash!(from)], servers: servers)
coins = Enum.map(utxos, &BitcoinElixir.Builder.coin_from_electrum(&1, from, key))
{:ok, %{hex: hex}} = BitcoinElixir.Builder.build(coins, [%{address: "bitcoincash:q…", value: 20_000}], change_address: from)
{:ok, txid} = Electrum.broadcast(hex, servers: servers)
# Token metadata, checked against the registry hash published on chain
{:ok, meta} = BitcoinElixir.BCMR.fetch(category, servers: servers)
{meta.name, meta.symbol, meta.decimals}
# Prices: $19.99 in satoshis at the live rate, rounded so the payer covers the price
{:ok, %{rate: rate}} = BitcoinElixir.Price.fetch("USD")
sats = BitcoinElixir.Price.to_sats(1_999, rate)
# Legacy addresses
{:ok, cashaddr} = CashAddr.from_legacy("1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu")
# Sign and verify a message
sig = BitcoinElixir.Message.sign("I control this address", key)
BitcoinElixir.Message.verify("I control this address", sig, from)
# Or let the watcher handle it
{:ok, watcher} = BitcoinElixir.Watcher.start_link(servers: servers, notify: self())
:ok = BitcoinElixir.Watcher.watch(watcher, "order-42", address,
amount: 150_000, expires_at: DateTime.add(DateTime.utc_now(), 15 * 60))
receive do
{:bitcoin_elixir_watcher, ^watcher, %BitcoinElixir.Watcher.Event{type: :seen}} -> :payment_received
end
# Decode a transaction, tokens included
{:ok, raw} = Electrum.request("blockchain.transaction.get", [txid], servers: servers)
{:ok, tx} = BitcoinElixir.Transaction.decode(raw)
for out <- tx.outputs, do: {out.value, out.token}
# Or watch an address yourself
{:ok, conn} = Electrum.Connection.start_link(servers: servers)
{:ok, _status} = Electrum.Connection.subscribe_scripthash(conn, Script.scripthash!(address))
receive do
{:electrum, ^conn, {:scripthash, _scripthash, _new_status}} -> :check_the_address_again
end
```
Put `Electrum.Connection` in your supervision tree with a `:name` to share
one connection across your app. Public servers are fine to start with; run
your own [Fulcrum](https://github.com/cculianu/Fulcrum) for production.
## Status
0.4 can watch, decode, build, sign and broadcast P2PKH transactions with
CashTokens, read token metadata and convert prices. Not yet: Schnorr signing
(verification only), multisig and other script types. Signed transactions are
checked in development with libauth's Bitcoin Cash virtual machine; the code
passes Dialyzer.
## Development
```bash
mix deps.get
mix test
mix docs
```
Test vectors in `test/fixtures` were generated with libauth 3.0.
## Licence
MIT. Built by [Septem Labs](https://septemlabs.com) for Cashlet and Enkaji.