-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddress.go
332 lines (297 loc) · 8.19 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
package gobbc
import (
"bytes"
"crypto/ed25519"
"encoding/base32"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"strconv"
"golang.org/x/crypto/blake2b"
)
//some len const
const (
PubkeyHexLen = 32*2 + 1
PrivkeyHexLen = 32*2 + 1
PubkeyAddressLen = 57 + 1
Uint256HexLen = 65
templateDexorder = 9
AddressPrefixPubk = '1'
AddressPrefixTpl = '2'
PrefixPubk = 1
PrefixTemplate = 2
)
// AddrKeyPair 地址、私钥、公钥
type AddrKeyPair struct {
Addr string
Privk string
Pubk string
}
// MakeKeyPair .
func MakeKeyPair() (AddrKeyPair, error) {
var pair AddrKeyPair
pubk, privk, err := ed25519.GenerateKey(nil)
if err != nil {
return pair, err
}
pair.Pubk = CopyReverseThenEncodeHex(pubk)
pair.Privk = CopyReverseThenEncodeHex(privk.Seed())
addr, err := GetPubKeyAddress(pair.Pubk)
if err != nil {
return pair, err
}
pair.Addr = addr
return pair, nil
}
// Seed2string 私钥字符串
func Seed2string(seed []byte) string {
return CopyReverseThenEncodeHex(seed)
}
// Seed2pubk .
func Seed2pubk(seed []byte) ([]byte, error) {
if l := len(seed); l != ed25519.SeedSize {
return nil, fmt.Errorf("invalid seed len, %v", l)
}
privateKey := ed25519.NewKeyFromSeed(seed)
return privateKey.Public().(ed25519.PublicKey), nil
}
// Seed2pubkString .
func Seed2pubkString(seed []byte) (string, error) {
pubk, err := Seed2pubk(seed)
if err != nil {
return "", err
}
return hex.EncodeToString(reverseBytes(pubk)), nil
}
// PrivateKeyHex2Seed 解析私钥为实际使用的seed
func PrivateKeyHex2Seed(hexedPrivk string) ([]byte, error) {
b, err := hex.DecodeString(hexedPrivk)
if err != nil {
return nil, fmt.Errorf("failed to hex decode private key, %v", err)
}
return reverseBytes(b), nil
}
// ParsePublicKeyHex 解析私钥为实际使用的seed
func ParsePublicKeyHex(hexedPubK string) ([]byte, error) {
b, err := hex.DecodeString(hexedPubK)
if err != nil {
return nil, fmt.Errorf("failed to hex decode private key, %v", err)
}
if l := len(b); l != 32 {
return nil, fmt.Errorf("invalid public key, invalid len: %d", l)
}
return reverseBytes(b), nil
}
// MultisigInfo 多签信息
type MultisigInfo struct {
Hex string
M, N uint8 //m-n签名,N名成员需要至少M个签名
Members []MultisigMember
}
// MultisigMember .
type MultisigMember struct {
Pub []byte
Weight uint8
}
// SignTemplatePart 签名时签名的前半部分
func (mi MultisigInfo) SignTemplatePart() []byte {
b, _ := hex.DecodeString(mi.Hex[4:])
return b
}
// Pubks 参与签名的公钥列表
func (mi MultisigInfo) Pubks() [][]byte {
var pubks [][]byte
for _, m := range mi.Members {
pubks = append(pubks, m.Pub)
}
return pubks
}
// ParsePrivkHex BBC 私钥解析为ed25519.PrivateKey
func ParsePrivkHex(privkHex string) (ed25519.PrivateKey, error) {
b, err := hex.DecodeString(privkHex)
if err != nil {
return nil, err
}
seed := CopyReverse(b)
if l := len(seed); l != ed25519.SeedSize {
return nil, fmt.Errorf("ed25519: bad seed length: %d", l)
}
return ed25519.NewKeyFromSeed(seed), nil
}
// GetPubKeyAddress Get Address hex string from public key hex string
func GetPubKeyAddress(pubk string) (string, error) {
return EncodeAddress(PrefixPubk, pubk)
}
// EncodeAddress Get Address hex string from public key hex string
func EncodeAddress(prefix uint8, hexed string) (string, error) {
if len(hexed) != 64 {
return "", errors.New("invalid address len, should be 64")
}
ui := uint256SetHex(hexed)
return strconv.Itoa(int(prefix)) + Base32Encode(ui[:]), nil
}
// ConvertAddress2pubk .
func ConvertAddress2pubk(address string) (string, error) {
if len(address) != 57 {
return "", errors.New("invalid address (len err)")
}
if address[0] != AddressPrefixPubk {
return "", errors.New("pubk address should start with 1")
}
enc := base32.NewEncoding(base32Alphabet)
b, err := enc.DecodeString(address[1:])
if err != nil {
return "", fmt.Errorf("base32 decode address err, %v", err)
}
pubk := hex.EncodeToString(reverseBytes(b))
validateAddr, err := GetPubKeyAddress(pubk[6:])
if err != nil {
return "", fmt.Errorf("校验不通过, %v", err)
}
if validateAddr != address {
return "", fmt.Errorf("校验不通过")
}
return pubk[6:], nil //前 3 byte是校验位
}
type Address string
// NewCDestinationFromAddress 可以用来校验地址,或者获取原始地址字节
func NewCDestinationFromAddress(address string) (cd CDestination, err error) {
if len(address) != 57 {
return CDestination{}, errors.New("invalid address len")
}
if address[0] != AddressPrefixPubk && address[0] != AddressPrefixTpl {
return CDestination{}, errors.New("pubk address should start with 1")
}
enc := base32.NewEncoding(base32Alphabet)
b, err := enc.DecodeString(address[1:])
if err != nil {
return CDestination{}, fmt.Errorf("base32 decode address err, %v", err)
}
prefix, _ := strconv.Atoi(string(address[0]))
dest := CDestination{
Prefix: uint8(prefix),
}
if len(b) != 3+32 {
return dest, fmt.Errorf("invalid len: %d", len(b))
}
copy(dest.Data[:], b[:32]) //3个字节的校验位
if dest.String() != address {
return dest, errors.New("validate err: got " + dest.String())
}
return dest, nil
}
func NewCDestinationFromHexString(s string) (cd CDestination, err error) {
if len(s) != 66 { //2*(32+1)
return cd, errors.New("invalid len, should be 66")
}
i, e := strconv.Atoi(s[:2])
if e != nil {
return cd, e
}
cd.Prefix = uint8(i)
b, e := hex.DecodeString(s[2:])
if e != nil {
return cd, e
}
copy(cd.Data[:], b)
return
}
type CDestination struct {
Prefix uint8
Data [32]byte
}
func (a CDestination) String() string {
add, _ := EncodeAddress(a.Prefix, hex.EncodeToString(CopyReverse(a.Data[:])))
return add
}
type VoteTpl struct {
Delegate CDestination
Voter CDestination
}
// DexOrderParam .
type DexOrderParam struct {
SellerAddress Address `json:"seller_address"`
Coinpair string `json:"coinpair"`
Price int64 `json:"price"`
Fee int32 `json:"fee"`
RecvAddress string `json:"recv_address"`
ValidHeight int32 `json:"valid_height"`
MatchAddress Address `json:"match_address"`
DealAddress string `json:"deal_address"`
Timestamp uint32 `json:"timestamp"`
}
// CreateTemplateDataDexOrder return tplID, tplData, error
func CreateTemplateDataDexOrder(p DexOrderParam) (string, string, error) {
buf := bytes.NewBuffer(nil)
var errs []error
write := func(v interface{}) {
if e := binary.Write(buf, binary.LittleEndian, v); e != nil {
errs = append(errs, e)
}
}
writeAddress := func(add Address) {
prefix, b, e := GetAddressBytes(string(add))
if e != nil {
errs = append(errs, e)
return
}
b = append([]byte{prefix}, b...)
if _, e = buf.Write(b); e != nil {
errs = append(errs, e)
}
}
writeString := func(s string) {
b := []byte(s)
write(int64(len(b)))
if _, e := buf.Write(b); e != nil {
errs = append(errs, e)
}
}
// os << destSeller << vCoinPair << nPrice << nFee << vRecvDest << nValidHeight << destMatch << destDeal;
write(int16(templateDexorder))
writeAddress(p.SellerAddress)
writeString(p.Coinpair)
write(p.Price)
write(p.Fee)
writeString(p.RecvAddress)
write(p.ValidHeight)
writeAddress(p.MatchAddress)
writeString(p.DealAddress)
write(p.Timestamp)
if len(errs) != 0 {
return "", "", fmt.Errorf("some errors when write binary: %v", errs)
}
hash := blake2b.Sum256(buf.Bytes()[2:]) //remove type
x := make([]byte, 2)
binary.LittleEndian.PutUint16(x, templateDexorder)
x = append(x, hash[:len(hash)-2]...)
return string(AddressPrefixTpl) + Base32Encode(x[:]), hex.EncodeToString(buf.Bytes()), nil
}
// GetAddressBytes prefix, pubkOrHash, error
func GetAddressBytes(add string) (byte, []byte, error) {
if len(add) != 57 {
return 0, nil, errors.New("invalid address len")
}
switch add[0] {
case AddressPrefixPubk: //1: pubk address
pubk, err := ConvertAddress2pubk(add)
if err != nil {
return 0, nil, err
}
bytes, err := hex.DecodeString(pubk)
if err != nil {
return 0, nil, err
}
return 1, reverseBytes(bytes), nil
case AddressPrefixTpl: //模版地址
enc := base32.NewEncoding(base32Alphabet)
db, err := enc.DecodeString(add[1:])
if err != nil {
return 0, nil, err
}
return 2, db[:], nil
default:
return 0, nil, errors.New("unknown address type")
}
}