-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchaincode.go
467 lines (397 loc) · 14.2 KB
/
chaincode.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
/*
* SPDX-License-Identifier: Apache-2.0
*/
/*
alteração no arquivo vendor/gonum.org/v1/gonum/floats/scalar/scalar.go
//const minNormalFloat64 = 0x1.P-1022
const minNormalFloat64 = 2.2250738585072014e-308
alteração no arquivo vendor/gonum.org/v1/gonum/lapack/gonum/lapack.go
//dlamchE = 0x1p-53
dlamchE = 1.1102230246251565e-16
//dlamchS = 0x1p-1022
dlamchS = 2.2250738585072014e-308
*/
package main
import (
"bytes"
"encoding/json"
"fmt"
"math"
"strconv"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/eriksonJAguiar/godiffpriv"
"github.com/hyperledger/fabric/core/chaincode/shim"
sc "github.com/hyperledger/fabric/protos/peer"
)
// Chaincode is the definition of the chaincode structure.
type Chaincode struct {
}
type Record struct {
LastName string `json:"lastname"`
FirstName string `json:"first_name"`
NationalProviderId string `json:"national_provider_id"`
LicenseNumber string `json:"license_number"`
MedicalProviderId string `json:"medical_provider_id"`
ManagedCarePlansId string `json:"managed_care_plans_id"`
PrimaryDesignation string `json:"primary_designation"`
ProviderType string `json:"provider_type"`
}
type DataArray struct {
numeric []float64
symbolic []string
maxValue float64
minValue float64
onlyNumbers bool
}
// Init is called when the chaincode is instantiated by the blockchain network.
func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {
fcn, params := stub.GetFunctionAndParameters()
fmt.Println("Init()", fcn, params)
return shim.Success(nil)
}
// Invoke is called as a result of an application request to run the chaincode.
func (cc *Chaincode) Invoke(stub shim.ChaincodeStubInterface) sc.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := stub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger appropriately
if function == "createRecord" {
return cc.createRecord(stub, args)
} else if function == "queryAllRecords" {
return cc.queryAllRecords(stub)
} else if function == "queryTeste" {
return cc.queryTeste(stub, args)
} else if function == "createRecordTeste" {
return cc.createRecordTeste(stub, args)
} else if function == "executeCommand" {
return cc.executeCommand(stub, args)
}
return shim.Error("Invalid Smart Contract function name.")
}
func constructQueryResponseFromIterator(resultsIterator shim.StateQueryIteratorInterface) (*bytes.Buffer, error) {
// buffer is a JSON array containing QueryResults
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("\n{\"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("]")
return &buffer, nil
}
//
//{\"selector\":{\"first_name\":\"134\"}}
func (cc *Chaincode) queryTeste(stub shim.ChaincodeStubInterface, args []string) sc.Response {
resultsIterator, err := stub.GetQueryResult(args[0])
// s := "{\"selector\":{\"lastname\":\"134\"}}"
// resultsIterator, err := stub.GetQueryResult(s)
if err != nil {
return shim.Error("Error doing GetQueryResult1:" + err.Error())
}
defer resultsIterator.Close()
buffer, err := constructQueryResponseFromIterator(resultsIterator)
if err != nil {
return shim.Error("Error doing GetQueryResult2")
}
fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
}
func (cc *Chaincode) createRecord(stub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 9 {
return shim.Error("Incorrect number of arguments. Expecting 9")
}
var rec = Record{
LastName: args[1],
FirstName: args[2],
NationalProviderId: args[3],
LicenseNumber: args[4],
MedicalProviderId: args[5],
ManagedCarePlansId: args[6],
PrimaryDesignation: args[7],
ProviderType: args[8],
}
recAsBytes, _ := json.Marshal(rec)
stub.PutState(args[0], recAsBytes)
return shim.Success(nil)
}
func (cc *Chaincode) createRecordTeste(stub shim.ChaincodeStubInterface, args []string) sc.Response {
s := "{\"lastname\":\"134\"}"
//recAsBytes, _ := json.Marshal(args[1])
/// recAsBytes, _ := json.Marshal(s)
err := stub.PutState(args[0], []byte(s))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
func (cc *Chaincode) queryAllRecords(stub shim.ChaincodeStubInterface) sc.Response {
startKey := "key0"
endKey := "key999"
resultsIterator, err := stub.GetStateByRange(startKey, endKey)
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
// buffer is a JSON array containing QueryResults
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// Add a comma before array members, suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",\n")
}
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.Printf("- queryAllRecords:\n%s\n", buffer.String())
antlr.NewInputStream("d")
return shim.Success(buffer.Bytes())
}
func (cc *Chaincode) executeCommand(stub shim.ChaincodeStubInterface, args []string) sc.Response {
is := antlr.NewInputStream(args[0])
// Create the Lexer
lexer := NewTranslatorLexer(is)
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
// Create the Parser
p := NewTranslatorParser(stream)
var listener translatorListener
// Finally parse the expression
antlr.ParseTreeWalkerDefault.Walk(&listener, p.Start())
// insert command
if len(listener.insertString) != 0 {
if len(args) != 2 {
return shim.Error("Wrong number of arguments.")
}
err := stub.PutState(args[1], []byte(listener.insertString))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
} else if len(listener.queryString) != 0 {
// select command
return cc.queryCommand(stub, listener)
/*resultsIterator, err := stub.GetQueryResult(listener.queryString)
// s := "{\"selector\":{\"lastname\":\"134\"}}"
// resultsIterator, err := stub.GetQueryResult(s)
if err != nil {
return shim.Error("Error doing GetQueryResult1:" + err.Error())
}
defer resultsIterator.Close()
buffer, err := constructQueryResponseFromIterator(resultsIterator)
if err != nil {
return shim.Error("Error doing GetQueryResult2")
}
fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
*/
} else {
return shim.Error("Unable to parse the string.")
}
}
// INSERT INTO doctype2 (coluna1, coluna2, coluna3) VALUES (\"123\",\"432\",\"1111\")
// INSERT INTO doctype3 (coluna1, coluna2, coluna3) VALUES (\"123\",\"321\",\"321\")
// INSERT INTO doctype3 (coluna1, coluna2, coluna3) VALUES (\"123\",\"654\",\"654\")
// INSERT INTO doctype3 (coluna1, coluna2, coluna3) VALUES (\"valor1\",\"valor2\",\"valor3\")
// INSERT INTO doctype3 (coluna1, coluna2, coluna3) VALUES (\"3333\",\"3333\",\"3333\")
// INSERT INTO doctype3 (coluna1, coluna2, coluna3) VALUES (\"2222\",\"2222\",\"2222\")
// SELECT AVG(coluna2) FROM doctype2 WHERE coluna1=\"123\"
// SELECT AVG(coluna2), AVG(coluna1), HISTOGRAM(coluna3) FROM doctype3 WHERE coluna1=\"123\"
// SELECT AVG(coluna2) FROM doctype2 WHERE coluna1="123"
// SELECT AVG(coluna2), AVG(coluna1), HISTOGRAM(coluna3) FROM doctype3 WHERE coluna1=\"123\" EPSILON=0.3
func (cc *Chaincode) queryCommand(stub shim.ChaincodeStubInterface, listener translatorListener) sc.Response {
resultsIterator, err := stub.GetQueryResult(listener.queryString)
if err != nil {
return shim.Error("Error doing GetQueryResult1:" + err.Error())
}
var buffer bytes.Buffer
// create an array with the data for each attribute
var data []DataArray = cc.prepareData(listener, resultsIterator)
if len(data[0].numeric) == 0 && len(data[0].symbolic) == 0 {
buffer.WriteString("Empty Result")
return shim.Success(buffer.Bytes())
}
// get all the data from the database
var alldata []DataArray = cc.getAllData(stub, listener)
// iterate the attributes applying the diff priv
for i, attribute := range listener.attributes {
var auxData interface{}
if listener.functions[i] == "AVG" {
// concatenate the queried data with all the data
alldata[i].numeric = append(alldata[i].numeric, data[i].numeric...)
auxData = alldata[i].numeric
} else { // if function == HISTOGRAM
// if sturges method must be applied
if data[i].onlyNumbers == true {
alldata[i].numeric = append(alldata[i].numeric, data[i].numeric...)
alldata[i].applySturgesRule()
} else {
alldata[i].symbolic = append(alldata[i].symbolic, data[i].symbolic...)
}
auxData = alldata[i].symbolic
}
val := godiffpriv.PrivateDataFactory(auxData)
buffer.WriteString("\n" + attribute)
var epsilon float64
// if epsilon was defined in the query command
if len(listener.epsilon) != 0 {
f, err := strconv.ParseFloat(listener.epsilon, 64)
if err != nil {
panic(1)
}
if f > 1 || f < 0 {
panic(1)
}
epsilon = f
} else {
epsilon = 1.0
}
res, _ := val.ApplyPrivacy(epsilon)
var response map[string]float64
err = json.Unmarshal(res, &response)
if err != nil {
fmt.Println(err.Error())
} else {
// s := strconv.FormatFloat(response["data"], 'f', 6, 64)
buffer.WriteString("\nresponse ")
s := fmt.Sprintf("%v", response)
buffer.WriteString(s)
}
}
return shim.Success(buffer.Bytes())
}
// apply sturges rule on DataArray.numeric insertin the generalized data on DataArray.symbolic
func (d *DataArray) applySturgesRule() {
d.symbolic = make([]string, 0, len(d.numeric))
// if d.maxValue == d.minValue {
// panic(1)
// }
N := len(d.numeric)
k := 1 + math.Round(math.Log2(float64(N)))
delta := d.maxValue - d.minValue
a := delta / k
for _, value := range d.numeric {
var classIndex float64
if delta != 0 { // if all values are not the same
classIndex = (value - d.minValue) / a
classIndex = math.Floor(classIndex)
if classIndex == k { // maximum value doesnt fit to the formula
classIndex = k - 1
}
} else { // all values the same
classIndex = 0
}
d.symbolic = append(d.symbolic, strconv.FormatFloat(classIndex, 'f', 0, 64))
}
}
func (cc *Chaincode) getAllData(stub shim.ChaincodeStubInterface, listener translatorListener) []DataArray {
s := "{\"selector\":{\"docType\":\"" + listener.docType + "\"}}"
resultsIterator, err := stub.GetQueryResult(s)
if err != nil {
panic(1)
}
return cc.prepareData(listener, resultsIterator)
}
// transform the query result into an map
func (cc *Chaincode) prepareData(listener translatorListener, iterator shim.StateQueryIteratorInterface) []DataArray {
defer iterator.Close()
var data = make([]DataArray, len(listener.attributes))
// initialize structs
for i, _ := range listener.attributes {
data[i].onlyNumbers = true
}
maxMinFlag := true // flag to define first value as max and min
for iterator.HasNext() {
queryResponse, err := iterator.Next()
if err != nil {
panic(1)
}
var object map[string]string
err = json.Unmarshal(queryResponse.Value, &object)
if err != nil {
panic(1)
}
// iterate through each attribute queried
for i, attribute := range listener.attributes {
// check if there is the attribute in the current row
if _, found := object[attribute]; !found {
panic(1)
}
// if the function is 'average', only numbers are allowed
if listener.functions[i] == "AVG" {
f, err := strconv.ParseFloat(object[attribute], 64)
if err != nil {
panic(1)
}
data[i].numeric = append(data[i].numeric, f)
// if the function is 'histogram', it can be symbolic data or only numeric data
} else if listener.functions[i] == "HISTOGRAM" {
data[i].symbolic = append(data[i].symbolic, object[attribute])
// verify if the data still only has numbers then append the numeric array
if data[i].onlyNumbers == true {
f, err := strconv.ParseFloat(object[attribute], 64)
if err != nil {
data[i].onlyNumbers = false // stop appending the numeric array
} else {
data[i].numeric = append(data[i].numeric, f)
// set max and min values
if maxMinFlag { // if we are in first row
data[i].maxValue = f
data[i].minValue = f
maxMinFlag = false
} else {
if data[i].maxValue < f {
data[i].maxValue = f
} else if data[i].minValue > f {
data[i].minValue = f
}
}
}
}
}
}
}
return data
}
/*
"key16",
"134",
"FirstName",
"NationalProviderId",
"LicenseNumber",
"MedicalProviderId",
"ManagedCarePlansId",
"PrimaryDesignation",
"ProviderType"
`{lastname:"134",first_name:134,national_provider_id:'134',license_number:'134',medical_provider_id:'134',managed_care_plans_id:'134',primary_designation:'134',provider_type:'134'}`
{adf:'3dd'}
{"selector":{"docType":"marble"}
Error upgrading smart contract: error starting container: error starting container: Failed to generate platform-specific docker build: Error returned from build: 1 "chaincode/input/src/newproj2/chaincode.go:13:2: cannot find package "github.com/eriksonJAguiar/DP-Tool-blockchain/parser" in any of: /chaincode/input/src/newproj2/vendor/github.com/eriksonJAguiar/DP-Tool-blockchain/parser (vendor tree) /opt/go/src/github.com/eriksonJAguiar/DP-Tool-blockchain/parser (from $GOROOT) /chaincode/input/src/github.com/eriksonJAguiar/DP-Tool-blockchain/parser (from $GOPATH) /opt/gopath/src/github.com/eriksonJAguiar/DP-Tool-blockchain/parser "
*/