-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_ledger.go
256 lines (223 loc) · 7.88 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
/*
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"
"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("- 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 {
Owners []Owner `json:"owners"`
Marbles []Marble `json:"marbles"`
}
var everything Everything
// ---- Get All Marbles ---- //
resultsIterator, err := stub.GetStateByRange("m0", "m9999999999999999999")
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
for resultsIterator.HasNext() {
queryKeyAsStr, queryValAsBytes, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
fmt.Println("on marble id - ", queryKeyAsStr)
var marble Marble
json.Unmarshal(queryValAsBytes, &marble) //un stringify it aka JSON.parse()
everything.Marbles = append(everything.Marbles, marble) //add this marble to the list
}
fmt.Println("marble array - ", everything.Marbles)
// ---- Get All Owners ---- //
ownersIterator, err := stub.GetStateByRange("o0", "o9999999999999999999")
if err != nil {
return shim.Error(err.Error())
}
defer ownersIterator.Close()
for ownersIterator.HasNext() {
queryKeyAsStr, queryValAsBytes, err := ownersIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
fmt.Println("on owner id - ", queryKeyAsStr)
var owner Owner
json.Unmarshal(queryValAsBytes, &owner) //un stringify it aka JSON.parse()
everything.Owners = append(everything.Owners, owner) //add this marble to the list
}
fmt.Println("owner array - ", everything.Owners)
//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 Marble `json:"value"`
}
var history []AuditHistory;
var marble Marble
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
marbleId := args[0]
fmt.Printf("- start getHistoryForMarble: %s\n", marbleId)
// Get History
resultsIterator, err := stub.GetHistoryForKey(marbleId)
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
for resultsIterator.HasNext() {
txID, historicValue, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
var tx AuditHistory
tx.TxId = txID //copy transaction id over
json.Unmarshal(historicValue, &marble) //un stringify it aka JSON.parse()
if historicValue == nil { //marble has been deleted
var emptyMarble Marble
tx.Value = emptyMarble //copy nil marble
} else {
json.Unmarshal(historicValue, &marble) //un stringify it aka JSON.parse()
tx.Value = marble //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() {
queryResultKey, queryResultValue, 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(",")
}
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())
}