-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathbase58check.go
More file actions
58 lines (50 loc) · 1.8 KB
/
base58check.go
File metadata and controls
58 lines (50 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright (c) 2013-2014 The btcsuite developers
// Copyright (c) 2015-2019 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package base58
import (
"bytes"
"errors"
"github.com/decred/dcrd/crypto/blake256"
)
// ErrChecksum indicates that the checksum of a check-encoded string does not
// verify against the checksum.
var ErrChecksum = errors.New("checksum error")
// ErrInvalidFormat indicates that the check-encoded string has an invalid
// format.
var ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing")
// checksum returns the first four bytes of BLAKE256(BLAKE256(input)).
func checksum(input []byte) [4]byte {
var calculatedChecksum [4]byte
intermediateHash := blake256.Sum256(input)
finalHash := blake256.Sum256(intermediateHash[:])
copy(calculatedChecksum[:], finalHash[:])
return calculatedChecksum
}
// CheckEncode prepends two version bytes and appends a four byte checksum.
func CheckEncode(input []byte, version [2]byte) string {
b := make([]byte, 0, 2+len(input)+4)
b = append(b, version[:]...)
b = append(b, input...)
calculatedChecksum := checksum(b)
b = append(b, calculatedChecksum[:]...)
return Encode(b)
}
// CheckDecode decodes a string that was encoded with [CheckEncode] and verifies
// the checksum.
func CheckDecode(input string) ([]byte, [2]byte, error) {
decoded := Decode(input)
if len(decoded) < 6 {
return nil, [2]byte{0, 0}, ErrInvalidFormat
}
version := [2]byte{decoded[0], decoded[1]}
dataLen := len(decoded) - 4
decodedChecksum := decoded[dataLen:]
calculatedChecksum := checksum(decoded[:dataLen])
if !bytes.Equal(decodedChecksum, calculatedChecksum[:]) {
return nil, [2]byte{0, 0}, ErrChecksum
}
payload := decoded[2:dataLen]
return payload, version, nil
}