File tree Expand file tree Collapse file tree 2 files changed +33
-16
lines changed Expand file tree Collapse file tree 2 files changed +33
-16
lines changed Original file line number Diff line number Diff line change @@ -22,38 +22,31 @@ func Base58Encode(input []byte) []byte {
22
22
result = append (result , b58Alphabet [mod .Int64 ()])
23
23
}
24
24
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 ])
32
28
}
33
29
30
+ ReverseBytes (result )
31
+
34
32
return result
35
33
}
36
34
37
35
// Base58Decode decodes Base58-encoded data
38
36
func Base58Decode (input []byte ) []byte {
39
37
result := big .NewInt (0 )
40
- zeroBytes := 0
41
38
42
39
for _ , b := range input {
43
- if b == 0x00 {
44
- zeroBytes ++
45
- }
46
- }
47
-
48
- payload := input [zeroBytes :]
49
- for _ , b := range payload {
50
40
charIndex := bytes .IndexByte (b58Alphabet , b )
51
41
result .Mul (result , big .NewInt (58 ))
52
42
result .Add (result , big .NewInt (int64 (charIndex )))
53
43
}
54
44
55
45
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
+ }
57
50
58
51
return decoded
59
52
}
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments