-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathgroup.go
414 lines (367 loc) · 10.9 KB
/
group.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
package mtg
import (
"context"
"encoding/hex"
"fmt"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/MixinNetwork/mixin/common"
"github.com/MixinNetwork/mixin/crypto"
"github.com/MixinNetwork/mixin/logger"
"github.com/fox-one/mixin-sdk-go/v2"
"github.com/fox-one/mixin-sdk-go/v2/mixinnet"
"github.com/shopspring/decimal"
)
const (
groupGenesisId = "group-genesis-id"
groupBootSynced = "group-boot-synced"
defaultKernelRPC = "https://kernel.mixin.dev"
)
type Worker interface {
// process the action in a queue and return transactions
// need to ensure enough balance with CheckAssetBalanceAt(ctx, a)
// before return any transactions, otherwise the transactions
// will be ignored when issuficient balance
//
// if we want to make a multi process worker, it's possible that
// we pass some RPC handle to the process, or we could build a
// whole state of the current sequence and send it to the process
// i.e. ProcessOutput(StateAtSequence, Action) []*Transaction
ProcessOutput(context.Context, *Action) ([]*Transaction, string)
}
type Group struct {
mixin *mixin.Client
store *SQLite3Store
workers map[string]Worker
entries map[string]string
groupSize int
waitDuration time.Duration
id string
GroupId string
rawMembers []string
threshold int
index int
epoch uint64
spendPrivateKey string
debug bool
kernelRPC string
}
func BuildGroup(ctx context.Context, store *SQLite3Store, conf *Configuration) (*Group, error) {
if cg := conf.Genesis; len(cg.Members) < cg.Threshold || cg.Threshold < 1 {
return nil, fmt.Errorf("invalid group threshold %d %d", len(cg.Members), cg.Threshold)
}
if !strings.Contains(strings.Join(conf.Genesis.Members, ","), conf.App.AppId) {
return nil, fmt.Errorf("app %s not belongs to the group", conf.App.AppId)
}
client, err := mixin.NewFromKeystore(&mixin.Keystore{
AppID: conf.App.AppId,
SessionID: conf.App.SessionId,
SessionPrivateKey: conf.App.SessionPrivateKey,
ServerPublicKey: conf.App.ServerPublicKey,
})
if err != nil {
return nil, err
}
if !CheckTestEnvironment(ctx) {
_, err := client.UserMe(ctx)
if err != nil {
return nil, err
}
}
id := generateGenesisId(conf)
grp := &Group{
mixin: client,
store: store,
spendPrivateKey: conf.App.SpendPrivateKey,
id: id,
GroupId: UniqueId(id, conf.Project),
groupSize: conf.GroupSize,
waitDuration: time.Duration(conf.LoopWaitDuration),
workers: make(map[string]Worker),
entries: make(map[string]string),
kernelRPC: defaultKernelRPC,
index: -1,
}
if grp.groupSize <= 0 {
grp.groupSize = OutputsBatchSize
}
oid, err := store.ReadProperty(ctx, groupGenesisId)
if err != nil {
return nil, err
}
if len(oid) > 0 && string(oid) != grp.id {
return nil, fmt.Errorf("malformed group genesis id %s %s", string(oid), grp.id)
}
err = store.WriteProperty(ctx, groupGenesisId, grp.id)
if err != nil {
return nil, err
}
err = store.WriteProperty(ctx, groupBootSynced, "0")
if err != nil {
return nil, err
}
for _, id := range conf.Genesis.Members {
err = grp.AddNode(ctx, id, conf.Genesis.Threshold, conf.Genesis.Epoch)
if err != nil {
return nil, err
}
}
members, threshold, epoch, err := grp.ListActiveNodes(ctx)
if err != nil {
return nil, err
}
sort.Strings(members)
grp.rawMembers = members
grp.threshold = threshold
grp.index = grp.calculateIndex()
grp.epoch = epoch
return grp, nil
}
func (grp *Group) GenesisId() string {
return grp.id
}
func (grp *Group) GetMembers() []string {
ms := make([]string, len(grp.rawMembers))
n := copy(ms, grp.rawMembers)
if len(grp.rawMembers) != n {
panic(n)
}
if grp.debug {
sort.Strings(ms)
if !slices.Equal(ms, grp.rawMembers) {
panic(ms)
}
}
return ms
}
func (grp *Group) GetThreshold() int {
return grp.threshold
}
func (grp *Group) Index() int {
if grp.index < 0 {
panic(grp.index)
}
return grp.index
}
func (grp *Group) EnableDebug() {
grp.debug = true
}
func (grp *Group) SetKernelRPC(rpc string) {
grp.kernelRPC = rpc
}
func (grp *Group) Synced(ctx context.Context) bool {
v, err := grp.store.ReadProperty(ctx, groupBootSynced)
if err != nil {
panic(err)
}
return v == "1"
}
func (grp *Group) AttachWorker(appId string, wkr Worker) {
if grp.FindWorker(appId) != nil {
panic(appId)
}
grp.workers[appId] = wkr
}
func (grp *Group) RegisterDepositEntry(appId string, entry DepositEntry) {
key := entry.UniqueKey()
if grp.FindWorker(appId) == nil || grp.FindAppByEntry(key) != "" {
panic(appId)
}
grp.entries[key] = appId
}
func (grp *Group) FindWorker(appId string) Worker {
return grp.workers[appId]
}
func (grp *Group) FindAppByEntry(entry string) string {
return grp.entries[entry]
}
func (grp *Group) calculateIndex() int {
for i, id := range grp.GetMembers() {
if grp.mixin.ClientID == id {
return i
}
}
panic(grp.mixin.ClientID)
}
func (grp *Group) Run(ctx context.Context) {
logger.Printf("Group(%s, %d, %s).Run(v0.10.0)\n", mixinnet.HashMembers(grp.GetMembers()), grp.threshold, grp.GenesisId())
filter := make(map[string]bool)
for {
time.Sleep(grp.waitDuration)
// drain all the utxos in the order of sequence
logger.Verbosef("Group.Run(drainOutputsFromNetwork) created\n")
grp.drainOutputsFromNetwork(ctx, filter, 500)
err := grp.store.WriteProperty(ctx, groupBootSynced, "1")
if err != nil {
panic(err)
}
// handle the utxos queue by sequence
logger.Verbosef("Group.Run(handleActionsQueue)\n")
err = grp.handleActionsQueue(ctx)
if err != nil {
panic(err)
}
// sign any possible transactions from BuildTransaction
logger.Verbosef("Group.Run(signTransactions)\n")
err = grp.signTransactions(ctx)
if err != nil {
panic(err)
}
// verify all transactions
logger.Verbosef("Group.Run(publishTransactions)\n")
err = grp.publishTransactions(ctx)
if err != nil {
panic(err)
}
// verify all withdrawal transactions
logger.Verbosef("Group.Run(confirmWithdrawalTransactions)\n")
err = grp.confirmWithdrawalTransactions(ctx)
if err != nil {
panic(err)
}
}
}
func (grp *Group) ListOutputsForAsset(ctx context.Context, appId, assetId string, consumedUntil, sequence uint64, state SafeUtxoState, limit int) []*UnifiedOutput {
outputs, err := grp.store.ListOutputsForAsset(ctx, appId, assetId, consumedUntil, sequence, state, limit)
if err != nil {
panic(err)
}
return outputs
}
func (grp *Group) ListOutputsForTransaction(ctx context.Context, traceId string, sequence uint64) []*UnifiedOutput {
outputs, err := grp.store.ListOutputsForTransaction(ctx, traceId, sequence)
if err != nil {
panic(err)
}
return outputs
}
func (grp *Group) ListOutputsByTransactionHash(ctx context.Context, hash string, sequence uint64) []*UnifiedOutput {
outputs, err := grp.store.ListOutputsByTransactionHash(ctx, hash, sequence)
if err != nil {
panic(err)
}
return outputs
}
func (grp *Group) ListUnconfirmedWithdrawalTransactions(ctx context.Context, limit int) []*Transaction {
txs, err := grp.store.ListUnconfirmedWithdrawalTransactions(ctx, limit)
if err != nil {
panic(err)
}
return txs
}
func (grp *Group) ListConfirmedWithdrawalTransactionsAfter(ctx context.Context, offset time.Time, limit int) []*Transaction {
txs, err := grp.store.ListConfirmedWithdrawalTransactionsAfter(ctx, offset, limit)
if err != nil {
panic(err)
}
return txs
}
// this function or rpc should be used only in ProcessOutput
func (act *Action) CheckAssetBalanceAt(ctx context.Context, assetId string) decimal.Decimal {
os, err := act.group.store.ListOutputsForAsset(ctx, act.AppId, assetId, act.consumed[assetId], act.Sequence, SafeUtxoStateUnspent, OutputsBatchSize)
if err != nil {
panic(err)
}
total := decimal.NewFromInt(0)
for _, o := range os {
total = total.Add(o.Amount)
}
return total
}
func (act *Action) CheckAssetBalanceForStorageAt(ctx context.Context, extra []byte) bool {
if len(extra) > common.ExtraSizeStorageCapacity {
panic(fmt.Errorf("too large extra %d > %d", len(extra), common.ExtraSizeStorageCapacity))
}
amount := getStorageTransactionAmount(extra)
total := act.CheckAssetBalanceAt(ctx, StorageAssetId)
return common.NewIntegerFromString(total.String()).Cmp(amount) > 0
}
func (grp *Group) signTransactionWithAsset(ctx context.Context, wg *sync.WaitGroup, asset string, txs []*Transaction) {
logger.Verbosef("Group.signTransactionWithAsset(%s)", asset)
defer wg.Done()
for _, tx := range txs {
ver := grp.signTransaction(ctx, tx)
if ver == nil {
break
}
logger.Verbosef("Group.signTransaction(%v) => %s", *tx, hex.EncodeToString(ver.Marshal()))
}
}
func (grp *Group) signTransactions(ctx context.Context) error {
_, assetTxMap, err := grp.store.ListTransactions(ctx, TransactionStateInitial, 0)
if err != nil {
panic(err)
}
var wg sync.WaitGroup
for asset, txs := range assetTxMap {
wg.Add(1)
go grp.signTransactionWithAsset(ctx, &wg, asset, txs)
}
wg.Wait()
return nil
}
func (grp *Group) publishTransactions(ctx context.Context) error {
txs, _, err := grp.store.ListTransactions(ctx, TransactionStateSigned, 0)
if err != nil || len(txs) == 0 {
return err
}
for _, tx := range txs {
snapshot, err := grp.snapshotTransaction(ctx, tx)
if err != nil {
return err
} else if !snapshot {
continue
}
err = grp.store.FinishTransaction(ctx, tx.TraceId)
if err != nil {
return err
}
}
return nil
}
func (grp *Group) snapshotTransaction(ctx context.Context, tx *Transaction) (bool, error) {
req, err := grp.readTransactionUntilSufficient(ctx, tx.RequestID())
logger.Verbosef("group.readTransactionUntilSufficient(%s, %s) => %v", tx.TraceId, tx.RequestID(), err)
if err != nil || req == nil {
return false, err
}
if req.TransactionHash != tx.Hash.String() {
panic(tx.TraceId)
}
return req.State == SafeUtxoStateSpent, nil
}
func (grp *Group) confirmWithdrawalTransactions(ctx context.Context) error {
txs, err := grp.store.ListUnconfirmedWithdrawalTransactions(ctx, 100)
if err != nil || len(txs) == 0 {
return err
}
for _, tx := range txs {
req, err := grp.readTransactionUntilSufficient(ctx, tx.RequestID())
logger.Verbosef("group.readTransactionUntilSufficient(%s, %s) => %v", tx.TraceId, tx.RequestID(), err)
if err != nil {
return err
}
if req.TransactionHash != tx.Hash.String() || req.Receivers[0].Destination != tx.Destination.String {
panic(tx.TraceId)
}
if req.Receivers[0].WithdrawalHash == "" {
continue
}
err = grp.store.ConfirmWithdrawalTransaction(ctx, tx.TraceId, req.Receivers[0].WithdrawalHash)
if err != nil {
return err
}
}
return nil
}
func generateGenesisId(conf *Configuration) string {
sort.Slice(conf.Genesis.Members, func(i, j int) bool {
return conf.Genesis.Members[i] < conf.Genesis.Members[j]
})
id := strings.Join(conf.Genesis.Members, "")
id = fmt.Sprintf("%s:%d:%d", id, conf.Genesis.Threshold, conf.Genesis.Epoch)
return crypto.Sha256Hash([]byte(id)).String()
}