foodchain.cc.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. package main
  2. import (
  3. //"bytes"
  4. "encoding/json"
  5. "fmt"
  6. //"strconv"
  7. //"strings"
  8. "time"
  9. "github.com/hyperledger/fabric/core/chaincode/shim"
  10. pb "github.com/hyperledger/fabric/protos/peer"
  11. )
  12. //=============================================================================================================================================================================
  13. // Structs
  14. //=============================================================================================================================================================================
  15. type SimpleChaincode struct {
  16. }
  17. type user struct {
  18. Firstname string `json:"firstname"`
  19. Lastname string `json:"lastname"`
  20. userID string `json:"userid"`
  21. DOB string `json:"dob"`
  22. Email string `json:"email"`
  23. Mobile string `json:"mobile"`
  24. Class string `json:"class"`
  25. ObjectType string `json:"docType"`
  26. }
  27. type RawMaterial struct {
  28. RMID string `json:"rmid"`
  29. Item string `json:"item"`
  30. Creator string `json:"creator"`
  31. Current_Owner string `json:"currentowner"`
  32. ClaimTags string `json:"claimtags"`
  33. Location string `json:"location"`
  34. Date string `json:"date"`
  35. CertID string `json:"certid"`
  36. ObjectType string `json:"docType"`
  37. // add quality
  38. }
  39. type FinishedGood struct {
  40. FPID string `json:"fpid"`
  41. Name string `json:"name"`
  42. Creator string `json:"creator"`
  43. Current_Owner string `json:"currentowner"`
  44. Ingredients string `json:"ingredients"`
  45. //Previous_Owner string `json:"previousowner"`
  46. Certificates string `json:"certificates"`
  47. ClaimTags string `json:"claimtags"`
  48. Location string `json:"location"`
  49. Date string `json:"date"`
  50. CertID string `json:"certid"`
  51. ObjectType string `json:"docType"`
  52. }
  53. type PurchaseOrder struct{
  54. PurchaseOrderID string `json:"purchaseorderid"`
  55. Customer string `json:"customer"`
  56. Vendor string `json:"vendor"`
  57. ProductID string `json:"productid"`
  58. Price string `json:"price"`
  59. Date string `json:"date"`
  60. // Status string `json:"status"`
  61. ObjectType string `json:"docType"`
  62. }
  63. type Certificate struct {
  64. CertID string `json:"certid"`
  65. OrgName string `json:"orgname"`
  66. Supplier string `json:"supplier"`
  67. Status string `json:"status"`
  68. Date_effective string `json:"dateeffective"`
  69. Certifier string `json:"certifier"`
  70. ProductList string `json:"productlist"`
  71. OpDetails string `json:"opdetails"`
  72. Location string `json:"location"`
  73. ExpiryDate string `json:"expdate"`
  74. ObjectType string `json:"docType"`
  75. }
  76. // =============================================================================================================================================================
  77. // MAIN FUNCTIONS
  78. // ==============================================================================================================================================================
  79. func main() {
  80. err := shim.Start(new(SimpleChaincode))
  81. if err != nil {
  82. fmt.Printf("Error starting Simple chaincode: %s", err)
  83. }
  84. }
  85. // Init initializes chaincode
  86. // ===========================
  87. func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
  88. var err error
  89. err = stub.PutState("status", []byte("Blockchain online")) //write the variable into the chaincode state
  90. if err != nil {
  91. return shim.Error(err.Error())
  92. }
  93. return shim.Success(nil)
  94. }
  95. // Invoke - Our entry point for Invocations
  96. // ========================================
  97. func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
  98. function, args := stub.GetFunctionAndParameters()
  99. fmt.Println("invoke is running " + function)
  100. // Handle different functions
  101. if function == "Register" { //create a new user
  102. return t.Register(stub, args)
  103. } else if function == "RegisterRM" {
  104. return t.RegisterRM(stub, args)
  105. } else if function == "RegisterFP" {
  106. return t.RegisterFP(stub, args)
  107. } else if function == "makePurchaseOrder" {
  108. return t.makePurchaseOrder(stub, args)
  109. } else if function == "replyPurchaseOrder" {
  110. return t.replyPurchaseOrder(stub, args)
  111. } else if function == "transferRM" {
  112. return t.transferRM(stub, args)
  113. } else if function == "transferFP" {
  114. return t.transferFP(stub, args)
  115. } else if function == "awardCert" {
  116. return t.awardCert(stub, args)
  117. } else if function == "requestCert" {
  118. return t.requestCert(stub, args)
  119. } else if function == "read" {
  120. return t.read(stub, args)
  121. } else if function == "getHistory" {
  122. return t.getHistory(stub, args)
  123. } else if function == "modifyCert" {
  124. return t.modifyCert(stub, args)
  125. } else if function == "getHistoryFG" {
  126. return t.getHistoryFG(stub, args)
  127. }
  128. fmt.Println("invoke did not find func: " + function) //error
  129. return shim.Error("Received unknown function invocation")
  130. }
  131. //============================================================================================================================================================================
  132. // REGISTRATION CODE BELOW
  133. //=============================================================================================================================================================================
  134. func (t *SimpleChaincode) Register(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  135. var err error
  136. // Firstname string `json:"firstname"` 0
  137. // Lastname string `json:"lastname"` 1
  138. // userID string `json:"userid"` 2
  139. // DOB string `json:"dob"` 3
  140. // Email string `json:"email"` 4
  141. // Mobile string `json:"mobile"` 5
  142. // Class string `json:"class"` 6
  143. if len(args) != 7 {
  144. return shim.Error("Incorrect number of arguments. Expecting 7")
  145. }
  146. // ==== Input sanitation ====
  147. fname := args[0]
  148. lname := args[1]
  149. uid := args[2]
  150. userdob := args[3]
  151. useremail := args[4]
  152. usermobile := args[5]
  153. userclass := args[6]
  154. // ==== Check if user already exists ====
  155. fnameAsBytes, err := stub.GetState(uid) //Change this to uid not fname
  156. if err != nil {
  157. return shim.Error("Failed to get user: " + err.Error())
  158. } else if fnameAsBytes != nil {
  159. fmt.Println("This user already exists: " + fname)
  160. return shim.Error("This user already exists: " + fname)
  161. }
  162. // ==== Create user object and marshal to JSON ====
  163. objectType := "user"
  164. user := &user{fname, lname, uid, userdob, useremail, usermobile, userclass, objectType}
  165. userJSONasBytes, err := json.Marshal(user)
  166. if err != nil {
  167. return shim.Error(err.Error())
  168. }
  169. // === Save user to state ===
  170. err = stub.PutState(uid, userJSONasBytes)
  171. if err != nil {
  172. return shim.Error(err.Error())
  173. }
  174. //this should be uid based range query, needs to be tested
  175. // Index
  176. indexName := "uid~fname"
  177. uidIndexKey, err := stub.CreateCompositeKey(indexName, []string{user.userID, user.Firstname})
  178. if err != nil {
  179. return shim.Error(err.Error())
  180. }
  181. // Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the user.
  182. // Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value
  183. value := []byte{0x00}
  184. stub.PutState(uidIndexKey, value)
  185. // ==== user saved and indexed. Return success ====
  186. fmt.Println("- end init user")
  187. return shim.Success(nil)
  188. }
  189. func (t *SimpleChaincode) RegisterRM(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  190. var err error
  191. // RMID string `json:"rmid"` 0
  192. // Item string `json:"item"` 1
  193. // Creator string `json:"creator"` 2
  194. // Current_Owner string `json:"currentowner"` 3
  195. // ClaimTags string `json:"claimtags"` 4
  196. // Location string `json:"location"` 5
  197. // Date string `json:"date"` 6
  198. // CertID string `json:"certid"` 7
  199. // ObjectType string `json:"docType"` 8
  200. // ==== Input sanitation ====
  201. rawid := args[0]
  202. item := args[1]
  203. originalcreator := args[2]
  204. cowner := args[3]
  205. claimtags := args[4]
  206. loc := args[5]
  207. dates := args[6]
  208. userclass := args[7]
  209. // ==== Check if RM already exists ====
  210. rawidAsBytes, err := stub.GetState(rawid)
  211. if err != nil {
  212. return shim.Error("Failed to get user: " + err.Error())
  213. } else if rawidAsBytes != nil {
  214. fmt.Println("This user already exists: " + rawid)
  215. return shim.Error("This user already exists: " + rawid)
  216. }
  217. // ==== Create RM object and marshal to JSON ====
  218. objectType := "RawMaterial"
  219. RawMaterial := &RawMaterial{rawid, item, originalcreator, cowner, claimtags, loc, dates, userclass, objectType}
  220. RawMaterialJSONasBytes, err := json.Marshal(RawMaterial)
  221. if err != nil {
  222. return shim.Error(err.Error())
  223. }
  224. // === Save RM to state ===
  225. err = stub.PutState(rawid, RawMaterialJSONasBytes)
  226. if err != nil {
  227. return shim.Error(err.Error())
  228. }
  229. // Index
  230. indexName := "rawid~cowner"
  231. rawidIndexKey, err := stub.CreateCompositeKey(indexName, []string{RawMaterial.RMID, RawMaterial.Current_Owner})
  232. if err != nil {
  233. return shim.Error(err.Error())
  234. }
  235. // Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the user.
  236. // Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value
  237. value := []byte{0x00}
  238. stub.PutState(rawidIndexKey, value)
  239. // ==== RM saved and indexed. Return success ====
  240. fmt.Println("- end init user")
  241. return shim.Success(nil)
  242. }
  243. func (t *SimpleChaincode) RegisterFP(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  244. var err error
  245. // ObjectType string `json:"docType"` 0
  246. // FPID string `json:"fpid"` 1
  247. // Name string `json:"name"` 2
  248. // Creator string `json:"creator"` 3
  249. // Current_Owner string `json:"currentowner"` 4
  250. // Ingredients string `json:"ingredients"` 5
  251. ////Previous_Owner string `json:"previousowner"` 6
  252. // Certificates string `json:"certificates"` 7
  253. // ClaimTags string `json:"claimtags"` 8
  254. // Location string `json:"location"` 9
  255. // Date string `json:"date"` 10
  256. // CertID string `json:"certid"` 11
  257. // ==== Input sanitation ====
  258. fpid_i := args[0]
  259. name_i := args[1]
  260. originalcreator_i := args[2]
  261. cowner_i := args[3]
  262. ingredients_i := args[4]
  263. certificates_i := args[5]
  264. claimtags_i := args[6]
  265. loc_i := args[7]
  266. dates_i := args[8]
  267. certid_i := args[9]
  268. // ==== Check if FP already exists ====
  269. fpid_iAsBytes, err := stub.GetState(fpid_i)
  270. if err != nil {
  271. return shim.Error("Failed to get user: " + err.Error())
  272. } else if fpid_iAsBytes != nil {
  273. fmt.Println("This user already exists: " + fpid_i)
  274. return shim.Error("This user already exists: " + fpid_i)
  275. }
  276. // ==== Create object and marshal to JSON ====
  277. objectType := "FinishedGood"
  278. FinishedGood := &FinishedGood{fpid_i, name_i, originalcreator_i, cowner_i, ingredients_i, certificates_i, claimtags_i, loc_i, dates_i, certid_i, objectType}
  279. FinishedGoodJSONasBytes, err := json.Marshal(FinishedGood)
  280. if err != nil {
  281. return shim.Error(err.Error())
  282. }
  283. // === Save FP to state ===
  284. err = stub.PutState(fpid_i, FinishedGoodJSONasBytes)
  285. if err != nil {
  286. return shim.Error(err.Error())
  287. }
  288. //Index
  289. indexName := "fpid_i~cowner"
  290. fpiIndexKey, err := stub.CreateCompositeKey(indexName, []string{FinishedGood.FPID, FinishedGood.Current_Owner})
  291. if err != nil {
  292. return shim.Error(err.Error())
  293. }
  294. // Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the user.
  295. // Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value
  296. value := []byte{0x00}
  297. stub.PutState(fpiIndexKey, value)
  298. // ==== FP saved and indexed. Return success ====
  299. fmt.Println("- end init user")
  300. return shim.Success(nil)
  301. }
  302. //=============================================================================================================================================================================
  303. // Purchase Orders
  304. //=============================================================================================================================================================================
  305. func (t *SimpleChaincode) makePurchaseOrder(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  306. var err error
  307. // PurchaseOrderID string `json:"purchaseorderid"` 0
  308. // Customer string `json:"customer"` 1
  309. // Vendor string `json:"vendor"` 2
  310. // ProductID string `json:"productid"` 3
  311. // Price string `json:"price"` 4
  312. // Date string `json:"date"` 5
  313. // Status string `json:"status"` Pending
  314. // ObjectType string `json:"docType"` PurchaseOrder
  315. // ==== Input sanitation ====
  316. purchid := args[0]
  317. cust := args[1]
  318. vend := args[2]
  319. prodid := args[3]
  320. price:= args[4]
  321. dat := args[5]
  322. //stat := "Pending"
  323. // ==== Check if order already exists ====
  324. purchAsBytes, err := stub.GetState(purchid)
  325. if err != nil {
  326. return shim.Error("Failed to get product: " + err.Error())
  327. } else if purchAsBytes != nil {
  328. fmt.Println("This product already exists: " + purchid)
  329. return shim.Error("This product already exists: " + purchid)
  330. }
  331. // ==== Create object and marshal to JSON ====
  332. objectType := "PurchaseOrder"
  333. PurchaseOrder := &PurchaseOrder{purchid, cust, vend, prodid, price, dat, objectType}
  334. prodJSONasBytes, err := json.Marshal(PurchaseOrder)
  335. if err != nil {
  336. return shim.Error(err.Error())
  337. }
  338. // === Save order to state ===
  339. err = stub.PutState(purchid, prodJSONasBytes)
  340. if err != nil {
  341. return shim.Error(err.Error())
  342. }
  343. // ==== order saved and NOT indexed. Return success ====
  344. fmt.Println("- end init user")
  345. return shim.Success(nil)
  346. }
  347. func (t *SimpleChaincode) replyPurchaseOrder(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  348. var err error
  349. var key, value string
  350. var a = time.Now()
  351. var b = a.Format("20060102150405")
  352. key = args[0]
  353. var body = args[2] //this will be the yes or no
  354. value = args[1] + "-" + b +"-"+ key + " " + body
  355. err = stub.PutState(key, []byte(value)) //write the variable into the chaincode state
  356. if err != nil {
  357. return shim.Error(err.Error())
  358. }
  359. return shim.Success(nil)
  360. }
  361. //===========================================================================================================================================================================
  362. // Transferring
  363. //===========================================================================================================================================================================
  364. func (t *SimpleChaincode) transferRM(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  365. // 0 1
  366. // "name", "bob"
  367. if len(args) < 2 {
  368. return shim.Error("Incorrect number of arguments. Expecting 2")
  369. }
  370. prodid := args[0]
  371. newOwner := args[1]
  372. newLoc := args[2]
  373. newDate := args[3]
  374. assetAsBytes, err := stub.GetState(prodid)
  375. if err != nil {
  376. return shim.Error("Failed to get asset:" + err.Error())
  377. } else if assetAsBytes == nil {
  378. return shim.Error("Assest does not exist")
  379. }
  380. assetToTransfer := RawMaterial{}
  381. err = json.Unmarshal(assetAsBytes, &assetToTransfer) //unmarshal it aka JSON.parse()
  382. if err != nil {
  383. return shim.Error(err.Error())
  384. }
  385. assetToTransfer.Current_Owner = newOwner //change the owner
  386. assetToTransfer.Location = newLoc
  387. assetToTransfer.Date = newDate
  388. assetJSONasBytes, _ := json.Marshal(assetToTransfer)
  389. err = stub.PutState(prodid, assetJSONasBytes) //rewrite the asset
  390. if err != nil {
  391. return shim.Error(err.Error())
  392. }
  393. fmt.Println("- end transferRM (success)")
  394. return shim.Success(nil)
  395. }
  396. func (t *SimpleChaincode) transferFP(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  397. // 0 1
  398. // "name", "bob"
  399. if len(args) < 2 {
  400. return shim.Error("Incorrect number of arguments. Expecting 2")
  401. }
  402. prodid := args[0]
  403. newOwner := args[1]
  404. newLoc := args[2]
  405. newDate := args[3]
  406. assetAsBytes, err := stub.GetState(prodid)
  407. if err != nil {
  408. return shim.Error("Failed to get asset:" + err.Error())
  409. } else if assetAsBytes == nil {
  410. return shim.Error("Assest does not exist")
  411. }
  412. assetToTransfer := FinishedGood{}
  413. err = json.Unmarshal(assetAsBytes, &assetToTransfer) //unmarshal it aka JSON.parse()
  414. if err != nil {
  415. return shim.Error(err.Error())
  416. }
  417. assetToTransfer.Current_Owner = newOwner //change the owner
  418. assetToTransfer.Location = newLoc
  419. assetToTransfer.Date = newDate
  420. assetJSONasBytes, _ := json.Marshal(assetToTransfer)
  421. err = stub.PutState(prodid, assetJSONasBytes) //rewrite the asset
  422. if err != nil {
  423. return shim.Error(err.Error())
  424. }
  425. fmt.Println("- end transferRM (success)")
  426. return shim.Success(nil)
  427. }
  428. //===========================================================================================================================================================================
  429. // Certifying
  430. //===========================================================================================================================================================================
  431. func (t *SimpleChaincode) awardCert(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  432. var err error
  433. // CertID string `json:"certid"` 0
  434. // OrgName string `json:"orgname"` 1
  435. // Supplier string `json:"supplier"` 2
  436. // Status string `json:"status"` 3
  437. // Date_effective string `json:"dateeffective"` 4
  438. // Certifier string `json:"certifier"` 5
  439. // ProductList string `json:"productlist"` 6
  440. // OpDetails string `json:"opdetails"` 7
  441. // Location string `json:"location"` 8
  442. // ExpiryDate string `json:"expdate"` 9
  443. // ObjectType string `json:"docType"` 10
  444. // ==== Input sanitation ====
  445. certid := args[0]
  446. oname := args[1]
  447. supplier := args[2]
  448. stat := args[3]
  449. dateeff := args[4]
  450. certifierorg := args[5]
  451. prodlist := args[6]
  452. opdet := args[7]
  453. loc := args[8]
  454. expdat := args[9]
  455. // ==== Check if cert already exists ====
  456. awardAsBytes, err := stub.GetState(certid)
  457. if err != nil {
  458. return shim.Error("Failed to get cert: " + err.Error())
  459. } else if awardAsBytes != nil {
  460. fmt.Println("This cert already exists: " + certid)
  461. return shim.Error("This cert already exists: " + certid)
  462. }
  463. // ==== Create object and marshal to JSON ====
  464. objectType := "Certificate"
  465. Certificate := &Certificate{certid, oname, supplier, stat, dateeff, certifierorg, prodlist, opdet, loc, expdat, objectType}
  466. CertJSONasBytes, err := json.Marshal(Certificate)
  467. if err != nil {
  468. return shim.Error(err.Error())
  469. }
  470. // === Save certificate to state ===
  471. err = stub.PutState(certid, CertJSONasBytes)
  472. if err != nil {
  473. return shim.Error(err.Error())
  474. }
  475. // ==== certificate saved and NOT indexed. Return success ====
  476. fmt.Println("- end init cert")
  477. return shim.Success(nil)
  478. }
  479. func (t *SimpleChaincode) requestCert(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  480. var err error
  481. var key, value string
  482. //arg 0 is the certificate request id which will be UUID generated but for now just input
  483. //arg 1 is the suppliers id who is requesting the certificate
  484. //arg 2 is the name of the certificate
  485. //arg 3 is the products
  486. //arg 4 is the location
  487. var a = time.Now()
  488. var b = a.Format("20060102150405")
  489. key = args[0]
  490. var suppid = args[1]
  491. var name = args[2]
  492. var product = args[3]
  493. var location = args[4]
  494. value = key + "-" + b + " " + suppid + " " + name + " " + product + " " + location
  495. err = stub.PutState(key, []byte(value)) //write the variable into the chaincode state
  496. if err != nil {
  497. return shim.Error(err.Error())
  498. }
  499. return shim.Success(nil)
  500. }
  501. //
  502. // This function should be used to revoke certificates but because of its open input nature can be more flexible and be used for whatever really
  503. //
  504. func (t *SimpleChaincode) modifyCert(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  505. // 0 1
  506. // "certid", "new status"
  507. if len(args) < 2 {
  508. return shim.Error("Incorrect number of arguments. Expecting 2")
  509. }
  510. certid := args[0] // assigning first input to certid
  511. newStatus := args[1] // assigning second input to the new status of the certificate
  512. certAsBytes, err := stub.GetState(certid) //retrieving the certificate from the blockchain using the getstate function
  513. if err != nil {
  514. return shim.Error("Failed to get certificate:" + err.Error())
  515. } else if certAsBytes == nil {
  516. return shim.Error("Certificate does not exist")
  517. }
  518. certToModify := Certificate{}
  519. err = json.Unmarshal(certAsBytes, &certToModify) //unmarshal it aka JSON.parse()
  520. if err != nil {
  521. return shim.Error(err.Error())
  522. }
  523. certToModify.Status = newStatus //change the status
  524. certJSONasBytes, _ := json.Marshal(certToModify)
  525. err = stub.PutState(certid, certJSONasBytes) //rewrite the asset
  526. if err != nil {
  527. return shim.Error(err.Error())
  528. }
  529. fmt.Println("- end revokeCert (success)")
  530. return shim.Success(nil)
  531. }
  532. //===========================================================================================================================================================================
  533. // Reading
  534. //===========================================================================================================================================================================
  535. func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  536. var A string // Entities
  537. var err error
  538. A = args[0]
  539. // Get the state from the ledger
  540. Avalbytes, err := stub.GetState(A)
  541. if err != nil {
  542. jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
  543. return shim.Error(jsonResp)
  544. }
  545. //jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
  546. //fmt.Printf("Query Response:%s\n", jsonResp)
  547. return shim.Success(Avalbytes)
  548. }
  549. /*
  550. func (t *SimpleChaincode) queryRMByUID(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  551. // 0
  552. // "bob"
  553. if len(args) < 1 {
  554. return shim.Error("Incorrect number of arguments. Expecting 1")
  555. }
  556. owner := args[0]
  557. queryString := fmt.Sprintf("{\"selector\":{\"docType\":\"RawMaterial\",\"owner\":\"%s\"}}", owner)
  558. queryResults, err := getQueryResultForQueryString(stub, queryString)
  559. if err != nil {
  560. return shim.Error(err.Error())
  561. }
  562. return shim.Success(queryResults)
  563. }
  564. func getQueryResultForQueryString(stub shim.ChaincodeStubInterface, queryString string) ([]byte, error) {
  565. fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString)
  566. resultsIterator, err := stub.GetQueryResult(queryString)
  567. if err != nil {
  568. return nil, err
  569. }
  570. defer resultsIterator.Close()
  571. // buffer is a JSON array containing QueryRecords
  572. var buffer bytes.Buffer
  573. buffer.WriteString("[")
  574. bArrayMemberAlreadyWritten := false
  575. for resultsIterator.HasNext() {
  576. queryResponse, err := resultsIterator.Next()
  577. if err != nil {
  578. return nil, err
  579. }
  580. // Add a comma before array members, suppress it for the first array member
  581. if bArrayMemberAlreadyWritten == true {
  582. buffer.WriteString(",")
  583. }
  584. buffer.WriteString("{\"Key\":")
  585. buffer.WriteString("\"")
  586. buffer.WriteString(queryResponse.Key)
  587. buffer.WriteString("\"")
  588. buffer.WriteString(", \"Record\":")
  589. // Record is a JSON object, so we write as-is
  590. buffer.WriteString(string(queryResponse.Value))
  591. buffer.WriteString("}")
  592. bArrayMemberAlreadyWritten = true
  593. }
  594. buffer.WriteString("]")
  595. fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String())
  596. return buffer.Bytes(), nil
  597. }
  598. */
  599. func (t *SimpleChaincode) getHistory(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  600. type AuditHistory struct {
  601. TxId string `json:"txId"`
  602. Value RawMaterial `json:"value"`
  603. }
  604. var history []AuditHistory;
  605. var rawmaterial RawMaterial
  606. if len(args) != 1 {
  607. return shim.Error("Incorrect number of arguments. Expecting 1")
  608. }
  609. RMId := args[0]
  610. fmt.Printf("- start getHistoryForMarble: %s\n", RMId)
  611. // Get History
  612. resultsIterator, err := stub.GetHistoryForKey(RMId)
  613. if err != nil {
  614. return shim.Error(err.Error())
  615. }
  616. defer resultsIterator.Close()
  617. for resultsIterator.HasNext() {
  618. historyData, err := resultsIterator.Next()
  619. if err != nil {
  620. return shim.Error(err.Error())
  621. }
  622. var tx AuditHistory
  623. tx.TxId = historyData.TxId //copy transaction id over
  624. json.Unmarshal(historyData.Value, &rawmaterial) //un stringify it aka JSON.parse()
  625. if historyData.Value == nil { //marble has been deleted
  626. var emptyRM RawMaterial
  627. tx.Value = emptyRM //copy nil marble
  628. } else {
  629. json.Unmarshal(historyData.Value, &rawmaterial) //un stringify it aka JSON.parse()
  630. tx.Value = rawmaterial //copy marble over
  631. }
  632. history = append(history, tx) //add this tx to the list
  633. }
  634. fmt.Printf("- getHistoryForMarble returning:\n%s", history)
  635. //change to array of bytes
  636. historyAsBytes, _ := json.Marshal(history) //convert to array of bytes
  637. return shim.Success(historyAsBytes)
  638. }
  639. func (t *SimpleChaincode) getHistoryFG(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  640. type AuditHistory struct {
  641. TxId string `json:"txId"`
  642. Value FinishedGood `json:"value"`
  643. }
  644. var history []AuditHistory;
  645. var finishedgood FinishedGood
  646. if len(args) != 1 {
  647. return shim.Error("Incorrect number of arguments. Expecting 1")
  648. }
  649. FGId := args[0]
  650. fmt.Printf("- start getHistoryForMarble: %s\n", FGId)
  651. // Get History
  652. resultsIterator, err := stub.GetHistoryForKey(FGId)
  653. if err != nil {
  654. return shim.Error(err.Error())
  655. }
  656. defer resultsIterator.Close()
  657. for resultsIterator.HasNext() {
  658. historyData, err := resultsIterator.Next()
  659. if err != nil {
  660. return shim.Error(err.Error())
  661. }
  662. var tx AuditHistory
  663. tx.TxId = historyData.TxId //copy transaction id over
  664. json.Unmarshal(historyData.Value, &finishedgood) //un stringify it aka JSON.parse()
  665. if historyData.Value == nil { //marble has been deleted
  666. var emptyFG FinishedGood
  667. tx.Value = emptyFG //copy nil marble
  668. } else {
  669. json.Unmarshal(historyData.Value, &finishedgood) //un stringify it aka JSON.parse()
  670. tx.Value = finishedgood //copy marble over
  671. }
  672. history = append(history, tx) //add this tx to the list
  673. }
  674. fmt.Printf("- getHistoryForMarble returning:\n%s", history)
  675. //change to array of bytes
  676. historyAsBytes, _ := json.Marshal(history) //convert to array of bytes
  677. return shim.Success(historyAsBytes)
  678. }