-
Notifications
You must be signed in to change notification settings - Fork 95
/
checksum.go
80 lines (71 loc) · 2.47 KB
/
checksum.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Package checksum provides functions for adding/removing checksums from supplied Trytes.
package checksum
import (
. "github.com/iotaledger/iota.go/consts"
"github.com/iotaledger/iota.go/guards"
"github.com/iotaledger/iota.go/kerl"
. "github.com/iotaledger/iota.go/trinary"
)
// AddChecksum computes the checksum and returns the given trytes with the appended checksum.
// If isAddress is true, then the input trytes must be of length HashTrytesSize.
// Specified checksum length must be at least MinChecksumTrytesSize long or it must be
// AddressChecksumTrytesSize if isAddress is true.
func AddChecksum(input Trytes, isAddress bool, checksumLength uint64) (Trytes, error) {
if isAddress && len(input) != HashTrytesSize {
if len(input) == AddressWithChecksumTrytesSize {
return input, nil
}
return "", ErrInvalidAddress
}
if checksumLength < MinChecksumTrytesSize ||
(isAddress && checksumLength != AddressChecksumTrytesSize) {
return "", ErrInvalidChecksum
}
inputCopy := input
for len(inputCopy)%HashTrytesSize != 0 {
inputCopy += "9"
}
k := kerl.NewKerl()
if err := k.AbsorbTrytes(inputCopy); err != nil {
return "", err
}
checksumTrytes, err := k.SqueezeTrytes(HashTrinarySize)
if err != nil {
return "", err
}
input += checksumTrytes[HashTrytesSize-checksumLength : HashTrytesSize]
return input, nil
}
// AddChecksums is a wrapper function around AddChecksum for multiple trytes strings.
func AddChecksums(inputs []Trytes, isAddress bool, checksumLength uint64) ([]Trytes, error) {
withChecksums := make([]Trytes, len(inputs))
for i, s := range inputs {
t, err := AddChecksum(s, isAddress, checksumLength)
if err != nil {
return nil, err
}
withChecksums[i] = t
}
return withChecksums, nil
}
// RemoveChecksum removes the checksum from the given trytes.
// The input trytes must be of length HashTrytesSize or AddressWithChecksumTrytesSize.
func RemoveChecksum(input Trytes) (Trytes, error) {
if !guards.IsTrytesOfExactLength(input, HashTrytesSize) &&
!guards.IsTrytesOfExactLength(input, AddressWithChecksumTrytesSize) {
return "", ErrInvalidAddress
}
return input[:HashTrytesSize], nil
}
// RemoveChecksums is a wrapper function around RemoveChecksum for multiple trytes strings.
func RemoveChecksums(inputs []Trytes) ([]Trytes, error) {
withoutChecksums := make([]Trytes, len(inputs))
for i, s := range inputs {
t, err := RemoveChecksum(s)
if err != nil {
return nil, err
}
withoutChecksums[i] = t
}
return withoutChecksums, nil
}