/
address.go
51 lines (43 loc) · 1.42 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
// Copyright 2017 The nem-toolchain project authors. All rights reserved.
// Use of this source code is governed by a MIT license that can be found in the LICENSE file.
package keypair
import (
"encoding/base32"
"errors"
"regexp"
"strings"
"github.com/nem-toolchain/nem-toolchain/pkg/core"
)
const (
// AddressBytes stores the address length in bytes
AddressBytes = 25
// AddressLength stores the address length as string representation
AddressLength = 40
// PrettyAddressLength stores the address length as pretty string representation
PrettyAddressLength = 46
)
// Address is a readable string representation for a public key.
type Address [AddressBytes]byte
// ParseAddress constructs an instance of `Address` from given base32 string representation
func ParseAddress(str string) (Address, error) {
var addr Address
str = strings.Replace(str, "-", "", -1)
if !core.IsChainPrefix(str) {
return addr, errors.New("unknown chain")
}
b, err := base32.StdEncoding.DecodeString(str)
if err != nil {
return addr, errors.New("can't decode address string")
}
copy(addr[:], b)
return addr, nil
}
// PrettyString returns pretty formatted address with separators ('-').
func (addr Address) PrettyString() string {
str := addr.String()
els := regexp.MustCompile(`.{6}`).FindAllString(str, -1)
return strings.Join(append(els, str[36:]), "-")
}
func (addr Address) String() string {
return base32.StdEncoding.EncodeToString(addr[:])
}