Correct padding error

This commit is contained in:
David Ellefsen 2013-08-18 19:50:57 +02:00
parent 26c330e886
commit c5319e77a8
2 changed files with 30 additions and 9 deletions

View File

@ -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
```

View File

@ -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.