diff --git a/README.md b/README.md index bc15abf..16ab532 100644 --- a/README.md +++ b/README.md @@ -12,19 +12,19 @@ The following example demonstrates the usage of this module: ```erlang 1> base58:integer_to_base58(16#00010966776006953D5567439E5E39F86A0D273BEED61967F6). -"6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM" -2> base58:base58_to_integer("6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"). +"16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM" +2> base58:base58_to_integer("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"). 25420294593250030202636073700053352635053786165627414518 -3> base58:base58_to_integer("6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM") == 16#00010966776006953D5567439E5E39F86A0D273BEED61967F6. +3> base58:base58_to_integer("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM") == 16#00010966776006953D5567439E5E39F86A0D273BEED61967F6. true 4> base58:binary_to_base58(binary:encode_unsigned(16#00010966776006953D5567439E5E39F86A0D273BEED61967F6)). -"6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM" +"16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM" 5> base58:base58_to_binary("6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"). -<<1,9,102,119,96,6,149,61,85,103,67,158,94,57,248,106,13, +<<0, 1,9,102,119,96,6,149,61,85,103,67,158,94,57,248,106,13, 39,59,238,214,25,103,246>> -6> base58:check_base58("6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"). +6> base58:check_base58("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"). true -7> base58:check_base58("6UwLL9Risc3QfPqBUvKofHmBQ7wMtjv0"). +7> base58:check_base58("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjv0"). false ``` diff --git a/src/base58.erl b/src/base58.erl index 6653326..e6c1b6c 100644 --- a/src/base58.erl +++ b/src/base58.erl @@ -192,7 +192,11 @@ base58_to_integer([Char | Str]) -> -spec base58_to_binary(base58()) -> binary(). base58_to_binary(Base58) -> - binary:encode_unsigned(base58_to_integer(Base58)). + Bin = binary:encode_unsigned(base58_to_integer(Base58)), + %The conversion between the binary and the integer strips any leading zero bytes that + % might have appeared in the binary - '0's' should be prepended to the binary stream for each + % 1 that appeared at the start of the base58 string. + zeroPad(Base58, Bin). %% @doc Convert a binary into a Base58 encoded string. The resulting Base58 %% encoded string will be in a big-endian representation of the original binary. @@ -203,5 +207,22 @@ base58_to_binary(Base58) -> binary_to_base58(Binary) when is_binary(Binary) -> case integer_to_base58(binary:decode_unsigned(Binary)) of error -> error; - Base58 -> Base58 + Base58 -> + % see above comment - just the reverse + binaryPad(binary_to_list(Binary), Base58) end. + +%% @doc Pad a "1" character to a Base58 stream to account for any stripped zeros +%% +%% @spec binaryPad(list(), base58()) +binaryPad([0 | Rest], Bin) -> + binaryPad(Rest, "1" ++ Bin); +binaryPad(_, Bin) -> Bin. + +%% @doc Pad a zero byte to a Base58 stream to account for any leading 1's +%% +%% @spec zeroPad(base58(), binary()) + +zeroPad("1" ++ Rest, Base58) -> + zeroPad(Rest, <<0, Base58/binary>>); +zeroPad(_, Base58) -> Base58.