forked from hyperledger-labs/fabric-token-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.go
More file actions
481 lines (401 loc) · 16.1 KB
/
store.go
File metadata and controls
481 lines (401 loc) · 16.1 KB
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package ttxdb
import (
"context"
"math/big"
"reflect"
"time"
"github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors"
cdriver "github.com/hyperledger-labs/fabric-smart-client/platform/common/driver"
"github.com/hyperledger-labs/fabric-token-sdk/token"
driver2 "github.com/hyperledger-labs/fabric-token-sdk/token/driver"
"github.com/hyperledger-labs/fabric-token-sdk/token/services/logging"
"github.com/hyperledger-labs/fabric-token-sdk/token/services/storage/db"
"github.com/hyperledger-labs/fabric-token-sdk/token/services/storage/db/common"
dbdriver "github.com/hyperledger-labs/fabric-token-sdk/token/services/storage/db/driver"
"github.com/hyperledger-labs/fabric-token-sdk/token/services/storage/db/multiplexed"
)
//go:generate counterfeiter -o mock/ttx_store_service_manager.go --fake-name TTXStoreServiceManager . StoreServiceManager
type StoreServiceManager db.StoreServiceManager[*StoreService]
var (
managerType = reflect.TypeOf((*StoreServiceManager)(nil))
logger = logging.MustGetLogger()
)
func NewStoreServiceManager(cp db.ConfigService, drivers multiplexed.Driver) StoreServiceManager {
return db.NewStoreServiceManager(cp, "ttxdb.persistence", drivers.NewOwnerTransaction, newStoreService)
}
func GetByTMSId(sp token.ServiceProvider, tmsID token.TMSID) (*StoreService, error) {
s, err := sp.GetService(managerType)
if err != nil {
return nil, errors.Wrapf(err, "failed to get manager service")
}
c, err := s.(StoreServiceManager).StoreServiceByTMSId(tmsID)
if err != nil {
return nil, errors.Wrapf(err, "failed to get db for tms [%s]", tmsID)
}
return c, nil
}
// TxStatus is the status of a transaction
type TxStatus = dbdriver.TxStatus
const (
// Unknown is the status of a transaction that is unknown
Unknown = dbdriver.Unknown
// Pending is the status of a transaction that has been submitted to the ledger
Pending = dbdriver.Pending
// Confirmed is the status of a transaction that has been confirmed by the ledger
Confirmed = dbdriver.Confirmed
// Deleted is the status of a transaction that has been deleted due to a failure to commit
Deleted = dbdriver.Deleted
)
// TxStatusMessage maps TxStatus to string
var TxStatusMessage = dbdriver.TxStatusMessage
// ActionType is the type of action performed by a transaction.
type ActionType = dbdriver.ActionType
const (
// Issue is the action type for issuing tokens.
Issue = dbdriver.Issue
// Transfer is the action type for transferring tokens.
Transfer = dbdriver.Transfer
// Redeem is the action type for redeeming tokens.
Redeem = dbdriver.Redeem
)
// SearchDirection defines the direction of a search.
type SearchDirection = dbdriver.SearchDirection
const (
// FromLast defines the direction of a search from the last key.
FromLast = dbdriver.FromLast
// FromBeginning defines the direction of a search from the first key.
FromBeginning = dbdriver.FromBeginning
)
// TransactionRecord is a more finer-grained version of a movement record.
// Given a Token Transaction, for each token action in the Token Request,
// a transaction record is created for each unique enrollment ID found in the outputs.
// The transaction record contains the total amount of the token type that was transferred to/from that enrollment ID
// in that action.
type TransactionRecord = dbdriver.TransactionRecord
// MovementRecord is a record of a movement of assets.
// Given a Token Transaction, a movement record is created for each enrollment ID that participated in the transaction
// and each token type that was transferred.
// The movement record contains the total amount of the token type that was transferred to/from the enrollment ID
// in a given token transaction.
type MovementRecord = dbdriver.MovementRecord
// ValidationRecord is a more finer-grained version of a movement record.
// Given a Token Transaction, for each token action in the Token Request,
// a transaction record is created for each unique enrollment ID found in the outputs.
// The transaction record contains the total amount of the token type that was transferred to/from that enrollment ID
// in that action.
type ValidationRecord = dbdriver.ValidationRecord
// TransactionIterator is an iterator over transaction records
type TransactionIterator struct {
it dbdriver.TransactionIterator
}
// Close closes the iterator. It must be called when done with the iterator.
func (t *TransactionIterator) Close() {
t.it.Close()
}
// Next returns the next transaction record, if any.
// It returns nil, nil if there are no more records.
func (t *TransactionIterator) Next() (*TransactionRecord, error) {
next, err := t.it.Next()
if err != nil {
return nil, err
}
if next == nil {
return nil, nil
}
return next, nil
}
// ValidationRecordsIterator is an iterator over validation records
type ValidationRecordsIterator struct {
it dbdriver.ValidationRecordsIterator
}
// Close closes the iterator. It must be called when done with the iterator.
func (t *ValidationRecordsIterator) Close() {
t.it.Close()
}
// Next returns the next validation record, if any.
// It returns nil, nil if there are no more records.
func (t *ValidationRecordsIterator) Next() (*ValidationRecord, error) {
next, err := t.it.Next()
if err != nil {
return nil, err
}
if next == nil {
return nil, nil
}
return next, nil
}
// Wallet models a wallet
type Wallet interface {
// ID returns the wallet ID
ID() string
// TMS returns the TMS of the wallet
TMS() *token.ManagementService
}
type Cache interface {
Get(key string) ([]byte, bool)
Add(key string, value []byte)
Delete(key string)
}
// StoreService is a database that stores token transactions related information
type StoreService struct {
*common.StatusSupport
db dbdriver.TokenTransactionStore
}
func newStoreService(p dbdriver.TokenTransactionStore) (*StoreService, error) {
return &StoreService{
StatusSupport: common.NewStatusSupport(),
db: p,
}, nil
}
// QueryTransactionsParams defines the parameters for querying movements
type QueryTransactionsParams = dbdriver.QueryTransactionsParams
// QueryTokenRequestsParams defines the parameters for querying token requests
type QueryTokenRequestsParams = dbdriver.QueryTokenRequestsParams
// QueryValidationRecordsParams defines the parameters for querying movements
type QueryValidationRecordsParams = dbdriver.QueryValidationRecordsParams
// Pagination defines the pagination for querying movements
type Pagination = cdriver.Pagination
// PageTransactionsIterator iterator defines the pagination iterator for movements query results
type PageTransactionsIterator = cdriver.PageIterator[*TransactionRecord]
// Transactions returns an iterators of transaction records filtered by the given params.
func (d *StoreService) Transactions(ctx context.Context, params QueryTransactionsParams, pagination Pagination) (*PageTransactionsIterator, error) {
return d.db.QueryTransactions(ctx, params, pagination)
}
// TokenRequests returns an iterator over the token requests matching the passed params
func (d *StoreService) TokenRequests(ctx context.Context, params QueryTokenRequestsParams) (dbdriver.TokenRequestIterator, error) {
return d.db.QueryTokenRequests(ctx, params)
}
// ValidationRecords returns an iterators of validation records filtered by the given params.
func (d *StoreService) ValidationRecords(ctx context.Context, params QueryValidationRecordsParams) (*ValidationRecordsIterator, error) {
it, err := d.db.QueryValidations(ctx, params)
if err != nil {
return nil, errors.Errorf("failed to query validation records: %s", err)
}
return &ValidationRecordsIterator{it: it}, nil
}
// AppendTransactionRecord appends the transaction records corresponding to the passed token request.
func (d *StoreService) AppendTransactionRecord(ctx context.Context, req *token.Request) error {
logger.DebugfContext(ctx, "appending new transaction record... [%s]", req.Anchor)
ins, outs, attrs, err := req.InputsAndOutputs(ctx)
if err != nil {
return errors.WithMessagef(err, "failed getting inputs and outputs for request [%s]", req.Anchor)
}
record := &token.AuditRecord{
Anchor: req.Anchor,
Inputs: ins,
Outputs: outs,
Attributes: attrs,
}
raw, err := req.Bytes()
if err != nil {
return errors.Wrapf(err, "failed to marshal token request [%s]", req.Anchor)
}
txs, err := TransactionRecords(ctx, record, time.Now().UTC())
if err != nil {
return errors.WithMessagef(err, "failed parsing transactions from audit record")
}
logger.DebugfContext(ctx, "storing new records... [%d,%d]", len(raw), len(txs))
w, err := d.db.BeginAtomicWrite()
if err != nil {
return errors.WithMessagef(err, "begin update for txid [%s] failed", record.Anchor)
}
anchor := string(record.Anchor)
if err := w.AddTokenRequest(
ctx,
anchor,
raw,
req.AllApplicationMetadata(),
record.Attributes,
req.PublicParamsHash(),
); err != nil {
w.Rollback()
return errors.WithMessagef(err, "append token request for txid [%s] failed", record.Anchor)
}
for _, tx := range txs {
if err := w.AddTransaction(ctx, tx); err != nil {
w.Rollback()
return errors.WithMessagef(err, "append transactions for txid [%s] failed", record.Anchor)
}
}
if err := w.Commit(); err != nil {
return errors.WithMessagef(err, "committing tx for txid [%s] failed", record.Anchor)
}
logger.DebugfContext(ctx, "appending transaction record new completed without errors")
return nil
}
// SetStatus sets the status of the audit records with the passed transaction id to the passed status
func (d *StoreService) SetStatus(ctx context.Context, txID string, status dbdriver.TxStatus, message string) error {
logger.DebugfContext(ctx, "set status [%s][%s]...", txID, status)
if err := d.db.SetStatus(ctx, txID, status, message); err != nil {
return errors.Wrapf(err, "failed setting status [%s][%s]", txID, dbdriver.TxStatusMessage[status])
}
// notify the listeners
d.Notify(common.StatusEvent{
Ctx: ctx,
TxID: txID,
ValidationCode: status,
})
logger.DebugfContext(ctx, "set status [%s][%s] done", txID, dbdriver.TxStatusMessage[status])
return nil
}
// GetStatus return the status of the given transaction id.
// It returns an error if no transaction with that id is found
func (d *StoreService) GetStatus(ctx context.Context, txID string) (TxStatus, string, error) {
logger.DebugfContext(ctx, "get status [%s]...", txID)
status, message, err := d.db.GetStatus(ctx, txID)
if err != nil {
return Unknown, "", errors.Wrapf(err, "failed getting status [%s]", txID)
}
logger.DebugfContext(ctx, "got status [%s][%s]", txID, status)
return status, message, nil
}
// GetTokenRequest returns the token request bound to the passed transaction id, if available.
func (d *StoreService) GetTokenRequest(ctx context.Context, txID string) ([]byte, error) {
return d.db.GetTokenRequest(ctx, txID)
}
// AddTransactionEndorsementAck records the signature of a given endorser for a given transaction
func (d *StoreService) AddTransactionEndorsementAck(ctx context.Context, txID string, id token.Identity, sigma []byte) error {
return d.db.AddTransactionEndorsementAck(ctx, txID, id, sigma)
}
// GetTransactionEndorsementAcks returns the endorsement signatures for the given transaction id
func (d *StoreService) GetTransactionEndorsementAcks(ctx context.Context, txID string) (map[string][]byte, error) {
return d.db.GetTransactionEndorsementAcks(ctx, txID)
}
// AppendValidationRecord appends the given validation metadata related to the given transaction id
func (d *StoreService) AppendValidationRecord(ctx context.Context, txID string, tokenRequest []byte, meta map[string][]byte, ppHash driver2.PPHash) error {
logger.DebugfContext(ctx, "appending new validation record... [%s]", txID)
w, err := d.db.BeginAtomicWrite()
if err != nil {
return errors.WithMessagef(err, "begin update for txid [%s] failed", txID)
}
// we store the token request, but don't have or care about the application metadata
if err := w.AddTokenRequest(ctx, txID, tokenRequest, nil, nil, ppHash); err != nil {
w.Rollback()
return errors.WithMessagef(err, "append token request for txid [%s] failed", txID)
}
if err := w.AddValidationRecord(ctx, txID, meta); err != nil {
w.Rollback()
return errors.WithMessagef(err, "append validation record for txid [%s] failed", txID)
}
if err := w.Commit(); err != nil {
return errors.WithMessagef(err, "append validation record commit for txid [%s] failed", txID)
}
logger.DebugfContext(ctx, "appending validation record completed without errors")
return nil
}
// TransactionRecords is a pure function that converts an AuditRecord for storage in the database.
func TransactionRecords(ctx context.Context, record *token.AuditRecord, timestamp time.Time) (txs []TransactionRecord, err error) {
inputs := record.Inputs
outputs := record.Outputs
actionIndex := 0
for {
// collect inputs and outputs from the same action
ins := inputs.Filter(func(t *token.Input) bool {
return t.ActionIndex == actionIndex
})
ous := outputs.Filter(func(t *token.Output) bool {
return t.ActionIndex == actionIndex
})
if ins.Count() == 0 && ous.Count() == 0 {
logger.DebugfContext(ctx, "no actions left for tx [%s][%d]", record.Anchor, actionIndex)
break
}
// create a transaction record from ins and ous
// All ins should be for same EID, check this
inEIDs := ins.EnrollmentIDs()
if len(inEIDs) > 1 {
return nil, errors.Errorf("expected at most 1 input enrollment id, got %d, [%v]", len(inEIDs), inEIDs)
}
inEID := ""
if len(inEIDs) == 1 {
inEID = inEIDs[0]
}
outEIDs := ous.EnrollmentIDs()
outEIDs = append(outEIDs, "")
outTT := ous.TokenTypes()
for _, outEID := range outEIDs {
for _, tokenType := range outTT {
received := ous.ByEnrollmentID(outEID).ByType(tokenType).Sum()
if received.Cmp(big.NewInt(0)) <= 0 {
continue
}
tt := dbdriver.Issue
if len(inEIDs) != 0 {
if len(outEID) == 0 {
tt = dbdriver.Redeem
} else {
tt = dbdriver.Transfer
}
}
txs = append(txs, dbdriver.TransactionRecord{
TxID: string(record.Anchor),
SenderEID: inEID,
RecipientEID: outEID,
TokenType: tokenType,
Amount: received,
Status: dbdriver.Pending,
ActionType: tt,
Timestamp: timestamp,
})
}
}
actionIndex++
}
logger.DebugfContext(ctx, "parsed transactions for tx [%s]", record.Anchor)
return txs, err
}
// Movements converts an AuditRecord to MovementRecords for storage in the database.
// A positive movement Amount means incoming tokens, and negative means outgoing tokens from the enrollment ID.
func Movements(ctx context.Context, record *token.AuditRecord, created time.Time) (mv []MovementRecord, err error) {
inputs := record.Inputs
outputs := record.Outputs
// we need to consider both inputs and outputs enrollment IDs because the record can refer to a redeem
eIDs := joinIOEIDs(record)
logger.DebugfContext(ctx, "eIDs [%v]", eIDs)
tokenTypes := outputs.TokenTypes()
for _, eID := range eIDs {
for _, tokenType := range tokenTypes {
received := outputs.ByEnrollmentID(eID).ByType(tokenType).Sum()
sent := inputs.ByEnrollmentID(eID).ByType(tokenType).Sum()
diff := received.Sub(received, sent)
if sent == received {
continue
}
logger.DebugfContext(ctx, "adding movement [%s:%d]", eID, diff.Int64())
mv = append(mv, dbdriver.MovementRecord{
TxID: string(record.Anchor),
EnrollmentID: eID,
Amount: diff,
TokenType: tokenType,
Timestamp: created,
Status: dbdriver.Pending,
})
}
}
logger.DebugfContext(ctx, "finished to parse sent movements for tx [%s]", record.Anchor)
return mv, err
}
// joinIOEIDs joins enrollment IDs of inputs and outputs
func joinIOEIDs(record *token.AuditRecord) []string {
iEIDs := record.Inputs.EnrollmentIDs()
oEIDs := record.Outputs.EnrollmentIDs()
eIDs := append(iEIDs, oEIDs...)
eIDs = deduplicate(eIDs)
return eIDs
}
// deduplicate removes duplicate entries from a slice
func deduplicate(source []string) []string {
support := make(map[string]bool)
var res []string
for _, item := range source {
if _, value := support[item]; !value {
support[item] = true
res = append(res, item)
}
}
return res
}