Fix address version processing in Base58 encoding/decoding

This commit is contained in:
Ivan Kuznetsov 2018-01-29 15:53:44 +07:00
parent c5c21fd069
commit fee9bfd3af
2 changed files with 33 additions and 16 deletions

View File

@ -22,38 +22,31 @@ func Base58Encode(input []byte) []byte {
result = append(result, b58Alphabet[mod.Int64()])
}
ReverseBytes(result)
for _, b := range input {
if b == 0x00 {
result = append([]byte{b58Alphabet[0]}, result...)
} else {
break
}
// https://en.bitcoin.it/wiki/Base58Check_encoding#Version_bytes
if input[0] == 0x00 {
result = append(result, b58Alphabet[0])
}
ReverseBytes(result)
return result
}
// Base58Decode decodes Base58-encoded data
func Base58Decode(input []byte) []byte {
result := big.NewInt(0)
zeroBytes := 0
for _, b := range input {
if b == 0x00 {
zeroBytes++
}
}
payload := input[zeroBytes:]
for _, b := range payload {
charIndex := bytes.IndexByte(b58Alphabet, b)
result.Mul(result, big.NewInt(58))
result.Add(result, big.NewInt(int64(charIndex)))
}
decoded := result.Bytes()
decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...)
if input[0] == b58Alphabet[0] {
decoded = append([]byte{0x00}, decoded...)
}
return decoded
}

24
base58_test.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"encoding/hex"
"log"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBase58(t *testing.T) {
rawHash := "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
hash, err := hex.DecodeString(rawHash)
if err != nil {
log.Fatal(err)
}
encoded := Base58Encode(hash)
assert.Equal(t, "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", string(encoded))
decoded := Base58Decode([]byte("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"))
assert.Equal(t, strings.ToLower("00010966776006953D5567439E5E39F86A0D273BEED61967F6"), hex.EncodeToString(decoded))
}