forked from pavankramadugu/CSE598-EBA-Project2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmartcontract.go
More file actions
264 lines (221 loc) · 7.37 KB
/
smartcontract.go
File metadata and controls
264 lines (221 loc) · 7.37 KB
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
package main // Package main, Do not change this line.
import (
"encoding/json"
"fmt"
"time"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
// Product represents the structure for a product entity
type Product struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Owner string `json:"owner"`
Description string `json:"description"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Category string `json:"category"`
}
// SupplyChainContract defines the smart contract structure
type SupplyChainContract struct {
contractapi.Contract
}
// getTimestamp returns the transaction timestamp as a string
func (s *SupplyChainContract) getTimestamp(ctx contractapi.TransactionContextInterface) (string, error) {
txTimestamp, err := ctx.GetStub().GetTxTimestamp()
if err != nil {
return "", fmt.Errorf("failed to get transaction timestamp: %v", err)
}
return time.Unix(txTimestamp.Seconds, int64(txTimestamp.Nanos)).Format(time.RFC3339), nil
}
// InitLedger initializes the ledger with some example products
func (s *SupplyChainContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
timestamp, err := s.getTimestamp(ctx)
if err != nil {
return err
}
// Initial set of products to populate the ledger
products := []Product{
{
ID: "p1",
Name: "Laptop",
Status: "Manufactured",
Owner: "CompanyA",
CreatedAt: timestamp,
UpdatedAt: timestamp,
Description: "High-end gaming laptop",
Category: "Electronics",
},
{
ID: "p2",
Name: "Smartphone",
Status: "Manufactured",
Owner: "CompanyB",
CreatedAt: timestamp,
UpdatedAt: timestamp,
Description: "Latest model smartphone",
Category: "Electronics",
}}
for _, product := range products {
if err := s.putProduct(ctx, &product); err != nil {
return err
}
}
return nil
}
// CreateProduct creates a new product in the ledger
func (s *SupplyChainContract) CreateProduct(ctx contractapi.TransactionContextInterface, id, name, owner, description, category string) error {
// Check if product already exists
exists, err := s.ProductExists(ctx, id)
if err != nil {
return fmt.Errorf("failed to check if product exists: %v", err)
}
if exists {
return fmt.Errorf("cannot create product: ID %s already in use", id)
}
// Get current timestamp
timestamp, err := s.getTimestamp(ctx)
if err != nil {
return fmt.Errorf("failed to get timestamp: %v", err)
}
// Create product
product := Product{
ID: id,
Name: name,
Status: "Manufactured",
Owner: owner,
CreatedAt: timestamp,
UpdatedAt: timestamp,
Description: description,
Category: category,
}
// Store product on the ledger
if err := s.putProduct(ctx, &product); err != nil {
return fmt.Errorf("failed to put product on ledger: %v", err)
}
return nil
}
// UpdateProduct allows updating a product's status, owner, description, and category
func (s *SupplyChainContract) UpdateProduct(ctx contractapi.TransactionContextInterface, id string, newStatus string, newOwner string, newDescription string, newCategory string) error {
// Fetch the current state of the product from the ledger
productJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return fmt.Errorf("failed to read from world state: %v", err)
}
if productJSON == nil {
return fmt.Errorf("product %s does not exist", id)
}
// Unmarshal product
var product Product
if err := json.Unmarshal(productJSON, &product); err != nil {
return fmt.Errorf("failed to unmarshal product JSON: %v", err)
}
// Get new timestamp
timestamp, err := s.getTimestamp(ctx)
if err != nil {
return fmt.Errorf("failed to get timestamp: %v", err)
}
// Update product fields
product.Status = newStatus
product.Description = newDescription
product.Category = newCategory
product.UpdatedAt = timestamp
// Save to ledger
if err := s.putProduct(ctx, &product); err != nil {
return fmt.Errorf("failed to update product: %v", err)
}
return nil
}
// TransferOwnership changes the owner of a product
func (s *SupplyChainContract) TransferOwnership(ctx contractapi.TransactionContextInterface, id, newOwner string) error {
// Retrieve product from ledger
productJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return fmt.Errorf("failed to read from world state: %v", err)
}
if productJSON == nil {
return fmt.Errorf("product %s does not exist", id)
}
// Unmarshal product
var product Product
if err := json.Unmarshal(productJSON, &product); err != nil {
return fmt.Errorf("failed to unmarshal product JSON: %v", err)
}
// Get new timestamp
timestamp, err := s.getTimestamp(ctx)
if err != nil {
return fmt.Errorf("failed to get timestamp: %v", err)
}
// Update the owner and timestamp
product.Owner = newOwner
product.UpdatedAt = timestamp
// Save updated product back to ledger
if err := s.putProduct(ctx, &product); err != nil {
return fmt.Errorf("failed to transfer ownership: %v", err)
}
return nil
}
// QueryProduct retrieves a single product from the ledger by ID
func (s *SupplyChainContract) QueryProduct(ctx contractapi.TransactionContextInterface, id string) (*Product, error) {
// Retrieve product from the ledger
productJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return nil, fmt.Errorf("failed to read from world state: %v", err)
}
if productJSON == nil {
return nil, fmt.Errorf("product with ID %s does not exist", id)
}
// Unmarshal product JSON into Product struct
var product Product
if err := json.Unmarshal(productJSON, &product); err != nil {
return nil, fmt.Errorf("failed to unmarshal product JSON: %v", err)
}
return &product, nil
}
// putProduct is a helper method for inserting or updating a product in the ledger
func (s *SupplyChainContract) putProduct(ctx contractapi.TransactionContextInterface, product *Product) error {
productJSON, err := json.Marshal(product)
if err == nil {
return ctx.GetStub().PutState(product.ID, productJSON)
}
return fmt.Errorf("failed to marshal product: %v", err)
}
// ProductExists is a helper method to check if a product exists in the ledger
func (s *SupplyChainContract) ProductExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) {
productJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return false, fmt.Errorf("failed to read from world state: %v", err)
}
return productJSON != nil, nil
}
// GetAllProducts is a helper method to retrieve all products from the ledger
func (s *SupplyChainContract) GetAllProducts(ctx contractapi.TransactionContextInterface) ([]*Product, error) {
resultsIterator, err := ctx.GetStub().GetStateByRange("", "")
if err != nil {
return nil, err
}
defer resultsIterator.Close()
var products []*Product
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return nil, err
}
var product Product
if err := json.Unmarshal(queryResponse.Value, &product); err != nil {
return nil, err
}
products = append(products, &product)
}
return products, nil
}
func main() {
chaincode, err := contractapi.NewChaincode(&SupplyChainContract{})
if err != nil {
fmt.Printf("Error creating supply chain chaincode: %s", err.Error())
return
}
if err := chaincode.Start(); err != nil {
fmt.Printf("Error starting supply chain chaincode: %s", err.Error())
}
}