/
bip32path.go
77 lines (72 loc) · 1.79 KB
/
bip32path.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
// Package bip32 provides ...
package commons
import (
"errors"
"strconv"
"strings"
)
var ErrKeyPathFormat = errors.New("Wallet Path Error")
var ErrParentKey = errors.New("Key must master")
var mapKey = make(map[string]*ExtendedKey)
// DerivePath return key by path : m/0'/1/2' etc...
func (key *ExtendedKey) DerivePath(pathStr string) (*ExtendedKey, error) {
//fmt.Println("###########", len(mapKey))
if key.childNum > 0 {
return nil, ErrParentKey
}
keyTmp := mapKey[pathStr]
path := strings.Split(pathStr, "/")
err := vaildPath(path)
if err != nil {
return nil, err
}
tmpPath := []string{}
var tmpPathStr string
var tmpParentKey *ExtendedKey
for _, childNumStr := range path {
tmpPath = append(tmpPath, childNumStr)
tmpPathStr = strings.Join(tmpPath, "/")
keyTmp = mapKey[tmpPathStr]
if tmpPathStr == "m" {
keyTmp = key
} else {
isHardenedChild := false
if strings.HasSuffix(childNumStr, "'") {
childNumStr = strings.Replace(childNumStr, "'", "", -1)
isHardenedChild = true
}
childNum, _ := strconv.Atoi(childNumStr)
var err error
if isHardenedChild {
keyTmp, err = tmpParentKey.HardenedChild(uint32(childNum))
} else {
keyTmp, err = tmpParentKey.Child(uint32(childNum))
}
if err != nil {
return nil, err
}
}
mapKey[tmpPathStr] = keyTmp
tmpParentKey = keyTmp
}
return keyTmp, nil
}
func vaildPath(path []string) error {
if path[0] != "m" {
return ErrKeyPathFormat
}
for i := 1; i < len(path); i++ {
childNumStr := path[i]
if strings.HasSuffix(childNumStr, "'") {
childNumStr = strings.Replace(childNumStr, "'", "", -1)
}
childNum, err := strconv.Atoi(childNumStr)
if err != nil {
return ErrKeyPathFormat
}
if uint32(childNum) >= HardenedKeyStart || childNum < 0 {
return ErrKeyPathFormat
}
}
return nil
}