OSDN Git Service

new repo
[bytom/vapor.git] / blockchain / signers / signers.go
1 // Package signers associates signers and their corresponding keys.
2 package signers
3
4 import (
5         "bytes"
6         "encoding/binary"
7
8         "github.com/vapor/crypto/ed25519/chainkd"
9         "github.com/vapor/errors"
10 )
11
12 type keySpace byte
13
14 const (
15         AssetKeySpace   keySpace = 0
16         AccountKeySpace keySpace = 1
17 )
18
19 const (
20         //BIP0032 compatible previous derivation rule m/account/address_index
21         BIP0032 uint8 = iota
22         //BIP0032 path derivation rule m/purpose'/coin_type'/account'/change/address_index
23         BIP0044
24 )
25
26 var (
27         // ErrBadQuorum is returned by Create when the quorum
28         // provided is less than 1 or greater than the number
29         // of xpubs provided.
30         ErrBadQuorum = errors.New("quorum must be greater than or equal to 1, and must be less than or equal to the length of xpubs")
31
32         // ErrBadXPub is returned by Create when the xpub
33         // provided isn't valid.
34         ErrBadXPub = errors.New("invalid xpub format")
35
36         // ErrNoXPubs is returned by create when the xpubs
37         // slice provided is empty.
38         ErrNoXPubs = errors.New("at least one xpub is required")
39
40         // ErrDupeXPub is returned by create when the same xpub
41         // appears twice in a single call.
42         ErrDupeXPub   = errors.New("xpubs cannot contain the same key more than once")
43         ErrDeriveRule = errors.New("invalid key derive rule")
44 )
45
46 var (
47         // BIP44Purpose purpose field 0x0000002c little-endian mode.
48         BIP44Purpose = []byte{0x2C, 0x00, 0x00, 0x00}
49         // BTMCoinType coin type field 0x00000099 little-endian mode.
50         BTMCoinType = []byte{0x99, 0x00, 0x00, 0x00}
51 )
52
53 // Signer is the abstract concept of a signer,
54 // which is composed of a set of keys as well as
55 // the amount of signatures needed for quorum.
56 type Signer struct {
57         Type       string         `json:"type"`
58         XPubs      []chainkd.XPub `json:"xpubs"`
59         Quorum     int            `json:"quorum"`
60         KeyIndex   uint64         `json:"key_index"`
61         DeriveRule uint8          `json:"derive_rule"`
62 }
63
64 // GetBip0032Path returns the complete path for bip0032 derived keys
65 func GetBip0032Path(s *Signer, ks keySpace, itemIndexes ...uint64) [][]byte {
66         var path [][]byte
67         signerPath := [9]byte{byte(ks)}
68         binary.LittleEndian.PutUint64(signerPath[1:], s.KeyIndex)
69         path = append(path, signerPath[:])
70         for _, idx := range itemIndexes {
71                 var idxBytes [8]byte
72                 binary.LittleEndian.PutUint64(idxBytes[:], idx)
73                 path = append(path, idxBytes[:])
74         }
75         return path
76 }
77
78 // getBip0044Path returns the complete path for bip0044 derived keys
79 func getBip0044Path(accountIndex uint64, change bool, addrIndex uint64) [][]byte {
80         var path [][]byte
81         path = append(path, BIP44Purpose[:]) //purpose
82         path = append(path, BTMCoinType[:])  //coin type
83         accIdxBytes := make([]byte, 4)
84         binary.LittleEndian.PutUint32(accIdxBytes, uint32(accountIndex))
85         path = append(path, accIdxBytes) //account index
86         branchBytes := make([]byte, 4)
87         if change {
88                 binary.LittleEndian.PutUint32(branchBytes, uint32(1))
89         } else {
90                 binary.LittleEndian.PutUint32(branchBytes, uint32(0))
91         }
92         path = append(path, branchBytes) //change
93         addrIdxBytes := make([]byte, 4)
94         binary.LittleEndian.PutUint32(addrIdxBytes[:], uint32(addrIndex))
95         path = append(path, addrIdxBytes[:]) //address index
96         return path
97 }
98
99 // Path returns the complete path for derived keys
100 func Path(s *Signer, ks keySpace, change bool, addrIndex uint64) ([][]byte, error) {
101         switch s.DeriveRule {
102         case BIP0032:
103                 return GetBip0032Path(s, ks, addrIndex), nil
104         case BIP0044:
105                 return getBip0044Path(s.KeyIndex, change, addrIndex), nil
106         }
107         return nil, ErrDeriveRule
108 }
109
110 // Create creates and stores a Signer in the database
111 func Create(signerType string, xpubs []chainkd.XPub, quorum int, keyIndex uint64, deriveRule uint8) (*Signer, error) {
112         if len(xpubs) == 0 {
113                 return nil, errors.Wrap(ErrNoXPubs)
114         }
115
116         xpubsMap := map[chainkd.XPub]bool{}
117         for _, xpub := range xpubs {
118                 if _, ok := xpubsMap[xpub]; ok {
119                         return nil, errors.WithDetailf(ErrDupeXPub, "duplicated key=%x", xpub)
120                 }
121                 xpubsMap[xpub] = true
122         }
123
124         if quorum == 0 || quorum > len(xpubs) {
125                 return nil, errors.Wrap(ErrBadQuorum)
126         }
127
128         return &Signer{
129                 Type:       signerType,
130                 XPubs:      xpubs,
131                 Quorum:     quorum,
132                 KeyIndex:   keyIndex,
133                 DeriveRule: deriveRule,
134         }, nil
135 }
136
137 type SortKeys []chainkd.XPub
138
139 func (s SortKeys) Len() int           { return len(s) }
140 func (s SortKeys) Less(i, j int) bool { return bytes.Compare(s[i][:], s[j][:]) < 0 }
141 func (s SortKeys) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }