Debian Codegraph @

internal/bech32/bech32.go

raw symbols SCIP
1 // Copyright (c) 2017 Takatoshi Nakagawa
2 // Copyright (c) 2019 The age Authors
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 // Package bech32 is a modified version of the reference implementation of BIP173.
23 package bech32
24
25 import (
26 "fmt"
27 "strings"
28 )
29
30 var charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
31
32 var generator = []uint32{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3}
33
34 func polymod(values []byte) uint32 {
35 chk := uint32(1)
36 for _, v := range values {
37 top := chk >> 25
38 chk = (chk & 0x1ffffff) << 5
39 chk = chk ^ uint32(v)
40 for i := range 5 {
41 bit := top >> i & 1
42 if bit == 1 {
43 chk ^= generator[i]
44 }
45 }
46 }
47 return chk
48 }
49
50 func hrpExpand(hrp string) []byte {
51 h := []byte(strings.ToLower(hrp))
52 var ret []byte
53 for _, c := range h {
54 ret = append(ret, c>>5)
55 }
56 ret = append(ret, 0)
57 for _, c := range h {
58 ret = append(ret, c&31)
59 }
60 return ret
61 }
62
63 func verifyChecksum(hrp string, data []byte) bool {
64 return polymod(append(hrpExpand(hrp), data...)) == 1
65 }
66
67 func createChecksum(hrp string, data []byte) []byte {
68 values := append(hrpExpand(hrp), data...)
69 values = append(values, []byte{0, 0, 0, 0, 0, 0}...)
70 mod := polymod(values) ^ 1
71 ret := make([]byte, 6)
72 for p := range ret {
73 shift := 5 * (5 - p)
74 ret[p] = byte(mod>>shift) & 31
75 }
76 return ret
77 }
78
79 func convertBits(data []byte, frombits, tobits byte, pad bool) ([]byte, error) {
80 var ret []byte
81 acc := uint32(0)
82 bits := byte(0)
83 maxv := byte(1<<tobits - 1)
84 for idx, value := range data {
85 if value>>frombits != 0 {
86 return nil, fmt.Errorf("invalid data range: data[%d]=%d (frombits=%d)", idx, value, frombits)
87 }
88 acc = acc<<frombits | uint32(value)
89 bits += frombits
90 for bits >= tobits {
91 bits -= tobits
92 ret = append(ret, byte(acc>>bits)&maxv)
93 }
94 }
95 if pad {
96 if bits > 0 {
97 ret = append(ret, byte(acc<<(tobits-bits))&maxv)
98 }
99 } else if bits >= frombits {
100 return nil, fmt.Errorf("illegal zero padding")
101 } else if byte(acc<<(tobits-bits))&maxv != 0 {
102 return nil, fmt.Errorf("non-zero padding")
103 }
104 return ret, nil
105 }
106
107 // Encode encodes the HRP and a bytes slice to Bech32. If the HRP is uppercase,
108 // the output will be uppercase.
109 func Encode(hrp string, data []byte) (string, error) {
110 values, err := convertBits(data, 8, 5, true)
111 if err != nil {
112 return "", err
113 }
114 if len(hrp) < 1 {
115 return "", fmt.Errorf("invalid HRP: %q", hrp)
116 }
117 for p, c := range hrp {
118 if c < 33 || c > 126 {
119 return "", fmt.Errorf("invalid HRP character: hrp[%d]=%d", p, c)
120 }
121 }
122 if strings.ToUpper(hrp) != hrp && strings.ToLower(hrp) != hrp {
123 return "", fmt.Errorf("mixed case HRP: %q", hrp)
124 }
125 lower := strings.ToLower(hrp) == hrp
126 hrp = strings.ToLower(hrp)
127 var ret strings.Builder
128 ret.WriteString(hrp)
129 ret.WriteString("1")
130 for _, p := range values {
131 ret.WriteByte(charset[p])
132 }
133 for _, p := range createChecksum(hrp, values) {
134 ret.WriteByte(charset[p])
135 }
136 if lower {
137 return ret.String(), nil
138 }
139 return strings.ToUpper(ret.String()), nil
140 }
141
142 // Decode decodes a Bech32 string. If the string is uppercase, the HRP will be uppercase.
143 func Decode(s string) (hrp string, data []byte, err error) {
144 if strings.ToLower(s) != s && strings.ToUpper(s) != s {
145 return "", nil, fmt.Errorf("mixed case")
146 }
147 pos := strings.LastIndex(s, "1")
148 if pos < 1 || pos+7 > len(s) {
149 return "", nil, fmt.Errorf("separator '1' at invalid position: pos=%d, len=%d", pos, len(s))
150 }
151 hrp = s[:pos]
152 for p, c := range hrp {
153 if c < 33 || c > 126 {
154 return "", nil, fmt.Errorf("invalid character human-readable part: s[%d]=%d", p, c)
155 }
156 }
157 for p, c := range s[pos+1:] {
158 // Fold ASCII explicitly. Unicode case folding can turn a non-ASCII
159 // rune into a shorter valid charset member.
160 if c >= 'A' && c <= 'Z' {
161 c += 'a' - 'A'
162 }
163 d := strings.IndexRune(charset, c)
164 if d == -1 {
165 return "", nil, fmt.Errorf("invalid character data part: s[%d]=%v", p, c)
166 }
167 data = append(data, byte(d))
168 }
169 if len(data) < 6 {
170 return "", nil, fmt.Errorf("data part too short")
171 }
172 if !verifyChecksum(hrp, data) {
173 return "", nil, fmt.Errorf("invalid checksum")
174 }
175 data, err = convertBits(data[:len(data)-6], 5, 8, false)
176 if err != nil {
177 return "", nil, err
178 }
179 return hrp, data, nil
180 }