daily pastebin goal
12%
SHARE
TWEET

Untitled

a guest Aug 10th, 2018 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "bytes"
  5.     "encoding/json"
  6.     "fmt"
  7.     "strconv"
  8.     "strings"
  9.     "time"
  10.  
  11.     "github.com/hyperledger/fabric/core/chaincode/shim"
  12.     pb "github.com/hyperledger/fabric/protos/peer"
  13. )
  14.  
  15. // AutoTraceChaincode example simple Chaincode implementation
  16. type AutoTraceChaincode struct {
  17. }
  18.  
  19. type BankTransaction struct {
  20.     BankTransactionId string `json:"bankTransactionId"`
  21.     CreatedBy    string `json:"createdBy"`      
  22.     DateCreated  int    `json:"dateCreated"`
  23.     ObjectId     int    `json:"objectId"`
  24.     ObjectType   string `json:"docType"`
  25.     OrgName      string `json:"orgName"`
  26.     TransactionType        int `json:"transactionType"`
  27.     UserId   string    `json:"userId"`
  28. }
  29.  
  30. // ===================================================================================
  31. // Main
  32. // ===================================================================================
  33. func main() {
  34.     err := shim.Start(new(AutoTraceChaincode))
  35.     if err != nil {
  36.         fmt.Printf("Error starting Parts Trace chaincode: %s", err)
  37.     }
  38. }
  39.  
  40. // ===================================================================================
  41. //  init...initializes chaincode
  42. // ===================================================================================
  43. func (t *AutoTraceChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
  44.     return shim.Success(nil)
  45. }
  46.  
  47. // ===================================================================================
  48. // Invoke - Our entry point for Invocations
  49. // ===================================================================================
  50. func (t *AutoTraceChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
  51.     function, args := stub.GetFunctionAndParameters()
  52.     fmt.Println("invoke is running " + function)
  53.  
  54.     // Handle different functions
  55.     if function == "initBankTransaction" { //create a new vehiclePart
  56.         return t.initBankTransaction(stub, args)
  57.     } else if function == "readBankTransaction" { //read a vehiclePart
  58.         return t.readBankTransaction(stub, args)
  59.     } else if function == "queryBankTransactionByOrgName" { //find vehicle part for owner X (rich query)
  60.         return t.queryBankTransactionByOrgName(stub, args)
  61.     }
  62.  
  63.     fmt.Println("invoke did not find func: " + function) //error
  64.     return shim.Error("Received unknown function invocation")
  65. }
  66.  
  67. // ============================================================
  68. // initBankTransaction - create a new bank transaction, store into chaincode state
  69. // ============================================================
  70. func (t *AutoTraceChaincode) initBankTransaction(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  71.     var err error
  72.  
  73.     // === Validation and Mapping ===
  74.  
  75.     if len(args) != 8 {
  76.         return shim.Error("Incorrect number of arguments. Expecting 8")
  77.     }
  78.    
  79.     createdBy := strings.ToLower(args[0])
  80.     dateCreated, err  := strconv.Atoi(args[1])
  81.     if err != nil {
  82.         return shim.Error("dateCreated should be int")
  83.     }
  84.     objectId, err     := strconv.Atoi(args[2])
  85.     if err != nil {
  86.         return shim.Error("objectId should bt int")
  87.     }
  88.     objectType   := strings.ToLower(args[3])
  89.     orgName      := strings.ToLower(args[4])
  90.     transactionType, err := strconv.Atoi(args[5])
  91.     if err != nil {
  92.         return shim.Error("transactionType should be string")
  93.     }
  94.     userId := strings.ToLower(args[6])
  95.     bankTransactionId := strings.ToLower(args[7])
  96.  
  97.  
  98.     BankTransaction := &BankTransaction{bankTransactionId, createdBy, dateCreated, objectId, objectType, orgName, transactionType, userId}
  99.     bankTransactionJSONasBytes, err := json.Marshal(BankTransaction)
  100.     if err != nil {
  101.         return shim.Error(err.Error())
  102.     }
  103.  
  104.     // === Save Bank Transaction to state ===
  105.     err = stub.PutState(bankTransactionId, bankTransactionJSONasBytes)
  106.     if err != nil {
  107.         return shim.Error(err.Error())
  108.     }
  109.  
  110.     // ==== Bank Transaction saved and indexed. Return success ====
  111.     fmt.Println("- end init bank transaction")
  112.     return shim.Success(nil)
  113. }
  114.  
  115.  
  116. // ===============================================
  117. // readBankTransaction - read a Bank Transaction from chaincode state
  118. // ===============================================
  119. func (t *AutoTraceChaincode) readBankTransaction(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  120.     var jsonResp string
  121.     var err error
  122.  
  123.     bankTransactionId := strings.ToLower(args[0])
  124.     valAsbytes, err := stub.GetState(bankTransactionId) //get the bank transaction from chaincode state
  125.     if err != nil {
  126.         jsonResp = "{\"Error\":\"Failed to get state for " + bankTransactionId + "\"}"
  127.         fmt.Println(jsonResp)
  128.         return shim.Error(jsonResp)
  129.     } else if valAsbytes == nil {
  130.         jsonResp = "{\"Error\":\"Vehicle part does not exist: " + bankTransactionId + "\"}"
  131.         fmt.Println(jsonResp)
  132.         return shim.Error(jsonResp)
  133.     }
  134.  
  135.     return shim.Success(valAsbytes)
  136. }
  137.  
  138.  
  139. // ===== Example: Parameterized rich query =================================================
  140. // queryBankTransactionByOrgName queries for Bank Transaction based on a passed in orgName.
  141. // =========================================================================================
  142. func (t *AutoTraceChaincode) queryBankTransactionByOrgName(stub shim.ChaincodeStubInterface, args []string) pb.Response {
  143.     if len(args) != 1 {
  144.         return shim.Error("Incorrect number of arguments. Expecting 1")
  145.     }
  146.  
  147.     orgName := strings.ToLower(args[0])
  148.  
  149.     queryString := fmt.Sprintf("{\"selector\":{\"orgName\":\"%s\"}}", orgName)
  150.  
  151.     queryResults, err := getQueryResultForQueryString(stub, queryString)
  152.     if err != nil {
  153.         return shim.Error(err.Error())
  154.     }
  155.     return shim.Success(queryResults)
  156. }
  157.  
  158. // =========================================================================================
  159. // getQueryResultForQueryString executes the passed in query string.
  160. // Result set is built and returned as a byte array containing the JSON results.
  161. // =========================================================================================
  162. func getQueryResultForQueryString(stub shim.ChaincodeStubInterface, queryString string) ([]byte, error) {
  163.  
  164.     fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString)
  165.  
  166.     resultsIterator, err := stub.GetQueryResult(queryString)
  167.     if err != nil {
  168.         return nil, err
  169.     }
  170.     defer resultsIterator.Close()
  171.  
  172.     // buffer is a JSON array containing QueryRecords
  173.     var buffer bytes.Buffer
  174.     buffer.WriteString("[")
  175.  
  176.     bArrayMemberAlreadyWritten := false
  177.     for resultsIterator.HasNext() {
  178.         queryResponse, err := resultsIterator.Next()
  179.         if err != nil {
  180.             return nil, err
  181.         }
  182.         // Add a comma before array members, suppress it for the first array member
  183.         if bArrayMemberAlreadyWritten == true {
  184.             buffer.WriteString(",")
  185.         }
  186.         buffer.WriteString(string(queryResponse.Value))
  187.         bArrayMemberAlreadyWritten = true
  188.     }
  189.     buffer.WriteString("]")
  190.  
  191.     fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String())
  192.  
  193.     return buffer.Bytes(), nil
  194. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Pastebin PRO 'SUMMER SPECIAL'!
Get 40% OFF Pastebin PRO accounts!
 
Top