/
beaconpdeprocess.go
453 lines (432 loc) · 17 KB
/
beaconpdeprocess.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
package blockchain
import (
"encoding/base64"
"encoding/json"
"github.com/incognitochain/incognito-chain/dataaccessobject/rawdbv2"
"reflect"
"strconv"
"github.com/incognitochain/incognito-chain/common"
"github.com/incognitochain/incognito-chain/dataaccessobject/statedb"
"github.com/incognitochain/incognito-chain/metadata"
)
func (blockchain *BlockChain) processPDEInstructions(pdexStateDB *statedb.StateDB, beaconBlock *BeaconBlock) error {
if !hasPDEInstruction(beaconBlock.Body.Instructions) {
return nil
}
beaconHeight := beaconBlock.Header.Height - 1
currentPDEState, err := InitCurrentPDEStateFromDB(pdexStateDB, beaconHeight)
if err != nil {
Logger.log.Error(err)
return nil
}
backUpCurrentPDEState := new(CurrentPDEState)
temp, err := json.Marshal(currentPDEState)
if err != nil {
return err
}
err = json.Unmarshal(temp, backUpCurrentPDEState)
if err != nil {
return err
}
for _, inst := range beaconBlock.Body.Instructions {
if len(inst) < 2 {
continue // Not error, just not PDE instruction
}
var err error
switch inst[0] {
case strconv.Itoa(metadata.PDEContributionMeta):
err = blockchain.processPDEContributionV2(pdexStateDB, beaconHeight, inst, currentPDEState)
case strconv.Itoa(metadata.PDETradeRequestMeta):
err = blockchain.processPDETrade(pdexStateDB, beaconHeight, inst, currentPDEState)
case strconv.Itoa(metadata.PDEWithdrawalRequestMeta):
err = blockchain.processPDEWithdrawal(pdexStateDB, beaconHeight, inst, currentPDEState)
}
if err != nil {
Logger.log.Error(err)
return nil
}
}
if reflect.DeepEqual(backUpCurrentPDEState, currentPDEState) {
return nil
}
// store updated currentPDEState to leveldb with new beacon height
err = storePDEStateToDB(pdexStateDB, beaconHeight+1, currentPDEState)
if err != nil {
Logger.log.Error(err)
}
return nil
}
func hasPDEInstruction(instructions [][]string) bool {
hasPDEXInstruction := false
for _, inst := range instructions {
if len(inst) < 2 {
continue // Not error, just not PDE instruction
}
switch inst[0] {
case strconv.Itoa(metadata.PDEContributionMeta):
hasPDEXInstruction = true
break
case strconv.Itoa(metadata.PDETradeRequestMeta):
hasPDEXInstruction = true
break
case strconv.Itoa(metadata.PDEWithdrawalRequestMeta):
hasPDEXInstruction = true
break
}
}
return hasPDEXInstruction
}
func (blockchain *BlockChain) processPDEContributionV2(pdexStateDB *statedb.StateDB, beaconHeight uint64, instruction []string, currentPDEState *CurrentPDEState) error {
if currentPDEState == nil {
Logger.log.Warn("WARN - [processPDEContribution]: Current PDE state is null.")
return nil
}
if len(instruction) != 4 {
return nil // skip the instruction
}
contributionStatus := instruction[2]
if contributionStatus == common.PDEContributionWaitingChainStatus {
var waitingContribution metadata.PDEWaitingContribution
err := json.Unmarshal([]byte(instruction[3]), &waitingContribution)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while unmarshaling content string of pde waiting contribution instruction: %+v", err)
return nil
}
waitingContribPairKey := string(rawdbv2.BuildWaitingPDEContributionKey(beaconHeight, waitingContribution.PDEContributionPairID))
currentPDEState.WaitingPDEContributions[waitingContribPairKey] = &rawdbv2.PDEContribution{
ContributorAddressStr: waitingContribution.ContributorAddressStr,
TokenIDStr: waitingContribution.TokenIDStr,
Amount: waitingContribution.ContributedAmount,
TxReqID: waitingContribution.TxReqID,
}
contribStatus := metadata.PDEContributionStatus{
Status: byte(common.PDEContributionWaitingStatus),
}
contribStatusBytes, _ := json.Marshal(contribStatus)
err = statedb.TrackPDEContributionStatus(
pdexStateDB,
rawdbv2.PDEContributionStatusPrefix,
[]byte(waitingContribution.PDEContributionPairID),
contribStatusBytes,
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde waiting contribution status: %+v", err)
return nil
}
} else if contributionStatus == common.PDEContributionRefundChainStatus {
var refundContribution metadata.PDERefundContribution
err := json.Unmarshal([]byte(instruction[3]), &refundContribution)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while unmarshaling content string of pde refund contribution instruction: %+v", err)
return nil
}
waitingContribPairKey := string(rawdbv2.BuildWaitingPDEContributionKey(beaconHeight, refundContribution.PDEContributionPairID))
existingWaitingContribution, found := currentPDEState.WaitingPDEContributions[waitingContribPairKey]
if found {
currentPDEState.DeletedWaitingPDEContributions[waitingContribPairKey] = existingWaitingContribution
delete(currentPDEState.WaitingPDEContributions, waitingContribPairKey)
}
contribStatus := metadata.PDEContributionStatus{
Status: byte(common.PDEContributionRefundStatus),
}
contribStatusBytes, _ := json.Marshal(contribStatus)
err = statedb.TrackPDEContributionStatus(
pdexStateDB,
rawdbv2.PDEContributionStatusPrefix,
[]byte(refundContribution.PDEContributionPairID),
contribStatusBytes,
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde refund contribution status: %+v", err)
return nil
}
} else if contributionStatus == common.PDEContributionMatchedChainStatus {
var matchedContribution metadata.PDEMatchedContribution
err := json.Unmarshal([]byte(instruction[3]), &matchedContribution)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while unmarshaling content string of pde matched contribution instruction: %+v", err)
return nil
}
waitingContribPairKey := string(rawdbv2.BuildWaitingPDEContributionKey(beaconHeight, matchedContribution.PDEContributionPairID))
existingWaitingContribution, found := currentPDEState.WaitingPDEContributions[waitingContribPairKey]
if !found || existingWaitingContribution == nil {
Logger.log.Errorf("ERROR: could not find out existing waiting contribution with unique pair id: %s", matchedContribution.PDEContributionPairID)
return nil
}
incomingWaitingContribution := &rawdbv2.PDEContribution{
ContributorAddressStr: matchedContribution.ContributorAddressStr,
TokenIDStr: matchedContribution.TokenIDStr,
Amount: matchedContribution.ContributedAmount,
TxReqID: matchedContribution.TxReqID,
}
updateWaitingContributionPairToPoolV2(
beaconHeight,
existingWaitingContribution,
incomingWaitingContribution,
currentPDEState,
)
currentPDEState.DeletedWaitingPDEContributions[waitingContribPairKey] = existingWaitingContribution
delete(currentPDEState.WaitingPDEContributions, waitingContribPairKey)
contribStatus := metadata.PDEContributionStatus{
Status: byte(common.PDEContributionAcceptedStatus),
}
contribStatusBytes, _ := json.Marshal(contribStatus)
err = statedb.TrackPDEContributionStatus(
pdexStateDB,
rawdbv2.PDEContributionStatusPrefix,
[]byte(matchedContribution.PDEContributionPairID),
contribStatusBytes,
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde accepted contribution status: %+v", err)
return nil
}
} else if contributionStatus == common.PDEContributionMatchedNReturnedChainStatus {
var matchedNReturnedContrib metadata.PDEMatchedNReturnedContribution
err := json.Unmarshal([]byte(instruction[3]), &matchedNReturnedContrib)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while unmarshaling content string of pde matched and returned contribution instruction: %+v", err)
return nil
}
waitingContribPairKey := string(rawdbv2.BuildWaitingPDEContributionKey(beaconHeight, matchedNReturnedContrib.PDEContributionPairID))
waitingContribution, found := currentPDEState.WaitingPDEContributions[waitingContribPairKey]
if found && waitingContribution != nil {
incomingWaitingContribution := &rawdbv2.PDEContribution{
ContributorAddressStr: matchedNReturnedContrib.ContributorAddressStr,
TokenIDStr: matchedNReturnedContrib.TokenIDStr,
Amount: matchedNReturnedContrib.ActualContributedAmount,
TxReqID: matchedNReturnedContrib.TxReqID,
}
existingWaitingContribution := &rawdbv2.PDEContribution{
ContributorAddressStr: waitingContribution.ContributorAddressStr,
TokenIDStr: waitingContribution.TokenIDStr,
Amount: matchedNReturnedContrib.ActualWaitingContribAmount,
TxReqID: waitingContribution.TxReqID,
}
updateWaitingContributionPairToPoolV2(
beaconHeight,
existingWaitingContribution,
incomingWaitingContribution,
currentPDEState,
)
currentPDEState.DeletedWaitingPDEContributions[waitingContribPairKey] = waitingContribution
delete(currentPDEState.WaitingPDEContributions, waitingContribPairKey)
}
pdeStatusContentBytes, err := statedb.GetPDEContributionStatus(
pdexStateDB,
rawdbv2.PDEContributionStatusPrefix,
[]byte(matchedNReturnedContrib.PDEContributionPairID),
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while getting pde contribution status: %+v", err)
return nil
}
if len(pdeStatusContentBytes) == 0 {
return nil
}
var contribStatus metadata.PDEContributionStatus
err = json.Unmarshal(pdeStatusContentBytes, &contribStatus)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while unmarshaling pde contribution status: %+v", err)
return nil
}
if contribStatus.Status != byte(common.PDEContributionMatchedNReturnedStatus) {
contribStatus := metadata.PDEContributionStatus{
Status: byte(common.PDEContributionMatchedNReturnedStatus),
TokenID1Str: matchedNReturnedContrib.TokenIDStr,
Contributed1Amount: matchedNReturnedContrib.ActualContributedAmount,
Returned1Amount: matchedNReturnedContrib.ReturnedContributedAmount,
}
contribStatusBytes, _ := json.Marshal(contribStatus)
err := statedb.TrackPDEContributionStatus(
pdexStateDB,
rawdbv2.PDEContributionStatusPrefix,
[]byte(matchedNReturnedContrib.PDEContributionPairID),
contribStatusBytes,
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde contribution status: %+v", err)
return nil
}
} else {
var contribStatus metadata.PDEContributionStatus
err := json.Unmarshal(pdeStatusContentBytes, &contribStatus)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while unmarshaling pde contribution status: %+v", err)
return nil
}
contribStatus.TokenID2Str = matchedNReturnedContrib.TokenIDStr
contribStatus.Contributed2Amount = matchedNReturnedContrib.ActualContributedAmount
contribStatus.Returned2Amount = matchedNReturnedContrib.ReturnedContributedAmount
contribStatusBytes, _ := json.Marshal(contribStatus)
err = statedb.TrackPDEContributionStatus(
pdexStateDB,
rawdbv2.PDEContributionStatusPrefix,
[]byte(matchedNReturnedContrib.PDEContributionPairID),
contribStatusBytes,
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde contribution status: %+v", err)
return nil
}
}
}
return nil
}
func (blockchain *BlockChain) processPDETrade(pdexStateDB *statedb.StateDB, beaconHeight uint64, instruction []string, currentPDEState *CurrentPDEState) error {
if len(instruction) != 4 {
return nil // skip the instruction
}
if instruction[2] == common.PDETradeRefundChainStatus {
contentBytes, err := base64.StdEncoding.DecodeString(instruction[3])
if err != nil {
Logger.log.Errorf("ERROR: an error occured while decoding content string of pde trade instruction: %+v", err)
return nil
}
var pdeTradeReqAction metadata.PDETradeRequestAction
err = json.Unmarshal(contentBytes, &pdeTradeReqAction)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while unmarshaling pde trade instruction: %+v", err)
return nil
}
err = statedb.TrackPDEStatus(
pdexStateDB,
rawdbv2.PDETradeStatusPrefix,
pdeTradeReqAction.TxReqID[:],
byte(common.PDETradeRefundStatus),
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde refund trade status: %+v", err)
}
return nil
}
var pdeTradeAcceptedContent metadata.PDETradeAcceptedContent
err := json.Unmarshal([]byte(instruction[3]), &pdeTradeAcceptedContent)
if err != nil {
Logger.log.Errorf("WARNING: an error occured while unmarshaling PDETradeAcceptedContent: %+v", err)
return nil
}
pdePoolForPairKey := string(rawdbv2.BuildPDEPoolForPairKey(beaconHeight, pdeTradeAcceptedContent.Token1IDStr, pdeTradeAcceptedContent.Token2IDStr))
pdePoolForPair, found := currentPDEState.PDEPoolPairs[pdePoolForPairKey]
if !found || pdePoolForPair == nil {
Logger.log.Errorf("WARNING: could not find out pdePoolForPair with token ids: %s & %s", pdeTradeAcceptedContent.Token1IDStr, pdeTradeAcceptedContent.Token2IDStr)
return nil
}
if pdeTradeAcceptedContent.Token1PoolValueOperation.Operator == "+" {
pdePoolForPair.Token1PoolValue += pdeTradeAcceptedContent.Token1PoolValueOperation.Value
pdePoolForPair.Token2PoolValue -= pdeTradeAcceptedContent.Token2PoolValueOperation.Value
} else {
pdePoolForPair.Token1PoolValue -= pdeTradeAcceptedContent.Token1PoolValueOperation.Value
pdePoolForPair.Token2PoolValue += pdeTradeAcceptedContent.Token2PoolValueOperation.Value
}
err = statedb.TrackPDEStatus(
pdexStateDB,
rawdbv2.PDETradeStatusPrefix,
pdeTradeAcceptedContent.RequestedTxID[:],
byte(common.PDETradeAcceptedStatus),
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde accepted trade status: %+v", err)
}
return nil
}
func (blockchain *BlockChain) processPDEWithdrawal(pdexStateDB *statedb.StateDB, beaconHeight uint64, instruction []string, currentPDEState *CurrentPDEState) error {
if len(instruction) != 4 {
return nil // skip the instruction
}
if instruction[2] == common.PDEWithdrawalRejectedChainStatus {
contentBytes, err := base64.StdEncoding.DecodeString(instruction[3])
if err != nil {
Logger.log.Errorf("ERROR: an error occured while decoding content string of pde withdrawal action: %+v", err)
return nil
}
var pdeWithdrawalRequestAction metadata.PDEWithdrawalRequestAction
err = json.Unmarshal(contentBytes, &pdeWithdrawalRequestAction)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while unmarshaling pde withdrawal request action: %+v", err)
return nil
}
err = statedb.TrackPDEStatus(
pdexStateDB,
rawdbv2.PDEWithdrawalStatusPrefix,
pdeWithdrawalRequestAction.TxReqID[:],
byte(common.PDEWithdrawalRejectedStatus),
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde rejected withdrawal status: %+v", err)
}
return nil
}
var wdAcceptedContent metadata.PDEWithdrawalAcceptedContent
err := json.Unmarshal([]byte(instruction[3]), &wdAcceptedContent)
if err != nil {
Logger.log.Errorf("WARNING: an error occured while unmarshaling PDEWithdrawalAcceptedContent: %+v", err)
return nil
}
// update pde pool pair
pdePoolForPairKey := string(rawdbv2.BuildPDEPoolForPairKey(
beaconHeight,
wdAcceptedContent.PairToken1IDStr,
wdAcceptedContent.PairToken2IDStr,
))
pdePoolForPair, found := currentPDEState.PDEPoolPairs[pdePoolForPairKey]
if !found || pdePoolForPair == nil {
Logger.log.Errorf("WARNING: could not find out pdePoolForPair with token ids: %s & %s", wdAcceptedContent.PairToken1IDStr, wdAcceptedContent.PairToken2IDStr)
return nil
}
if pdePoolForPair.Token1IDStr == wdAcceptedContent.WithdrawalTokenIDStr {
pdePoolForPair.Token1PoolValue -= wdAcceptedContent.DeductingPoolValue
} else {
pdePoolForPair.Token2PoolValue -= wdAcceptedContent.DeductingPoolValue
}
// update pde shares
deductSharesForWithdrawal(
beaconHeight,
wdAcceptedContent.PairToken1IDStr, wdAcceptedContent.PairToken2IDStr,
wdAcceptedContent.WithdrawerAddressStr,
wdAcceptedContent.DeductingShares,
currentPDEState,
)
err = statedb.TrackPDEStatus(
pdexStateDB,
rawdbv2.PDEWithdrawalStatusPrefix,
wdAcceptedContent.TxReqID[:],
byte(common.PDEWithdrawalAcceptedStatus),
)
if err != nil {
Logger.log.Errorf("ERROR: an error occured while tracking pde accepted withdrawal status: %+v", err)
}
return nil
}
func storePDEPoolForPair(
pdePoolForPairKey string,
token1IDStr string,
token1PoolValue uint64,
token2IDStr string,
token2PoolValue uint64,
currentPDEState *CurrentPDEState,
) {
pdePoolForPair := &rawdbv2.PDEPoolForPair{
Token1IDStr: token1IDStr,
Token1PoolValue: token1PoolValue,
Token2IDStr: token2IDStr,
Token2PoolValue: token2PoolValue,
}
currentPDEState.PDEPoolPairs[pdePoolForPairKey] = pdePoolForPair
}
func deductSharesForWithdrawal(
beaconHeight uint64,
token1IDStr string,
token2IDStr string,
withdrawerAddressStr string,
amt uint64,
currentPDEState *CurrentPDEState,
) {
pdeShareKey := string(rawdbv2.BuildPDESharesKeyV2(beaconHeight, token1IDStr, token2IDStr, withdrawerAddressStr))
adjustingAmt := uint64(0)
currentAmt, found := currentPDEState.PDEShares[pdeShareKey]
if found && amt <= currentAmt {
adjustingAmt = currentAmt - amt
}
currentPDEState.PDEShares[pdeShareKey] = adjustingAmt
}