-
Notifications
You must be signed in to change notification settings - Fork 137
/
path.go
76 lines (60 loc) · 1.35 KB
/
path.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
package addresspath
import (
"fmt"
"strconv"
"strings"
)
const HardenedKeyStart = uint32(0x80000000) // 2^31
type Path []uint32
func NewPath(indexes ...uint32) Path {
p := make([]uint32, 0, len(indexes))
p = append(p, indexes...)
return p
}
func FromString(str string) (Path, error) {
sub := strings.Split(str, "/")
if sub[0] != "m" {
return nil, ErrInvalidPath
}
// TODO: check the path should exactly 4 levels.
var path []uint32
for i := 1; i < len(sub); i++ {
indexStr := sub[i]
added := uint32(0)
if indexStr[len(indexStr)-1] == '\'' {
added = HardenedKeyStart
indexStr = indexStr[:len(indexStr)-1]
}
val, err := strconv.ParseInt(indexStr, 10, 32)
if err != nil {
return nil, err
}
path = append(path, uint32(val)+added)
}
return path, nil
}
func (p Path) String() string {
var builder strings.Builder
builder.WriteString("m")
for _, i := range p {
if i >= HardenedKeyStart {
builder.WriteString(fmt.Sprintf("/%d'", i-HardenedKeyStart))
} else {
builder.WriteString(fmt.Sprintf("/%d", i))
}
}
return builder.String()
}
// TODO: we can add IsBLSPurpose or IsImportedPurpose functions
func (p Path) Purpose() uint32 {
return p[0]
}
func (p Path) CoinType() uint32 {
return p[len(p)-3]
}
func (p Path) AddressType() uint32 {
return p[len(p)-2]
}
func (p Path) AddressIndex() uint32 {
return p[len(p)-1]
}