/
address.go
436 lines (363 loc) · 9.76 KB
/
address.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
package types
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"github.com/stratosnet/sds/framework/crypto/sha3"
"github.com/stratosnet/sds/framework/types/bech32"
)
// Bech32 conversion constants
const (
// MaxAddrLen is the maximum allowed length (in bytes) for an address.
MaxAddrLen = 255
StratosBech32Prefix = "st"
// PrefixPublic is the prefix for public keys
PrefixPublic = "pub"
// PrefixSds is the prefix for sds keys
PrefixSds = "sds"
// WalletAddressPrefix defines the Bech32 prefix of an account's address (st)
WalletAddressPrefix = StratosBech32Prefix
// WalletPubKeyPrefix defines the Bech32 prefix of an account's public key (stpub)
WalletPubKeyPrefix = StratosBech32Prefix + PrefixPublic
// P2PPubkeyPrefix defines the Bech32 prefix of an sds account's public key (stsdspub)
P2PPubkeyPrefix = StratosBech32Prefix + PrefixSds + PrefixPublic
// P2PAddressPrefix defines the Bech32 prefix of an sds account's address (stsds)
P2PAddressPrefix = StratosBech32Prefix + PrefixSds
)
var (
_ Address = P2PAddress{}
_ Address = WalletAddress{}
ErrEmptyAddress = errors.New("address is empty")
)
// Address is a common interface for different types of addresses used by the SDK
type Address interface {
Equals(Address) bool
Empty() bool
Marshal() ([]byte, error)
MarshalJSON() ([]byte, error)
Bytes() []byte
String() string
Format(s fmt.State, verb rune)
Hex() string
}
// ----------------------------------------------------------------------------
// account
// ----------------------------------------------------------------------------
// WalletAddress a wrapper around bytes meant to represent an account address.
// When marshaled to a string or JSON, it uses Bech32.
type WalletAddress []byte
func WalletAddressFromHex(s string) WalletAddress {
if len(s) > 1 {
if s[0:2] == "0x" || s[0:2] == "0X" {
s = s[2:]
}
}
if len(s)%2 == 1 {
s = "0" + s
}
bz, _ := hex.DecodeString(s)
return WalletAddress(bz)
}
func WalletAddressBytesToBech32(addr []byte) string {
return addrBytesToBech32(addr, WalletAddressPrefix)
}
// WalletAddressFromBech32 creates an WalletAddress from a Bech32 string.
func WalletAddressFromBech32(address string) (addr WalletAddress, err error) {
if len(strings.TrimSpace(address)) == 0 {
return WalletAddress{}, ErrEmptyAddress
}
bz, err := GetFromBech32(address, WalletAddressPrefix)
if err != nil {
return nil, err
}
err = VerifyAddressFormat(bz)
if err != nil {
return nil, err
}
return WalletAddress(bz), nil
}
// Returns boolean for whether two AccAddresses are Equal
func (aa WalletAddress) Equals(aa2 Address) bool {
if aa.Empty() && aa2.Empty() {
return true
}
return bytes.Equal(aa.Bytes(), aa2.Bytes())
}
// Returns boolean for whether an WalletAddress is empty
func (aa WalletAddress) Empty() bool {
return len(aa) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (aa WalletAddress) Marshal() ([]byte, error) {
return aa, nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (aa *WalletAddress) Unmarshal(data []byte) error {
*aa = data
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (aa WalletAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(aa.String())
}
// MarshalYAML marshals to YAML using Bech32.
func (aa WalletAddress) MarshalYAML() (interface{}, error) {
return aa.String(), nil
}
// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding.
func (aa *WalletAddress) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*aa = WalletAddress{}
return nil
}
aa2, err := WalletAddressFromBech32(s)
if err != nil {
return err
}
*aa = aa2
return nil
}
// UnmarshalYAML unmarshals from JSON assuming Bech32 encoding.
func (aa *WalletAddress) UnmarshalYAML(data []byte) error {
var s string
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*aa = WalletAddress{}
return nil
}
aa2, err := WalletAddressFromBech32(s)
if err != nil {
return err
}
*aa = aa2
return nil
}
// Bytes returns the raw address bytes.
func (aa WalletAddress) Bytes() []byte {
return aa
}
// String implements the Stringer interface.
func (aa WalletAddress) String() string {
if aa.Empty() {
return ""
}
bech32Addr, err := bech32.ConvertAndEncode(WalletAddressPrefix, aa.Bytes())
if err != nil {
return ""
}
return bech32Addr
}
// Format implements the fmt.Formatter interface.
func (aa WalletAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
s.Write([]byte(aa.String()))
case 'p':
s.Write([]byte(fmt.Sprintf("%p", aa)))
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(aa))))
}
}
func (aa WalletAddress) Hex() string {
unchecksummed := hex.EncodeToString(aa[:])
sha := sha3.NewKeccak256()
sha.Write([]byte(unchecksummed))
hash := sha.Sum(nil)
result := []byte(unchecksummed)
for i := 0; i < len(result); i++ {
hashByte := hash[i/2]
if i%2 == 0 {
hashByte = hashByte >> 4
} else {
hashByte &= 0xf
}
if result[i] > '9' && hashByte > 7 {
result[i] -= 32
}
}
return "0x" + string(result)
}
// ----------------------------------------------------------------------------
// P2PAddress
// ----------------------------------------------------------------------------
type P2PAddress []byte
func P2PAddressFromHex(s string) P2PAddress {
if len(s) > 1 {
if s[0:2] == "0x" || s[0:2] == "0X" {
s = s[2:]
}
}
if len(s)%2 == 1 {
s = "0" + s
}
bz, _ := hex.DecodeString(s)
return P2PAddress(bz)
}
func P2PAddressBytesToBech32(addr []byte) string {
return addrBytesToBech32(addr, P2PAddressPrefix)
}
// P2PAddressFromBech32 creates an P2PAddress from a Bech32 string.
func P2PAddressFromBech32(address string) (addr P2PAddress, err error) {
if len(strings.TrimSpace(address)) == 0 {
return P2PAddress{}, ErrEmptyAddress
}
bz, err := GetFromBech32(address, P2PAddressPrefix)
if err != nil {
return nil, err
}
err = VerifyAddressFormat(bz)
if err != nil {
return nil, err
}
return P2PAddress(bz), nil
}
// Equals Returns boolean for whether two P2PAddress are Equal
func (aa P2PAddress) Equals(aa2 Address) bool {
if aa.Empty() && aa2.Empty() {
return true
}
return bytes.Equal(aa.Bytes(), aa2.Bytes())
}
// Empty Returns boolean for whether a P2PAddress is empty
func (aa P2PAddress) Empty() bool {
return aa == nil || len(aa) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (aa P2PAddress) Marshal() ([]byte, error) {
return aa, nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (aa *P2PAddress) Unmarshal(data []byte) error {
*aa = data
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (aa P2PAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(aa.String())
}
// MarshalYAML marshals to YAML using Bech32.
func (aa P2PAddress) MarshalYAML() (interface{}, error) {
return aa.String(), nil
}
// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding.
func (aa *P2PAddress) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*aa = P2PAddress{}
return nil
}
aa2, err := P2PAddressFromBech32(s)
if err != nil {
return err
}
*aa = aa2
return nil
}
// Bytes returns the raw address bytes.
func (aa P2PAddress) Bytes() []byte {
return aa
}
// String implements the Stringer interface.
func (aa P2PAddress) String() string {
if aa.Empty() {
return ""
}
bech32Addr, err := bech32.ConvertAndEncode(P2PAddressPrefix, aa.Bytes())
if err != nil {
return ""
}
return bech32Addr
}
// Format implements the fmt.Formatter interface.
func (aa P2PAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
s.Write([]byte(aa.String()))
case 'p':
s.Write([]byte(fmt.Sprintf("%p", aa)))
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(aa))))
}
}
func (aa P2PAddress) Hex() string {
unchecksummed := hex.EncodeToString(aa[:])
sha := sha3.NewKeccak256()
sha.Write([]byte(unchecksummed))
hash := sha.Sum(nil)
result := []byte(unchecksummed)
for i := 0; i < len(result); i++ {
hashByte := hash[i/2]
if i%2 == 0 {
hashByte = hashByte >> 4
} else {
hashByte &= 0xf
}
if result[i] > '9' && hashByte > 7 {
result[i] -= 32
}
}
return "0x" + string(result)
}
//--------------------------------------------------------------------
func addrBytesToBech32(addr []byte, addrPrefix string) string {
if addr == nil || len(addr) == 0 {
return ""
}
bech32Addr, err := bech32.ConvertAndEncode(addrPrefix, addr)
if err != nil {
return ""
}
return bech32Addr
}
// GetFromBech32 decodes a bytestring from a Bech32 encoded string.
func GetFromBech32(bech32str, prefix string) ([]byte, error) {
if len(bech32str) == 0 {
return nil, fmt.Errorf("decoding Bech32 address failed: must provide a non empty address")
}
hrp, bz, err := bech32.DecodeAndConvert(bech32str)
if err != nil {
return nil, err
}
if hrp != prefix {
return nil, fmt.Errorf("invalid Bech32 prefix; expected %s, got %s", prefix, hrp)
}
return bz, nil
}
// VerifyAddressFormat verifies that the provided bytes form a valid address
// according to the default address rules or a custom address verifier set by
// GetConfig().SetAddressVerifier().
// TODO make an issue to get rid of global Config
// ref: https://github.com/cosmos/cosmos-sdk/issues/9690
func VerifyAddressFormat(bz []byte) error {
//verifier := GetConfig().GetAddressVerifier()
//if verifier != nil {
// return verifier(bz)
//}
if len(bz) == 0 {
return fmt.Errorf("addresses cannot be empty")
}
if len(bz) > MaxAddrLen {
return fmt.Errorf("address max length is %d, got %d", MaxAddrLen, len(bz))
}
return nil
}