BitcoinElixir.HD (bitcoin_elixir v0.1.0)

Copy Markdown View Source

Watch-only BIP32: parse an extended public key (xpub, or tpub for test networks) and derive child public keys and addresses from it. No private key is ever involved, so a server can make a fresh address for every invoice while the wallet that owns the xpub keeps the money.

Public child derivation is K_i = point(IL) + K, where IL is the left half of HMAC-SHA512(chain_code, serP(K) || ser32(i)). point(IL) comes from Erlang's :crypto; the point addition is done here with integer arithmetic. Only public data passes through this module.

{:ok, account} = BitcoinElixir.HD.parse("xpub6C…")
BitcoinElixir.HD.address(account, [0, 5])
#=> "bitcoincash:q…"   # the receive address at index 5 (…/0/5)

Summary

Functions

The P2PKH address of the node at path below node. Options: :tokens (default false) for the token-aware z… form, and :prefix (default from the node's network: "bitcoincash" or "bchtest").

The child at a non-hardened index. Hardened children need the private key, so they are refused. Returns {:error, :invalid_child} in the (about 2^-127) case BIP32 says to skip.

Derive along a list of non-hardened indexes, such as [0, 7].

Like derive/2 but raises.

HASH160 of the node's compressed public key (the P2PKH payload).

Parse an xpub or tpub.

Write a node back out as an xpub or tpub.

Types

network()

@type network() :: :mainnet | :testnet

t()

@type t() :: %BitcoinElixir.HD{
  chain_code: binary(),
  child_number: non_neg_integer(),
  depth: non_neg_integer(),
  network: network(),
  parent_fingerprint: binary(),
  public_key: binary()
}

Functions

address(node, path \\ [], opts \\ [])

@spec address(t(), [non_neg_integer()], keyword()) :: String.t()

The P2PKH address of the node at path below node. Options: :tokens (default false) for the token-aware z… form, and :prefix (default from the node's network: "bitcoincash" or "bchtest").

child(node, index)

@spec child(t(), non_neg_integer()) :: {:ok, t()} | {:error, atom()}

The child at a non-hardened index. Hardened children need the private key, so they are refused. Returns {:error, :invalid_child} in the (about 2^-127) case BIP32 says to skip.

derive(node, path)

@spec derive(t(), [non_neg_integer()]) :: {:ok, t()} | {:error, atom()}

Derive along a list of non-hardened indexes, such as [0, 7].

derive!(node, path)

@spec derive!(t(), [non_neg_integer()]) :: t()

Like derive/2 but raises.

key_hash(hd)

@spec key_hash(t()) :: binary()

HASH160 of the node's compressed public key (the P2PKH payload).

parse(text)

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

Parse an xpub or tpub.

serialize(node)

@spec serialize(t()) :: String.t()

Write a node back out as an xpub or tpub.