-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathutil.go
419 lines (362 loc) · 9.85 KB
/
util.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package nkn
import (
"context"
"crypto/rand"
"crypto/sha256"
"log"
"math/big"
"net"
"sync"
"time"
"github.com/nknorg/nkn/v2/common"
"github.com/nknorg/nkn/v2/crypto"
"github.com/nknorg/nkn/v2/pb"
"github.com/nknorg/nkn/v2/program"
"github.com/nknorg/nkn/v2/util/address"
"github.com/nknorg/nkn/v2/vault"
"github.com/nknorg/nkngomobile"
)
const (
// AmountUnit is the inverse of the NKN precision
AmountUnit = common.StorageFactor
)
var (
zeroTime time.Time
)
// Account is a wrapper type for gomobile compatibility.
type Account struct{ *vault.Account }
// NewAccount creates an account from secret seed. Seed length should be 32 or
// 0. If seed has zero length (including nil), a random seed will be generated.
func NewAccount(seed []byte) (*Account, error) {
var account *vault.Account
var err error
if len(seed) > 0 {
account, err = vault.NewAccountWithSeed(seed)
} else {
account, err = vault.NewAccount()
}
if err != nil {
return nil, err
}
_, err = account.ProgramHash.ToAddress()
if err != nil {
return nil, err
}
return &Account{account}, err
}
// Seed returns the secret seed of the account. Secret seed can be used to
// create client/wallet with the same key pair and should be kept secret and
// safe.
func (account *Account) Seed() []byte {
return crypto.GetSeedFromPrivateKey(account.PrivKey())
}
// PubKey returns the public key of the account.
func (account *Account) PubKey() []byte {
return account.Account.PublicKey
}
// WalletAddress returns the wallet address of the account.
func (account *Account) WalletAddress() string {
// no need to handle error here as it's already checked in NewAccount()
addr, _ := account.ProgramHash.ToAddress()
return addr
}
// Amount is a wrapper type for gomobile compatibility.
type Amount struct{ common.Fixed64 }
// NewAmount creates an amount from string in unit of NKN. For example, "0.1"
// will be parsed as 0.1 NKN.
func NewAmount(s string) (*Amount, error) {
fixed64, err := common.StringToFixed64(s)
if err != nil {
return nil, err
}
return &Amount{fixed64}, err
}
// ToFixed64 returns amount as Fixed64 type.
func (amount *Amount) ToFixed64() common.Fixed64 {
if amount == nil {
return 0
}
return amount.Fixed64
}
// Subscribers is a wrapper type for gomobile compatibility.
type Subscribers struct{ Subscribers, SubscribersInTxPool *nkngomobile.StringMap }
// OnConnectFunc is a wrapper type for gomobile compatibility.
type OnConnectFunc interface{ OnConnect(*Node) }
// OnConnect is a wrapper type for gomobile compatibility.
type OnConnect struct {
C chan *Node
Callback OnConnectFunc
}
// NewOnConnect creates an OnConnect channel with a channel size and callback
// function.
func NewOnConnect(size int, cb OnConnectFunc) *OnConnect {
return &OnConnect{
C: make(chan *Node, size),
Callback: cb,
}
}
// Next waits and returns the next element from the channel.
func (c *OnConnect) Next() *Node {
return <-c.C
}
// MaybeNext returns the next element in the channel, or nil if channel is
// empty.
func (c *OnConnect) MaybeNext() *Node {
select {
case v := <-c.C:
return v
default:
return nil
}
}
func (c *OnConnect) receive(node *Node) {
if c.Callback != nil {
c.Callback.OnConnect(node)
} else {
select {
case c.C <- node:
default:
}
}
}
func (c *OnConnect) close() {
close(c.C)
}
// OnMessageFunc is a wrapper type for gomobile compatibility.
type OnMessageFunc interface{ OnMessage(*Message) }
// OnMessage is a wrapper type for gomobile compatibility.
type OnMessage struct {
C chan *Message
Callback OnMessageFunc
}
// NewOnMessage creates an OnMessage channel with a channel size and callback
// function.
func NewOnMessage(size int, cb OnMessageFunc) *OnMessage {
return &OnMessage{
C: make(chan *Message, size),
Callback: cb,
}
}
// Next waits and returns the next element from the channel.
func (c *OnMessage) Next() *Message {
return <-c.C
}
// MaybeNext returns the next element in the channel, or nil if channel is
// empty.
func (c *OnMessage) MaybeNext() *Message {
select {
case v := <-c.C:
return v
default:
return nil
}
}
// NextWithTimeout waits and returns the next element from the channel, timeout in millisecond.
func (c *OnMessage) NextWithTimeout(timeout int32) *Message {
if timeout == 0 {
return <-c.C
}
select {
case msg := <-c.C:
return msg
case <-time.After(time.Duration(timeout) * time.Millisecond):
return nil
}
}
func (c *OnMessage) receive(msg *Message, verbose bool) {
if c.Callback != nil {
c.Callback.OnMessage(msg)
} else {
select {
case c.C <- msg:
default:
if verbose {
log.Println("Message channel full, discarding msg...")
}
}
}
}
func (c *OnMessage) close() {
close(c.C)
}
// OnErrorFunc is a wrapper type for gomobile compatibility.
type OnErrorFunc interface{ OnError(error) }
// OnError is a wrapper type for gomobile compatibility.
type OnError struct {
C chan error
Callback OnErrorFunc
}
// NewOnError creates an OnError channel with a channel size and callback
// function.
func NewOnError(size int, cb OnErrorFunc) *OnError {
return &OnError{
C: make(chan error, size),
Callback: cb,
}
}
// Next waits and returns the next element from the channel.
func (c *OnError) Next() error {
return <-c.C
}
// MaybeNext returns the next element in the channel, or nil if channel is
// empty.
func (c *OnError) MaybeNext() error {
select {
case v := <-c.C:
return v
default:
return nil
}
}
func (c *OnError) receive(err error) {
if c.Callback != nil {
c.Callback.OnError(err)
} else {
select {
case c.C <- err:
default:
log.Printf("OnError channel full, print error instead: %v", err)
}
}
}
func (c *OnError) close() {
close(c.C)
}
// ClientAddr represents NKN client address. It implements net.Addr interface.
type ClientAddr struct {
addr string
}
// NewClientAddr creates a ClientAddr from a client address string.
func NewClientAddr(addr string) *ClientAddr {
return &ClientAddr{addr: addr}
}
// Network returns "nkn"
func (addr ClientAddr) Network() string { return "nkn" }
// String returns the NKN client address string.
func (addr ClientAddr) String() string { return addr.addr }
func addIdentifierPrefix(base, prefix string) string {
if len(base) == 0 {
return prefix
}
if len(prefix) == 0 {
return base
}
return prefix + "." + base
}
// RandomBytes return cryptographically secure random bytes with given size.
func RandomBytes(numBytes int) ([]byte, error) {
b := make([]byte, numBytes)
if _, err := rand.Read(b); err != nil {
return nil, err
}
return b, nil
}
func sessionKey(remoteAddr string, sessionID []byte) string {
return remoteAddr + string(sessionID)
}
func randUint32() uint32 {
m := big.NewInt(4294967296)
for {
result, err := rand.Int(rand.Reader, m)
if err != nil {
continue
}
return uint32(result.Uint64())
}
}
func randUint64() uint64 {
m := new(big.Int).SetUint64(18446744073709551615)
m.Add(m, big.NewInt(1))
for {
result, err := rand.Int(rand.Reader, m)
if err != nil {
continue
}
return result.Uint64()
}
}
func addressToID(addr string) []byte {
id := sha256.Sum256([]byte(addr))
return id[:]
}
// ClientAddrToPubKey converts a NKN client address to its public key.
func ClientAddrToPubKey(clientAddr string) ([]byte, error) {
_, pk, _, err := address.ParseClientAddress(clientAddr)
if err != nil {
return nil, err
}
err = crypto.CheckPublicKey(pk)
if err != nil {
return nil, err
}
return pk, nil
}
// PubKeyToWalletAddr converts a public key to its NKN wallet address.
func PubKeyToWalletAddr(pubKey []byte) (string, error) {
programHash, err := program.CreateProgramHash(pubKey)
if err != nil {
return "", err
}
return programHash.ToAddress()
}
// ClientAddrToWalletAddr converts a NKN client address to its NKN wallet
// address. It's a shortcut for calling ClientAddrToPubKey followed by
// PubKeyToWalletAddr.
func ClientAddrToWalletAddr(clientAddr string) (string, error) {
pk, err := ClientAddrToPubKey(clientAddr)
if err != nil {
return "", err
}
return PubKeyToWalletAddr(pk)
}
// VerifyWalletAddress returns error if the given wallet address is invalid.
func VerifyWalletAddress(address string) error {
_, err := common.ToScriptHash(address)
return err
}
// MeasureSeedRPCServer wraps MeasureSeedRPCServerContext with background
// context.
func MeasureSeedRPCServer(seedRPCList *nkngomobile.StringArray, timeout int32, dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) (*nkngomobile.StringArray, error) {
return MeasureSeedRPCServerContext(context.Background(), seedRPCList, timeout, dialContext)
}
// MeasureSeedRPCServerContext measures the latency to seed rpc node list, only
// select the ones in persist finished state, and sort them by latency (from low
// to high). If none of the given seed rpc node is accessible or in persist
// finished state, returned string array will contain zero elements. Timeout is
// in millisecond.
func MeasureSeedRPCServerContext(ctx context.Context, seedRPCList *nkngomobile.StringArray, timeout int32, dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) (*nkngomobile.StringArray, error) {
var wg sync.WaitGroup
var lock sync.Mutex
rpcAddrs := make([]string, 0, seedRPCList.Len())
for _, node := range seedRPCList.Elems() {
wg.Add(1)
go func(addr string) {
defer wg.Done()
nodeState, err := GetNodeStateContext(ctx, &RPCConfig{
SeedRPCServerAddr: nkngomobile.NewStringArray(addr),
RPCTimeout: timeout,
HttpDialContext: dialContext,
})
if err != nil {
return
}
if nodeState.SyncState != pb.SyncState_name[int32(pb.SyncState_PERSIST_FINISHED)] {
return
}
lock.Lock()
rpcAddrs = append(rpcAddrs, addr)
lock.Unlock()
}(node)
}
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-done:
}
return nkngomobile.NewStringArray(rpcAddrs...), nil
}