/
block_processor.go
462 lines (445 loc) · 14.7 KB
/
block_processor.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
454
455
456
457
458
459
460
461
462
package backend
import (
"context"
"crypto"
"fmt"
"log/slog"
sdk "github.com/alphabill-org/alphabill-wallet/wallet"
"github.com/alphabill-org/alphabill/logger"
"github.com/alphabill-org/alphabill/network/protocol/genesis"
"github.com/alphabill-org/alphabill/txsystem/fc/transactions"
"github.com/alphabill-org/alphabill/txsystem/money"
"github.com/alphabill-org/alphabill/types"
)
const (
DustBillDeletionTimeout = 65536
ExpiredBillDeletionTimeout = 65536
)
type BlockProcessor struct {
store BillStore
sdrs map[types.SystemID]*genesis.SystemDescriptionRecord
moneySDR *genesis.SystemDescriptionRecord
log *slog.Logger
}
func NewBlockProcessor(store BillStore, moneySystemID types.SystemID, log *slog.Logger) (*BlockProcessor, error) {
sdrs, err := store.Do().GetSystemDescriptionRecords()
if err != nil {
return nil, fmt.Errorf("failed to get system description records: %w", err)
}
sdrsMap := map[types.SystemID]*genesis.SystemDescriptionRecord{}
for _, sdr := range sdrs {
sdrsMap[sdr.SystemIdentifier] = sdr
}
return &BlockProcessor{store: store, sdrs: sdrsMap, moneySDR: sdrsMap[moneySystemID], log: log}, nil
}
func (p *BlockProcessor) ProcessBlock(ctx context.Context, b *types.Block) error {
roundNumber := b.GetRoundNumber()
log := p.log.With(logger.Round(roundNumber))
log.InfoContext(ctx, fmt.Sprintf("processing block with %d transactions", len(b.Transactions)))
return p.store.WithTransaction(func(dbTx BillStoreTx) error {
lastBlockNumber, err := dbTx.GetBlockNumber()
if err != nil {
return err
}
if lastBlockNumber >= roundNumber {
return fmt.Errorf("invalid block number. Received blockNumber %d current wallet blockNumber %d", roundNumber, lastBlockNumber)
}
for i, tx := range b.Transactions {
if err := p.processTx(tx, b, i, dbTx, log); err != nil {
return fmt.Errorf("failed to process transaction: %w", err)
}
}
if err := dbTx.DeleteExpiredBills(roundNumber); err != nil {
return fmt.Errorf("failed to delete expired bills: %w", err)
}
return dbTx.SetBlockNumber(roundNumber)
})
}
func (p *BlockProcessor) processTx(txr *types.TransactionRecord, b *types.Block, txIdx int, dbTx BillStoreTx, log *slog.Logger) error {
txo := txr.TransactionOrder
txHash := txo.Hash(crypto.SHA256)
proof, err := sdk.NewTxProof(txIdx, b, crypto.SHA256)
if err != nil {
return err
}
log.Info(fmt.Sprintf("processing %q order", txo.PayloadType()), logger.UnitID(txo.UnitID()))
switch txo.PayloadType() {
case money.PayloadTypeTransfer:
if err = p.updateFCB(dbTx, txr); err != nil {
return err
}
attr := &money.TransferAttributes{}
if err = txo.UnmarshalAttributes(attr); err != nil {
return err
}
if err = dbTx.SetBill(&Bill{
Id: txo.UnitID(),
Value: attr.TargetValue,
TxHash: txHash,
OwnerPredicate: attr.NewBearer,
}, proof); err != nil {
return err
}
if err = saveTx(dbTx, attr.NewBearer, txo, txHash); err != nil {
return err
}
case money.PayloadTypeTransDC:
err := p.updateFCB(dbTx, txr)
if err != nil {
return err
}
attr := &money.TransferDCAttributes{}
err = txo.UnmarshalAttributes(attr)
if err != nil {
return err
}
// update bill value, txHash, target unit
dcBill, err := dbTx.GetBill(txo.UnitID())
if err != nil {
return fmt.Errorf("failed to fetch bill: %w", err)
}
if dcBill == nil {
return fmt.Errorf("bill not found: %s", txo.UnitID())
}
dcBill.Value = attr.Value
dcBill.TxHash = txHash
dcBill.DCTargetUnitID = attr.TargetUnitID
dcBill.DCTargetUnitBacklink = attr.TargetUnitBacklink
err = dbTx.SetBill(dcBill, proof)
if err != nil {
return err
}
// TODO AB-1133
//err = dbTx.SetBillExpirationTime(roundNumber+DustBillDeletionTimeout, txo.UnitID())
//if err != nil {
// return err
//}
case money.PayloadTypeSplit:
err := p.updateFCB(dbTx, txr)
if err != nil {
return err
}
attr := &money.SplitAttributes{}
err = txo.UnmarshalAttributes(attr)
if err != nil {
return err
}
// old bill
oldBill, err := dbTx.GetBill(txo.UnitID())
if err != nil {
return err
}
if oldBill != nil {
err = dbTx.SetBill(&Bill{
Id: txo.UnitID(),
Value: attr.RemainingValue,
TxHash: txHash,
OwnerPredicate: oldBill.OwnerPredicate,
}, proof)
if err != nil {
return err
}
} else {
// we should always have the "previous bill" other than splitting the initial bill or some error condition
log.Warn("received split order where existing unit was not found, ignoring tx", logger.UnitID(txo.UnitID()))
}
// new bills
for i, targetUnit := range attr.TargetUnits {
newID := money.NewBillID(txo.UnitID(), money.HashForIDCalculation(txo.UnitID(), txo.Payload.Attributes, txo.Timeout(), uint32(i), crypto.SHA256))
log.Info(fmt.Sprintf("new UnitID=%x for split order", newID), logger.UnitID(txo.UnitID()))
err = dbTx.SetBill(&Bill{
Id: newID,
TxHash: txHash,
Value: targetUnit.Amount,
OwnerPredicate: targetUnit.OwnerCondition,
}, proof)
if err != nil {
return fmt.Errorf("failed to store split tx unit for new id %s at index %d", newID, i)
}
if err := saveTx(dbTx, targetUnit.OwnerCondition, txo, txHash); err != nil {
return fmt.Errorf("failed to store tx history record: %w", err)
}
}
case money.PayloadTypeSwapDC:
err := p.updateFCB(dbTx, txr)
if err != nil {
return err
}
attr := &money.SwapDCAttributes{}
err = txo.UnmarshalAttributes(attr)
if err != nil {
return err
}
bill, err := dbTx.GetBill(txo.UnitID())
if err != nil {
return err
}
if bill == nil {
return fmt.Errorf("existing bill not found for swap tx (UnitID=%s)", txo.UnitID())
}
bill.Value += attr.TargetValue
bill.TxHash = txHash
bill.OwnerPredicate = attr.OwnerCondition
bill.Locked = 0
err = dbTx.SetBill(bill, proof)
if err != nil {
return err
}
for _, dustTransfer := range attr.DcTransfers {
err := dbTx.RemoveBill(dustTransfer.TransactionOrder.UnitID())
if err != nil {
return err
}
}
case money.PayloadTypeLock:
if err := p.updateFCB(dbTx, txr); err != nil {
return fmt.Errorf("failed to update fee credit bill: %w", err)
}
bill, err := dbTx.GetBill(txo.UnitID())
if err != nil {
return err
}
if bill == nil {
return fmt.Errorf("unit not found for lock tx (unitID=%s)", txo.UnitID())
}
attr := &money.LockAttributes{}
if err := txo.UnmarshalAttributes(attr); err != nil {
return err
}
bill.Locked = sdk.LockReason(attr.LockStatus)
bill.TxHash = txHash
return dbTx.SetBill(bill, proof)
case money.PayloadTypeUnlock:
if err := p.updateFCB(dbTx, txr); err != nil {
return fmt.Errorf("failed to update fee credit bill: %w", err)
}
bill, err := dbTx.GetBill(txo.UnitID())
if err != nil {
return err
}
if bill == nil {
return fmt.Errorf("unit not found for unlock tx (unitID=%s)", txo.UnitID())
}
bill.Locked = 0
bill.TxHash = txHash
return dbTx.SetBill(bill, proof)
case transactions.PayloadTypeTransferFeeCredit:
bill, err := dbTx.GetBill(txo.UnitID())
if err != nil {
return fmt.Errorf("failed to get bill: %w", err)
}
if bill == nil {
return fmt.Errorf("unit not found for transferFC tx (unitID=%s)", txo.UnitID())
}
attr := &transactions.TransferFeeCreditAttributes{}
err = txo.UnmarshalAttributes(attr)
if err != nil {
return fmt.Errorf("failed to unmarshal transferFC attributes: %w", err)
}
if attr.Amount < bill.Value {
bill.Value -= attr.Amount
bill.TxHash = txHash
if err := dbTx.SetBill(bill, proof); err != nil {
return fmt.Errorf("failed to save transferFC bill with proof: %w", err)
}
} else {
if err := dbTx.StoreTxProof(txo.UnitID(), txHash, proof); err != nil {
return fmt.Errorf("failed to store tx proof zero value bill: %w", err)
}
if err := dbTx.RemoveBill(bill.Id); err != nil {
return fmt.Errorf("failed to remove zero value bill: %w", err)
}
}
err = p.addTransferredCreditToPartitionFeeBill(dbTx, attr, proof, txr.ServerMetadata.ActualFee)
if err != nil {
return fmt.Errorf("failed to add transferred fee credit to partition fee bill: %w", err)
}
err = p.addTxFeeToMoneyFeeBill(dbTx, txr, proof)
if err != nil {
return fmt.Errorf("failed to add tx fees to money fee bill: %w", err)
}
return nil
case transactions.PayloadTypeAddFeeCredit:
fcb, err := dbTx.GetFeeCreditBill(txo.UnitID())
if err != nil {
return err
}
addFCAttr := &transactions.AddFeeCreditAttributes{}
err = txo.UnmarshalAttributes(addFCAttr)
if err != nil {
return err
}
transferFCAttr := &transactions.TransferFeeCreditAttributes{}
err = addFCAttr.FeeCreditTransfer.TransactionOrder.UnmarshalAttributes(transferFCAttr)
if err != nil {
return err
}
return dbTx.SetFeeCreditBill(&Bill{
Id: txo.UnitID(),
Value: fcb.getValue() + transferFCAttr.Amount - addFCAttr.FeeCreditTransfer.ServerMetadata.ActualFee - txr.ServerMetadata.ActualFee,
TxHash: txHash,
}, proof)
case transactions.PayloadTypeCloseFeeCredit:
fcb, err := dbTx.GetFeeCreditBill(txo.UnitID())
if err != nil {
return err
}
attr := &transactions.CloseFeeCreditAttributes{}
err = txo.UnmarshalAttributes(attr)
if err != nil {
return err
}
return dbTx.SetFeeCreditBill(&Bill{
Id: txo.UnitID(),
TxHash: txHash,
Value: fcb.getValue() - attr.Amount,
}, proof)
case transactions.PayloadTypeReclaimFeeCredit:
bill, err := dbTx.GetBill(txo.UnitID())
if err != nil {
return err
}
if bill == nil {
return fmt.Errorf("unit not found for reclaimFC tx (unitID=%s)", txo.UnitID())
}
reclaimFCAttr := &transactions.ReclaimFeeCreditAttributes{}
err = txo.UnmarshalAttributes(reclaimFCAttr)
if err != nil {
return err
}
closeFCTXR := reclaimFCAttr.CloseFeeCreditTransfer
closeFCTXO := closeFCTXR.TransactionOrder
closeFCAttr := &transactions.CloseFeeCreditAttributes{}
err = closeFCTXO.UnmarshalAttributes(closeFCAttr)
if err != nil {
return err
}
// 1. remove reclaimed amount from user bill
reclaimedValue := closeFCAttr.Amount - closeFCTXR.ServerMetadata.ActualFee - txr.ServerMetadata.ActualFee
bill.Value += reclaimedValue
bill.TxHash = txHash
bill.Locked = 0
err = dbTx.SetBill(bill, proof)
if err != nil {
return err
}
// 2. remove reclaimed amount from partition fee bill
err = p.removeReclaimedCreditFromPartitionFeeBill(dbTx, closeFCTXR, closeFCAttr, proof)
if err != nil {
return err
}
// 3. add reclaimFC tx fee to money partition fee bill
return p.addTxFeeToMoneyFeeBill(dbTx, txr, proof)
case transactions.PayloadTypeLockFeeCredit:
fcb, err := dbTx.GetFeeCreditBill(txo.UnitID())
if err != nil {
return fmt.Errorf("failed to load fee credit bill: %w", err)
}
if fcb == nil {
return fmt.Errorf("fee credit bill not found: %X", txo.UnitID())
}
actualFee := txr.GetActualFee()
if fcb.Value < actualFee {
return fmt.Errorf("fee credit bill value cannot go negative; value=%d fee=%d", fcb.Value, actualFee)
}
attr := &transactions.LockFeeCreditAttributes{}
if err := txo.UnmarshalAttributes(attr); err != nil {
return fmt.Errorf("failed to unmarshal lockFC attributes: %w", err)
}
fcb.Locked = sdk.LockReason(attr.LockStatus)
fcb.Value -= actualFee
fcb.TxHash = txHash
return dbTx.SetFeeCreditBill(fcb, proof)
case transactions.PayloadTypeUnlockFeeCredit:
fcb, err := dbTx.GetFeeCreditBill(txo.UnitID())
if err != nil {
return fmt.Errorf("failed to load fee credit bill: %w", err)
}
if fcb == nil {
return fmt.Errorf("fee credit bill not found: %X", txo.UnitID())
}
actualFee := txr.GetActualFee()
if fcb.Value < actualFee {
return fmt.Errorf("fee credit bill value cannot go negative; value=%d fee=%d", fcb.Value, actualFee)
}
fcb.Locked = 0
fcb.Value -= actualFee
fcb.TxHash = txHash
return dbTx.SetFeeCreditBill(fcb, proof)
default:
log.Warn(fmt.Sprintf("no handler for transaction type %q, skipping processing", txo.PayloadType()), logger.UnitID(txo.UnitID()))
}
return nil
}
func saveTx(dbTx BillStoreTx, bearer sdk.Predicate, txo *types.TransactionOrder, txHash sdk.TxHash) error {
bearerKeyHash := extractOwnerHashFromP2pkh(bearer)
if bearerKeyHash != nil {
if err := dbTx.StoreTxHistoryRecord(bearerKeyHash, &sdk.TxHistoryRecord{
UnitID: txo.UnitID(),
TxHash: txHash,
Timeout: txo.Timeout(),
State: sdk.CONFIRMED,
Kind: sdk.INCOMING,
CounterParty: extractOwnerKeyFromProof(txo.OwnerProof),
}); err != nil {
return err
}
}
return nil
}
func (p *BlockProcessor) addTransferredCreditToPartitionFeeBill(dbTx BillStoreTx, tx *transactions.TransferFeeCreditAttributes, proof *sdk.Proof, actualFee uint64) error {
sdr, f := p.sdrs[tx.TargetSystemIdentifier]
if !f {
return fmt.Errorf("received transferFC for unknown tx system: %x", tx.TargetSystemIdentifier)
}
partitionFeeBill, err := dbTx.GetBill(sdr.FeeCreditBill.UnitID)
if err != nil {
return err
}
if partitionFeeBill == nil {
return fmt.Errorf("partition fee bill not found: systemID=%x unitID=%x", tx.TargetSystemIdentifier, sdr.FeeCreditBill.UnitID)
}
partitionFeeBill.Value += tx.Amount - actualFee
return dbTx.SetBill(partitionFeeBill, proof)
}
func (p *BlockProcessor) removeReclaimedCreditFromPartitionFeeBill(dbTx BillStoreTx, txr *types.TransactionRecord, attr *transactions.CloseFeeCreditAttributes, proof *sdk.Proof) error {
txo := txr.TransactionOrder
sdr, f := p.sdrs[txo.SystemID()]
if !f {
return fmt.Errorf("received reclaimFC for unknown tx system: %x", txo.SystemID())
}
partitionFeeBill, err := dbTx.GetBill(sdr.FeeCreditBill.UnitID)
if err != nil {
return err
}
if partitionFeeBill == nil {
return fmt.Errorf("partition fee bill not found: systemID=%x unitID=%x", txo.SystemID(), sdr.FeeCreditBill.UnitID)
}
partitionFeeBill.Value -= attr.Amount
partitionFeeBill.Value += txr.ServerMetadata.ActualFee
return dbTx.SetBill(partitionFeeBill, proof)
}
func (p *BlockProcessor) addTxFeeToMoneyFeeBill(dbTx BillStoreTx, tx *types.TransactionRecord, proof *sdk.Proof) error {
moneyFeeBill, err := dbTx.GetBill(p.moneySDR.FeeCreditBill.UnitID)
if err != nil {
return err
}
moneyFeeBill.Value += tx.ServerMetadata.ActualFee
return dbTx.SetBill(moneyFeeBill, proof)
}
func (p *BlockProcessor) updateFCB(dbTx BillStoreTx, txr *types.TransactionRecord) error {
txo := txr.TransactionOrder
fcb, err := dbTx.GetFeeCreditBill(txo.GetClientFeeCreditRecordID())
if err != nil {
return err
}
if fcb == nil {
return fmt.Errorf("fee credit bill not found: %X", txo.GetClientFeeCreditRecordID())
}
actualFee := txr.GetActualFee()
if fcb.Value < actualFee {
return fmt.Errorf("fee credit bill value cannot go negative; value=%d fee=%d", fcb.Value, actualFee)
}
fcb.Value -= actualFee
return dbTx.SetFeeCreditBill(fcb, nil)
}