Skip to content

Commit fee9bfd

Browse files
committed
Fix address version processing in Base58 encoding/decoding
1 parent c5c21fd commit fee9bfd

File tree

2 files changed

+33
-16
lines changed

2 files changed

+33
-16
lines changed

base58.go

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,38 +22,31 @@ func Base58Encode(input []byte) []byte {
2222
result = append(result, b58Alphabet[mod.Int64()])
2323
}
2424

25-
ReverseBytes(result)
26-
for _, b := range input {
27-
if b == 0x00 {
28-
result = append([]byte{b58Alphabet[0]}, result...)
29-
} else {
30-
break
31-
}
25+
// https://en.bitcoin.it/wiki/Base58Check_encoding#Version_bytes
26+
if input[0] == 0x00 {
27+
result = append(result, b58Alphabet[0])
3228
}
3329

30+
ReverseBytes(result)
31+
3432
return result
3533
}
3634

3735
// Base58Decode decodes Base58-encoded data
3836
func Base58Decode(input []byte) []byte {
3937
result := big.NewInt(0)
40-
zeroBytes := 0
4138

4239
for _, b := range input {
43-
if b == 0x00 {
44-
zeroBytes++
45-
}
46-
}
47-
48-
payload := input[zeroBytes:]
49-
for _, b := range payload {
5040
charIndex := bytes.IndexByte(b58Alphabet, b)
5141
result.Mul(result, big.NewInt(58))
5242
result.Add(result, big.NewInt(int64(charIndex)))
5343
}
5444

5545
decoded := result.Bytes()
56-
decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...)
46+
47+
if input[0] == b58Alphabet[0] {
48+
decoded = append([]byte{0x00}, decoded...)
49+
}
5750

5851
return decoded
5952
}

base58_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package main
2+
3+
import (
4+
"encoding/hex"
5+
"log"
6+
"strings"
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func TestBase58(t *testing.T) {
13+
rawHash := "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
14+
hash, err := hex.DecodeString(rawHash)
15+
if err != nil {
16+
log.Fatal(err)
17+
}
18+
19+
encoded := Base58Encode(hash)
20+
assert.Equal(t, "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", string(encoded))
21+
22+
decoded := Base58Decode([]byte("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"))
23+
assert.Equal(t, strings.ToLower("00010966776006953D5567439E5E39F86A0D273BEED61967F6"), hex.EncodeToString(decoded))
24+
}

0 commit comments

Comments
 (0)