-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
296 lines (239 loc) · 8.62 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
// ServntireDemoChaincode implementation of Chaincode
type ServntireDemoChaincode struct {
}
type Car struct {
Make string `json:"make"`
Model string `json:"model"`
Colour string `json:"colour"`
Owner string `json:"owner"`
}
// Init of the chaincode
// This function is called only one when the chaincode is instantiated.
// So the goal is to prepare the ledger to handle future requests.
func (t *ServntireDemoChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("########### ServntireDemoChaincode Init ###########")
// Get the function and arguments from the request
function, _ := stub.GetFunctionAndParameters()
// Check if the request is the init function
if function != "init" {
return shim.Error("Unknown function call")
}
// Adding to the ledger.
cars := []Car{
Car{Make: "Toyota", Model: "Prius", Colour: "blue", Owner: "Tomoko"},
Car{Make: "Ford", Model: "Mustang", Colour: "red", Owner: "Brad"},
Car{Make: "Hyundai", Model: "Tucson", Colour: "green", Owner: "Jin Soo"},
Car{Make: "Volkswagen", Model: "Passat", Colour: "yellow", Owner: "Max"},
Car{Make: "Tesla", Model: "S", Colour: "black", Owner: "Adriana"},
Car{Make: "Peugeot", Model: "205", Colour: "purple", Owner: "Michel"},
Car{Make: "Chery", Model: "S22L", Colour: "white", Owner: "Aarav"},
Car{Make: "Fiat", Model: "Punto", Colour: "violet", Owner: "Pari"},
Car{Make: "Tata", Model: "Nano", Colour: "indigo", Owner: "Valeria"},
Car{Make: "Holden", Model: "Barina", Colour: "brown", Owner: "Shotaro"},
}
i := 0
for i < len(cars) {
fmt.Println("i is ", i)
carAsBytes, _ := json.Marshal(cars[i])
stub.PutState("CAR"+strconv.Itoa(i), carAsBytes)
fmt.Println("Added", cars[i])
i = i + 1
}
// Return a successful message
return shim.Success(nil)
}
// Invoke
// All future requests named invoke will arrive here.
func (t *ServntireDemoChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("########### ServntireDemoChaincode Invoke ###########")
// Get the function and arguments from the request
function, args := stub.GetFunctionAndParameters()
// Check whether it is an invoke request
if function != "invoke" {
return shim.Error("Unknown function call")
}
// Check whether the number of arguments is sufficient
if len(args) < 1 {
return shim.Error("The number of arguments is insufficient.")
}
// In order to manage multiple type of request, we will check the first argument.
// Here we have one possible argument: query (every query request will read in the ledger without modification)
if args[0] == "query" {
return t.query(stub, args)
}
// The update argument will manage all update in the ledger
if args[0] == "invoke" {
return t.invoke(stub, args)
}
// Querying Single Record by Passing CAR ID => Key as parameter
if args[0] == "queryone" {
return t.queryone(stub, args)
}
// Adding a new transaction to the ledger
if args[0] == "create" {
return t.createcar(stub, args)
}
// If the arguments given don’t match any function, we return an error
return shim.Error("Unknown action, check the first argument")
}
// query
// Every readonly functions in the ledger will be here
func (t *ServntireDemoChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {
// Check whether the number of arguments is sufficient
if len(args) < 2 {
return shim.Error("The number of arguments is insufficient.")
}
// Retrieves All the records here.
if args[1] == "all" {
//startKey := "CAR0"
//endKey := "CAR999"
// GetState by passing lower and upper limits
resultsIterator, err := stub.GetStateByRange("", "")
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(",")
}
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("- queryAllCars:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
}
// If the arguments given don’t match any function, we return an error
return shim.Error("Unknown query action, check the second argument.")
}
// invoke
// Every functions that read and write in the ledger will be here
func (t *ServntireDemoChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response {
if len(args) < 2 {
return shim.Error("The number of arguments is insufficient.")
}
// Changing Ownership of a Car by Accepting Key and Value
if args[1] == "changeOwner" && len(args) == 4 {
/*
@@@ Editing Single Field @@@
*/
carAsBytes, _ := stub.GetState(args[2])
car := Car{}
json.Unmarshal(carAsBytes, &car)
car.Owner = args[3]
carAsBytes, _ = json.Marshal(car)
stub.PutState(args[2], carAsBytes)
return shim.Success(nil)
}
// If the arguments given don’t match any function, we return an error
return shim.Error("Unknown invoke action, check the second argument.")
}
// Retrieves a single record from the ledger by accepting Key value
func (t *ServntireDemoChaincode) queryone(stub shim.ChaincodeStubInterface, args []string) pb.Response {
if len(args) < 2 {
return shim.Error("The number of arguments is insufficient.")
}
// GetState retrieves the data from ledger using the Key
carAsBytes, _ := stub.GetState(args[1])
// Transaction Response
return shim.Success(carAsBytes)
}
// Adds a new transaction to the ledger
func (s *ServntireDemoChaincode) createcar(stub shim.ChaincodeStubInterface, args []string) pb.Response {
if len(args) < 3 {
return shim.Error("Incorrect number of arguments. Expecting 3")
}
var newCar Car
json.Unmarshal([]byte(args[2]), &newCar)
var car = Car{Make: newCar.Make, Model: newCar.Model, Colour: newCar.Colour, Owner: newCar.Owner}
carAsBytes, _ := json.Marshal(car)
stub.PutState(args[1], carAsBytes)
return shim.Success(nil)
}
// Get History of a transaction by passing Key
func (s *ServntireDemoChaincode) gethistory(stub shim.ChaincodeStubInterface, args []string) pb.Response {
if len(args) < 2 {
return shim.Error("Incorrect number of arguments. Expecting 3")
}
carKey := args[1]
fmt.Printf("##### start History of Record: %s\n", carKey)
resultsIterator, err := stub.GetHistoryForKey(carKey)
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
// buffer is a JSON array containing historic values for the marble
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
response, 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("{\"TxId\":")
buffer.WriteString("\"")
buffer.WriteString(response.TxId)
buffer.WriteString("\"")
buffer.WriteString(", \"Value\":")
// if it was a delete operation on given key, then we need to set the
//corresponding value null. Else, we will write the response.Value
//as-is (as the Value itself a JSON marble)
if response.IsDelete {
buffer.WriteString("null")
} else {
buffer.WriteString(string(response.Value))
}
buffer.WriteString(", \"Timestamp\":")
buffer.WriteString("\"")
buffer.WriteString(time.Unix(response.Timestamp.Seconds, int64(response.Timestamp.Nanos)).String())
buffer.WriteString("\"")
buffer.WriteString(", \"IsDelete\":")
buffer.WriteString("\"")
buffer.WriteString(strconv.FormatBool(response.IsDelete))
buffer.WriteString("\"")
buffer.WriteString("}")
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
fmt.Printf("- getHistoryForMarble returning:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
}
func main() {
// Start the chaincode and make it ready for futures requests
err := shim.Start(new(ServntireDemoChaincode))
if err != nil {
fmt.Printf("Error starting Servntire Demo chaincode: %s", err)
}
}