forked from IBM/securitization_blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_ledger.go
335 lines (302 loc) · 10.7 KB
/
read_ledger.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
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
package main
import (
// "bytes"
"encoding/json"
"fmt"
// "reflect"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
// ============================================================================================================================
// Read - read a generic variable from ledger
//
// Shows Off GetState() - reading a key/value from the ledger
//
// Inputs - Array of strings
// 0
// key
// "abc"
//
// Returns - string
// ============================================================================================================================
func read(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var key, jsonResp string
var err error
fmt.Println("starting read")
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting key of the var to query")
}
// input sanitation
err = sanitize_arguments(args)
if err != nil {
return shim.Error(err.Error())
}
key = args[0]
valAsbytes, err := stub.GetState(key) //get the var from ledger
if err != nil {
jsonResp = "{\"Error\":\"Failed to get state for " + key + "\"}"
return shim.Error(jsonResp)
}
fmt.Println("Object keys")
fmt.Println(string(valAsbytes))
// fmt.Printf("%+v\n", security.Investor)
fmt.Println("- end read")
return shim.Success(valAsbytes) //send it onward
}
// ============================================================================================================================
// Get everything we need (owners + marbles + companies)
//
// Inputs - none
//
// Returns:
// {
// "owners": [{
// "id": "o99999999",
// "company": "United Marbles"
// "username": "alice"
// }],
// "marbles": [{
// "id": "m1490898165086",
// "color": "white",
// "docType" :"marble",
// "owner": {
// "company": "United Marbles"
// "username": "alice"
// },
// "size" : 35
// }]
// }
// ============================================================================================================================
func read_everything(stub shim.ChaincodeStubInterface) pb.Response {
type Everything struct {
Originators []Originator `json:"originators"`
Assets []Asset `json:"assets"`
Pools []Pool `json:"pools"`
Securities []Security `json:"securities"`
Investors []Investor `json:"investors"`
}
var everything Everything
// ---- Get All Marbles ---- //
assetsIterator, err := stub.GetStateByRange("asset0", "asset9999999999999999999")
if err != nil {
return shim.Error(err.Error())
}
defer assetsIterator.Close()
for assetsIterator.HasNext() {
aKeyValue, err := assetsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// queryKeyAsStr := aKeyValue.Key
queryValAsBytes := aKeyValue.Value
// fmt.Println("on asset id - ", queryKeyAsStr)
var asset Asset
json.Unmarshal(queryValAsBytes, &asset) //un stringify it aka JSON.parse()
everything.Assets = append(everything.Assets, asset) //add this marble to the list
}
// fmt.Println("asset array - ", everything.Assets)
// ---- Get All Originators ---- //
originatorsIterator, err := stub.GetStateByRange("originator0", "originator9999999999999999999")
if err != nil {
return shim.Error(err.Error())
}
defer originatorsIterator.Close()
for originatorsIterator.HasNext() {
aKeyValue, err := originatorsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// queryKeyAsStr := aKeyValue.Key
queryValAsBytes := aKeyValue.Value
// fmt.Println("on originator id - ", queryKeyAsStr)
var originator Originator
json.Unmarshal(queryValAsBytes, &originator) //un stringify it aka JSON.parse()
everything.Originators = append(everything.Originators, originator) //add this marble to the list
}
// fmt.Println("originator array - ", everything.Originators)
// ---- Get All Pools ---- //
poolsIterator, err := stub.GetStateByRange("pool0", "pool9999999999999999999")
if err != nil {
return shim.Error(err.Error())
}
defer poolsIterator.Close()
for poolsIterator.HasNext() {
aKeyValue, err := poolsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// queryKeyAsStr := aKeyValue.Key
queryValAsBytes := aKeyValue.Value
// fmt.Println("on pool id - ", queryKeyAsStr)
var pool Pool
json.Unmarshal(queryValAsBytes, &pool) //un stringify it aka JSON.parse()
everything.Pools = append(everything.Pools, pool) //add this marble to the list
}
// fmt.Println("pool array - ", everything.Pools)
// ---- Get All Securities ---- //
securitiesIterator, err := stub.GetStateByRange("security0", "security9999999999999999999")
if err != nil {
return shim.Error(err.Error())
}
defer securitiesIterator.Close()
for securitiesIterator.HasNext() {
aKeyValue, err := securitiesIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// queryKeyAsStr := aKeyValue.Key
queryValAsBytes := aKeyValue.Value
// fmt.Println("on security id - ", queryKeyAsStr)
var security Security
json.Unmarshal(queryValAsBytes, &security) //un stringify it aka JSON.parse()
everything.Securities = append(everything.Securities, security) //add this marble to the list
}
// fmt.Println("security array - ", everything.Securities)
// ---- Get All Investors ---- //
investorsIterator, err := stub.GetStateByRange("investor0", "investor9999999999999999999")
if err != nil {
return shim.Error(err.Error())
}
defer investorsIterator.Close()
for investorsIterator.HasNext() {
aKeyValue, err := investorsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// queryKeyAsStr := aKeyValue.Key
queryValAsBytes := aKeyValue.Value
// fmt.Println("on investor id - ", queryKeyAsStr)
var investor Investor
json.Unmarshal(queryValAsBytes, &investor) //un stringify it aka JSON.parse()
everything.Investors = append(everything.Investors, investor) //add this marble to the list
}
// fmt.Println("investor array - ", everything.Investors)
fmt.Println("result", everything)
//change to array of bytes
everythingAsBytes, _ := json.Marshal(everything) //convert to array of bytes
return shim.Success(everythingAsBytes)
}
// ============================================================================================================================
// Get history of asset
//
// Shows Off GetHistoryForKey() - reading complete history of a key/value
//
// Inputs - Array of strings
// 0
// id
// "m01490985296352SjAyM"
// ============================================================================================================================
func getHistory(stub shim.ChaincodeStubInterface, args []string) pb.Response {
type AuditHistory struct {
TxId string `json:"txId"`
Value Asset `json:"value"`
}
var history []AuditHistory;
var asset Asset
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
assetId := args[0]
fmt.Printf("- start getHistoryForAsset: %s\n", assetId)
// Get History
resultsIterator, err := stub.GetHistoryForKey(assetId)
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
for resultsIterator.HasNext() {
historyData, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
var tx AuditHistory
tx.TxId = historyData.TxId //copy transaction id over
json.Unmarshal(historyData.Value, &asset) //un stringify it aka JSON.parse()
if historyData.Value == nil { //marble has been deleted
var emptyAsset Asset
tx.Value = emptyAsset //copy nil marble
} else {
json.Unmarshal(historyData.Value, &asset) //un stringify it aka JSON.parse()
tx.Value = asset //copy marble over
}
history = append(history, tx) //add this tx to the list
}
fmt.Printf("- getHistoryForMarble returning:\n%s", history)
//change to array of bytes
historyAsBytes, _ := json.Marshal(history) //convert to array of bytes
return shim.Success(historyAsBytes)
}
// ============================================================================================================================
// Get history of asset - performs a range query based on the start and end keys provided.
//
// Shows Off GetStateByRange() - reading a multiple key/values from the ledger
//
// Inputs - Array of strings
// 0 , 1
// startKey , endKey
// "marbles1" , "marbles5"
// ============================================================================================================================
// func getMarblesByRange(stub shim.ChaincodeStubInterface, args []string) pb.Response {
// if len(args) != 2 {
// return shim.Error("Incorrect number of arguments. Expecting 2")
// }
//
// startKey := args[0]
// endKey := args[1]
//
// 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() {
// aKeyValue, err := resultsIterator.Next()
// if err != nil {
// return shim.Error(err.Error())
// }
// queryResultKey := aKeyValue.Key
// queryResultValue := aKeyValue.Value
//
// // 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(queryResultKey)
// buffer.WriteString("\"")
//
// buffer.WriteString(", \"Record\":")
// // Record is a JSON object, so we write as-is
// buffer.WriteString(string(queryResultValue))
// buffer.WriteString("}")
// bArrayMemberAlreadyWritten = true
// }
// buffer.WriteString("]")
//
// fmt.Printf("- getMarblesByRange queryResult:\n%s\n", buffer.String())
//
// return shim.Success(buffer.Bytes())
// }