-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcannabee-chaincode.go
230 lines (192 loc) · 6.26 KB
/
cannabee-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
// SPDX-License-Identifier: Apache-2.0
/*
Sample Chaincode based on Demonstrated Scenario
This code is based on code written by the Hyperledger Fabric community.
Original code can be found here: https://github.com/hyperledger/fabric-samples/blob/release/chaincode/fabcar/fabcar.go
*/
package main
/* Imports
* 4 utility libraries for handling bytes, reading and writing JSON,
formatting, and string manipulation
* 2 specific Hyperledger Fabric specific libraries for Smart Contracts
*/
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/hyperledger/fabric/core/chaincode/shim"
sc "github.com/hyperledger/fabric/protos/peer"
)
// Define the Smart Contract structure
type SmartContract struct {
}
/* Define Tuna structure, with 4 properties.
Structure tags are used by encoding/json library
*/
type Usd struct {
Holder string `json:"holder"`
Value string `json:"value"`
}
/*
* The Init method *
called when the Smart Contract "tuna-chaincode" is instantiated by the network
* Best practice is to have any Ledger initialization in separate function
-- see initLedger()
*/
func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
return shim.Success(nil)
}
/*
* The Invoke method *
called when an application requests to run the Smart Contract "tuna-chaincode"
The app also specifies the specific smart contract function to call with args
*/
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := APIstub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger
if function == "queryTuna" {
return s.queryTuna(APIstub, args)
} else if function == "initLedger" {
return s.initLedger(APIstub)
} else if function == "recordTuna" {
return s.recordTuna(APIstub, args)
} else if function == "queryAllUsd" {
return s.queryAllUsd(APIstub)
} else if function == "changeTunaHolder" {
return s.changeTunaHolder(APIstub, args)
}
return shim.Error("Invalid Smart Contract function name.")
}
/*
* The queryTuna method *
Used to view the records of one particular tuna
It takes one argument -- the key for the tuna in question
*/
func (s *SmartContract) queryTuna(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
tunaAsBytes, _ := APIstub.GetState(args[0])
if tunaAsBytes == nil {
return shim.Error("Could not locate tuna")
}
return shim.Success(tunaAsBytes)
}
/*
* The initLedger method *
Will add test data (10 tuna catches)to our network
*/
func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) sc.Response {
usd := []Usd{
Usd{Holder: "Adam", Value: "200"},
Usd{Holder: "Jenny", Value: "150"},
Usd{Holder: "Suman", Value: "140"},
Usd{Holder: "Sukanya", Value: "60"},
Usd{Holder: "Alan", Value: "100"}
}
i := 0
for i < len(usd) {
fmt.Println("i is ", i)
usdAsBytes, _ := json.Marshal(usd[i])
APIstub.PutState(strconv.Itoa(i+1), usdAsBytes)
fmt.Println("Added", usd[i])
i = i + 1
}
return shim.Success(nil)
}
/*
* The recordTuna method *
Fisherman like Sarah would use to record each of her tuna catches.
This method takes in five arguments (attributes to be saved in the ledger).
*/
func (s *SmartContract) recordTuna(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 5 {
return shim.Error("Incorrect number of arguments. Expecting 5")
}
var tuna = Tuna{ Vessel: args[1], Location: args[2], Timestamp: args[3], Holder: args[4] }
tunaAsBytes, _ := json.Marshal(tuna)
err := APIstub.PutState(args[0], tunaAsBytes)
if err != nil {
return shim.Error(fmt.Sprintf("Failed to record tuna catch: %s", args[0]))
}
return shim.Success(nil)
}
/*
* The queryAllTuna method *
allows for assessing all the records added to the ledger(all tuna catches)
This method does not take any arguments. Returns JSON string containing results.
*/
func (s *SmartContract) queryAllUsd(APIstub shim.ChaincodeStubInterface) sc.Response {
startKey := "0"
endKey := "999"
resultsIterator, err := APIstub.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 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("- queryAllUsd:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
}
/*
* The changeTunaHolder method *
The data in the world state can be updated with who has possession.
This function takes in 2 arguments, tuna id and new holder name.
*/
func (s *SmartContract) changeTunaHolder(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 2 {
return shim.Error("Incorrect number of arguments. Expecting 2")
}
tunaAsBytes, _ := APIstub.GetState(args[0])
if tunaAsBytes == nil {
return shim.Error("Could not locate tuna")
}
tuna := Tuna{}
json.Unmarshal(tunaAsBytes, &tuna)
// Normally check that the specified argument is a valid holder of tuna
// we are skipping this check for this example
tuna.Holder = args[1]
tunaAsBytes, _ = json.Marshal(tuna)
err := APIstub.PutState(args[0], tunaAsBytes)
if err != nil {
return shim.Error(fmt.Sprintf("Failed to change tuna holder: %s", args[0]))
}
return shim.Success(nil)
}
/*
* main function *
calls the Start function
The main function starts the chaincode in the container during instantiation.
*/
func main() {
// Create a new Smart Contract
err := shim.Start(new(SmartContract))
if err != nil {
fmt.Printf("Error creating new Smart Contract: %s", err)
}
}