forked from hyperledger/fabric
/
table_api.go
484 lines (402 loc) · 16.9 KB
/
table_api.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/******************************************************************
Copyright IT People Corp. 2017 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************/
///////////////////////////////////////////////////////////////////////
// Author : IT People - Mohan Venkataraman - table API for v1.0
// Purpose: Explore the Hyperledger/fabric and understand
// how to write an chain code, application/chain code boundaries
// The code is not the best as it has just hammered out in a day or two
// Feedback and updates are appreciated
///////////////////////////////////////////////////////////////////////
package main
import (
"bytes"
"errors"
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
//////////////////////////////////////////////////////////////////////////////////////////////////
// The recType is a mandatory attribute. The original app was written with a single table
// in mind. The only way to know how to process a record was the 70's style 80 column punch card
// which used a record type field. The array below holds a list of valid record types.
// This could be stored on a blockchain table or an application
//////////////////////////////////////////////////////////////////////////////////////////////////
var recType = []string{"ARTINV", "USER", "BID", "AUCREQ", "POSTTRAN", "OPENAUC", "CLAUC", "XFER", "VERIFY", "DOWNLOAD"}
//////////////////////////////////////////////////////////////////////////////////////////////////
// The following array holds the list of tables that should be created
// The deploy/init deletes the tables and recreates them every time a deploy is invoked
//////////////////////////////////////////////////////////////////////////////////////////////////
var Objects = []string{"PARTY", "CASHTXN", "User", "UserCat", "Item", "ItemCat", "ItemHistory", "Auction", "AucInit", "AucOpen", "Bid", "Trans"}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// A Map that holds ObjectNames and the number of Keys
// This information is used to dynamically Create, Update
// Replace , and Query the Ledger
// In this model all attributes in a table are strings
// The chain code does both validation
// A dummy key like 2016 in some cases is used for a query to get all rows
//
// "User": 1, Key: UserID
// "Item": 1, Key: ItemID
// "UserCat": 3, Key: "2016", UserType, UserID
// "ItemCat": 3, Key: "2016", ItemSubject, ItemID
// "Auction": 1, Key: AuctionID
// "AucInit": 2, Key: Year, AuctionID
// "AucOpen": 2, Key: Year, AuctionID
// "Trans": 2, Key: AuctionID, ItemID
// "Bid": 2, Key: AuctionID, BidNo
// "ItemHistory": 4, Key: ItemID, Status, AuctionHouseID(if applicable),date-time
//
// The additional key is the ObjectType (aka ObjectName or Object). The keys would be
// keys: {"User", UserId} or keys: {"AuctInit", "2016", "1134"}
/////////////////////////////////////////////////////////////////////////////////////////////////////
func GetNumberOfKeys(tname string) int {
ObjectMap := map[string]int{
"User": 1,
"Item": 1,
"UserCat": 3,
"ItemCat": 3,
"Auction": 1,
"AucInit": 2,
"AucOpen": 2,
"Trans": 2,
"Bid": 2,
"ItemHistory": 4,
"PARTY": 2,
"CASHTXN": 1,
}
return ObjectMap[tname]
}
/////////////////////////////////////////////////////////////////
// This function checks the incoming args for a valid record
// type entry as per the declared array recType[]
// The rectType attribute can be anywhere in the args or struct
// not necessarily in args[1] as per my old logic
// The Request type is used to direct processing
// the record accordingly e: recType is "USER"
// "Args":["PostUser","100", "USER", "Ashley Hart", "TRD", "Morrisville Parkway, #216, Morrisville, NC 27560",
// "9198063535", "ashley@it people.com", "SUNTRUST", "0001732345", "0234678", "2017-01-02 15:04:05"]}'
/////////////////////////////////////////////////////////////////
func ChkRecType(args []string) bool {
for _, rt := range args {
for _, val := range recType {
if val == rt {
return true
}
}
}
return false
}
/////////////////////////////////////////////////////////////////
// Checks if the incoming invoke has a valid requesType
// The Request type is used to process the record accordingly
// Old Logic (see new logic up)
/////////////////////////////////////////////////////////////////
func CheckRecType(rt string) bool {
for _, val := range recType {
if val == rt {
fmt.Println("CheckRequestType() : Valid Request Type , val : ", val, rt, "\n")
return true
}
}
fmt.Println("CheckRequestType() : Invalid Request Type , val : ", rt, "\n")
return false
}
/////////////////////////////////////////////////////////////////
// Checks if the args contain a valid Record Type. Typically, this
// model expects the Object Type to be args[2] but
// for the sake of flexibility, it scans the input data for
// a valid type if available
/////////////////////////////////////////////////////////////////
func IdentifyRecType(args []string) (string, error) {
for _, rt := range args {
for _, val := range recType {
if val == rt {
return rt, nil
}
}
}
return "", fmt.Errorf("IdentifyRecType: Not Found")
}
/////////////////////////////////////////////////////////////////
// Checks if the args contain a valid Object Type. Typically, this
// model expects the Object Type to be args[0] but
// for the sake of flexibility, it scans the input data for
// a valid type if available
/////////////////////////////////////////////////////////////////
func IdentifyObjectType(args []string) (string, error) {
for _, rt := range args {
for _, val := range Objects {
if val == rt {
return rt, nil
}
}
}
return "", fmt.Errorf("IdentifyObjectType: Object Not Found")
}
////////////////////////////////////////////////////////////////////////////
// Open a Ledgers if one does not exist
// These ledgers will be used to write / read data
////////////////////////////////////////////////////////////////////////////
func InitObject(stub shim.ChaincodeStubInterface, objectType string, keys []string) error {
fmt.Println(">> Not Implemented Yet << Initializing Object : ", objectType, " Keys: ", keys)
return nil
}
////////////////////////////////////////////////////////////////////////////
// Update the Object - Replace current data with replacement
// Register users into this table
////////////////////////////////////////////////////////////////////////////
func UpdateObject(stub shim.ChaincodeStubInterface, objectType string, keys []string, objectData []byte) error {
// Check how many keys
err := VerifyAtLeastOneKeyIsPresent(objectType, keys)
if err != nil {
return err
}
// Convert keys to compound key
compositeKey, _ := stub.CreateCompositeKey(objectType, keys)
// Add Object JSON to state
err = stub.PutState(compositeKey, objectData)
if err != nil {
fmt.Println("UpdateObject() : Error inserting Object into State Database %s", err)
return err
}
return nil
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Retrieve the object based on the key and simply delete it
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
func DeleteObject(stub shim.ChaincodeStubInterface, objectType string, keys []string) error {
// Check how many keys
err := VerifyAtLeastOneKeyIsPresent(objectType, keys)
if err != nil {
return err
}
// Convert keys to compound key
compositeKey, _ := stub.CreateCompositeKey(objectType, keys)
// Remove object from the State Database
err = stub.DelState(compositeKey)
if err != nil {
fmt.Println("DeleteObject() : Error deleting Object into State Database %s", err)
return err
}
fmt.Println("DeleteObject() : ", "Object : ", objectType, " Key : ", compositeKey)
return nil
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Delete all objects of ObjectType
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
func DeleteAllObjects(stub shim.ChaincodeStubInterface, objectType string) error {
// Convert keys to compound key
compositeKey, _ := stub.CreateCompositeKey(objectType, []string{""})
// Remove object from the State Database
err := stub.DelState(compositeKey)
if err != nil {
fmt.Println("DeleteAllObjects() : Error deleting all Object into State Database %s", err)
return err
}
fmt.Println("DeleteObject() : ", "Object : ", objectType, " Key : ", compositeKey)
return nil
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Replaces the Entry in the Ledger
// The existing object is simply queried and the data contents is replaced with
// new content
////////////////////////////////////////////////////////////////////////////////////////////////////////////
func ReplaceObject(stub shim.ChaincodeStubInterface, objectType string, keys []string, objectData []byte) error {
// Check how many keys
err := VerifyAtLeastOneKeyIsPresent(objectType, keys)
if err != nil {
return err
}
// Convert keys to compound key
compositeKey, _ := stub.CreateCompositeKey(objectType, keys)
// Add Party JSON to state
err = stub.PutState(compositeKey, objectData)
if err != nil {
fmt.Println("ReplaceObject() : Error replacing Object in State Database %s", err)
return err
}
fmt.Println("ReplaceObject() : - end init object ", objectType)
return nil
}
////////////////////////////////////////////////////////////////////////////
// Query a User Object by Object Name and Key
// This has to be a full key and should return only one unique object
////////////////////////////////////////////////////////////////////////////
func QueryObject(stub shim.ChaincodeStubInterface, objectType string, keys []string) ([]byte, error) {
// Check how many keys
err := VerifyAtLeastOneKeyIsPresent(objectType, keys)
if err != nil {
return nil, err
}
compoundKey, _ := stub.CreateCompositeKey(objectType, keys)
fmt.Println("QueryObject() : Compound Key : ", compoundKey)
Avalbytes, err := stub.GetState(compoundKey)
if err != nil {
return nil, err
}
return Avalbytes, nil
}
////////////////////////////////////////////////////////////////////////////
// Query a User Object by Object Name and Key
// This has to be a full key and should return only one unique object
////////////////////////////////////////////////////////////////////////////
func QueryObjectWithProcessingFunction(stub shim.ChaincodeStubInterface, objectType string, keys []string, fname func(shim.ChaincodeStubInterface, []byte, []string) error) ([]byte, error) {
// Check how many keys
err := VerifyAtLeastOneKeyIsPresent(objectType, keys)
if err != nil {
return nil, err
}
compoundKey, _ := stub.CreateCompositeKey(objectType, keys)
fmt.Println("QueryObject: Compound Key : ", compoundKey)
Avalbytes, err := stub.GetState(compoundKey)
if err != nil {
return nil, err
}
if Avalbytes == nil {
return nil, fmt.Errorf("QueryObject: No Data Found for Compound Key : ", compoundKey)
}
// Perform Any additional processing of data
fmt.Println("fname() : Successful - Proceeding to fname")
err = fname(stub, Avalbytes, keys)
if err != nil {
fmt.Println("QueryLedger() : Cannot execute : ", fname)
jsonResp := "{\"fname() Error\":\" Cannot create Object for key " + compoundKey + "\"}"
return Avalbytes, errors.New(jsonResp)
}
return Avalbytes, nil
}
////////////////////////////////////////////////////////////////////////////
// Get a List of Rows based on query criteria from the OBC
// The getList Function
////////////////////////////////////////////////////////////////////////////
func GetKeyList(stub shim.ChaincodeStubInterface, args []string) (shim.StateQueryIteratorInterface, error) {
// Define partial key to query within objects namespace (objectType)
objectType := args[0]
// Check how many keys
err := VerifyAtLeastOneKeyIsPresent(objectType, args[1:])
if err != nil {
return nil, err
}
// Execute the Query
// This will execute a key range query on all keys starting with the compound key
resultsIterator, err := stub.GetStateByPartialCompositeKey(objectType, args[1:])
if err != nil {
return nil, err
}
defer resultsIterator.Close()
// Iterate through result set
var i int
for i = 0; resultsIterator.HasNext(); i++ {
// Retrieve the Key and Object
myCompositeKey, err := resultsIterator.Next()
if err != nil {
return nil, err
}
fmt.Println("GetList() : my Value : ", myCompositeKey)
}
return resultsIterator, nil
}
///////////////////////////////////////////////////////////////////////////////////////////
// GetQueryResultForQueryString executes the passed in query string.
// Result set is built and returned as a byte array containing the JSON results.
///////////////////////////////////////////////////////////////////////////////////////////
func GetQueryResultForQueryString(stub shim.ChaincodeStubInterface, queryString string) ([]byte, error) {
fmt.Println("GetQueryResultForQueryString() : getQueryResultForQueryString queryString:\n%s\n", queryString)
resultsIterator, err := stub.GetQueryResult(queryString)
if err != nil {
return nil, err
}
defer resultsIterator.Close()
// buffer is a JSON array containing QueryRecords
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return nil, err
}
// Add a comma before array members, suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",")
}
buffer.WriteString("{\"Key\":")
buffer.WriteString("\"")
buffer.WriteString(queryResponse.Key)
buffer.WriteString("\"")
buffer.WriteString(", \"Record\":")
// Record is a JSON object, so we write as-is
buffer.WriteString(string(queryResponse.Value))
buffer.WriteString("}")
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
fmt.Println("GetQueryResultForQueryString(): getQueryResultForQueryString queryResult:\n%s\n", buffer.String())
return buffer.Bytes(), nil
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Retrieve a list of Objects from the Query
// The function returns an iterator from which objects can be retrieved.
// defer rs.Close()
//
// // Iterate through result set
// var i int
// for i = 0; rs.HasNext(); i++ {
//
// // We can process whichever return value is of interest
// myKey , myKeyVal , err := rs.Next()
// if err != nil {
// return shim.Success(nil)
// }
// bob, _ := JSONtoUser(myKeyVal)
// fmt.Println("GetList() : my Value : ", bob)
// }
//
// eg: Args":["fetchlist", "PARTY","CHK"]}
// fetchList is the function that calls getList : ObjectType = "Party" and key is "CHK"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func GetList(stub shim.ChaincodeStubInterface, objectType string, keys []string) (shim.StateQueryIteratorInterface, error) {
// Check how many keys
err := VerifyAtLeastOneKeyIsPresent(objectType, keys)
if err != nil {
return nil, err
}
// Get Result set
resultIter, err := stub.GetStateByPartialCompositeKey(objectType, keys)
fmt.Println("GetList(): Retrieving Objects into an array")
if err != nil {
return nil, err
}
// Return iterator for result set
// Use code above to retrieve objects
return resultIter, nil
}
////////////////////////////////////////////////////////////////////////////
// This function verifies if the number of key provided is at least 1 and
// < the max keys defined for the Object
////////////////////////////////////////////////////////////////////////////
func VerifyAtLeastOneKeyIsPresent(objectType string, args []string) error {
// Check how many keys
nKeys := GetNumberOfKeys(objectType)
nCol := len(args)
if nCol == 1 {
return nil
}
if nCol < 1 {
error_str := fmt.Sprintf("VerifyAtLeastOneKeyIsPresent() Failed: Atleast 1 Key must is needed : nKeys : %s, nCol : %s ", nKeys, nCol)
fmt.Println(error_str)
return errors.New(error_str)
}
return nil
}