| 1 |
// Copyright (c) 2013-2014 The btcsuite developers |
| 2 |
// Use of this source code is governed by an ISC |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package base58 |
| 6 |
|
| 7 |
import ( |
| 8 |
"crypto/sha256" |
| 9 |
"errors" |
| 10 |
) |
| 11 |
|
| 12 |
// ErrChecksum indicates that the checksum of a check-encoded string does not verify against |
| 13 |
// the checksum. |
| 14 |
var ErrChecksum = errors.New("checksum error") |
| 15 |
|
| 16 |
// ErrInvalidFormat indicates that the check-encoded string has an invalid format. |
| 17 |
var ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing") |
| 18 |
|
| 19 |
// checksum: first four bytes of sha256^2 |
| 20 |
func checksum(input []byte) (cksum [4]byte) { |
| 21 |
h := sha256.Sum256(input) |
| 22 |
h2 := sha256.Sum256(h[:]) |
| 23 |
copy(cksum[:], h2[:4]) |
| 24 |
return |
| 25 |
} |
| 26 |
|
| 27 |
// CheckEncode prepends a version byte and appends a four byte checksum. |
| 28 |
func CheckEncode(input []byte, version byte) string { |
| 29 |
b := make([]byte, 0, 1+len(input)+4) |
| 30 |
b = append(b, version) |
| 31 |
b = append(b, input...) |
| 32 |
cksum := checksum(b) |
| 33 |
b = append(b, cksum[:]...) |
| 34 |
return Encode(b) |
| 35 |
} |
| 36 |
|
| 37 |
// CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum. |
| 38 |
func CheckDecode(input string) (result []byte, version byte, err error) { |
| 39 |
decoded := Decode(input) |
| 40 |
if len(decoded) < 5 { |
| 41 |
return nil, 0, ErrInvalidFormat |
| 42 |
} |
| 43 |
version = decoded[0] |
| 44 |
var cksum [4]byte |
| 45 |
copy(cksum[:], decoded[len(decoded)-4:]) |
| 46 |
if checksum(decoded[:len(decoded)-4]) != cksum { |
| 47 |
return nil, 0, ErrChecksum |
| 48 |
} |
| 49 |
payload := decoded[1 : len(decoded)-4] |
| 50 |
result = append(result, payload...) |
| 51 |
return |
| 52 |
} |