diff --git a/lib/address.ex b/lib/address.ex index 91ba9eb..2b110fe 100644 --- a/lib/address.ex +++ b/lib/address.ex @@ -34,6 +34,13 @@ defmodule Bitcoinex.Address do Base58.encode(<> <> script_hash) end + def encode(script_hash, network_name, :p2wpkh) do + case Segwit.encode_address(network_name, 0, :binary.bin_to_list(script_hash)) do + {:ok, address} -> address + {:error, _} -> "" + end + end + @doc """ Checks if the address is valid. Both encoding and network is checked. diff --git a/test/address_test.exs b/test/address_test.exs index a351bee..2e8f10e 100644 --- a/test/address_test.exs +++ b/test/address_test.exs @@ -249,5 +249,14 @@ defmodule Bitcoinex.AddressTest do script_hash = Base.decode16!("6d77fa9de297e9c536c6b23cfda1a8450bb5f765", case: :lower) assert "3BfqJjn7H2jsbKd2NVHGP4sQWQ2bQWBRLv" == Address.encode(script_hash, :mainnet, :p2sh) end + + test "return true for encoding p2wpkh" do + script_hash = "751e76e8199196d454941c45d1b3a323f1433bd6" + + script_hash = Base.decode16!(script_hash, case: :lower) + + assert "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4" == + Address.encode(script_hash, :mainnet, :p2wpkh) + end end end