katiyman

hashcode.go

Aug 17th, 2017
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 7.59 KB | None | 0 0
  1. package main
  2.  
  3. /* Imports
  4.  * 4 utility libraries for formatting, handling bytes, reading and writing JSON, and string manipulation
  5.  * 2 specific Hyperledger Fabric specific libraries for Smart Contracts
  6.  */
  7. import (
  8.         "bytes"
  9.         "encoding/json"
  10.         "fmt"
  11.         "strconv"
  12.         "time"
  13.         "github.com/hyperledger/fabric/core/chaincode/shim"
  14.         sc "github.com/hyperledger/fabric/protos/peer"
  15. )
  16.  
  17. // Define the Smart Contract structure
  18. type SmartContract struct {
  19. }
  20. // Define the car structure.  Structure tags are used by encoding/json library
  21. type Code struct {
  22.         //TimeStamp int64 `json:"timestamp"`
  23.         HashCode  string `json:"HashCode"`
  24.  
  25. }
  26.  
  27. /*
  28.  * The Init method is called when the Smart Contract  is instantiated by the blockchain network
  29.  * Best practice is to have any Ledger initialization in separate function -- see initLedger()
  30.  */
  31. func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
  32.         return shim.Success(nil)
  33. }
  34.  
  35. /*
  36.  * The Invoke method is called as a result of an application request to run the Smart Contract
  37.  * The calling application program has also specified the particular smart contract function to be called, with arguments
  38.  */
  39. func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {
  40.  
  41.         // Retrieve the requested Smart Contract function and arguments
  42.         function, args := APIstub.GetFunctionAndParameters()
  43.         // Route to the appropriate handler function to interact with the ledger appropriately
  44.         if function == "init" {
  45.                 return s.initCodeLedger(APIstub, args)
  46.         } else if function == "pushCode" {
  47.                 return s.pushCode(APIstub, args)
  48.         } else if function == "getAllCode" {
  49.                 return s.getAllCode(APIstub)
  50.         } else if function == "getCodesForRange"{
  51.                 return s.getCodesForRange(APIstub,args)
  52.         } else if function == "getCode"{
  53.                 return s.getCode(APIstub,args)
  54.         }
  55.  
  56.         return shim.Error("Invalid Smart Contract function name.")
  57. }
  58. func (s *SmartContract) initCodeLedger(APIstub shim.ChaincodeStubInterface, args[] string) sc.Response {
  59.         if len(args) == 0 {
  60.                 return shim.Error("Incorrect number of arguments. Expecting atlease 1")
  61.         }
  62.         for k:=0;k < len(args);k++{
  63.                         fmt.Println("k is ", k)
  64.                         hsCode := args[k]
  65.                         lenChk:=checkHashLen(hsCode)
  66.                         if lenChk==false{
  67.                                 fmt.Println("Length should be 32" )
  68.                                 continue
  69.                         }
  70.                         codeBytes,_ := json.Marshal(hsCode)
  71.                         APIstub.PutState(strconv.FormatInt(makeTimestamp(),10), codeBytes)
  72.                         fmt.Println("Added: ", k)
  73.  
  74.                 }
  75.  
  76.         return shim.Success(nil)
  77. }
  78. //push single code on the block
  79. func (s *SmartContract) pushCode(APIstub shim.ChaincodeStubInterface, args[] string) sc.Response {
  80.  
  81.         hsCode := args[0]
  82.         lenChk:=checkHashLen(hsCode)
  83.         if lenChk==false {
  84.                  fmt.Println("Length should be 32" )
  85.                  continue
  86.         }
  87.         codeBytes, _ := json.Marshal(hsCode)
  88.         APIstub.PutState(strconv.FormatInt(makeTimestamp(),10), codeBytes)
  89.         return shim.Success(nil)
  90. }
  91. //return all the codes from the ledger
  92. func (s *SmartContract) getAllCode(APIstub shim.ChaincodeStubInterface) sc.Response {
  93.  
  94.         startKey := "00000000000000000"
  95.         endKey := strconv.FormatInt(makeTimestamp(),10)
  96.  
  97.         resultsIterator, err := APIstub.GetStateByRange(startKey, endKey)
  98.         if err != nil {
  99.                 return shim.Error(err.Error())
  100.         }
  101.         defer resultsIterator.Close()
  102.  
  103.         // buffer is a JSON array containing QueryResults
  104.         var buffer bytes.Buffer
  105.         buffer.WriteString("[")
  106.  
  107.         bArrayMemberAlreadyWritten := false
  108.         for resultsIterator.HasNext() {
  109.                 queryResponse, err := resultsIterator.Next()
  110.                 if err != nil {
  111.                         return shim.Error(err.Error())
  112.                 }
  113.                 // Add a comma before array members, suppress it for the first array member
  114.                 if bArrayMemberAlreadyWritten == true {
  115.                         buffer.WriteString(",")
  116.                 }
  117.                 buffer.WriteString("{\"Key\":")
  118.                 buffer.WriteString("\"")
  119.                 buffer.WriteString(queryResponse.Key)
  120.                 buffer.WriteString("\"")
  121.  
  122.                 buffer.WriteString(", \"Record\":")
  123.                 // Record is a JSON object, so we write as-is
  124.                 buffer.WriteString(string(queryResponse.Value))
  125.                 buffer.WriteString("}")
  126.                 bArrayMemberAlreadyWritten = true
  127.         }
  128.         buffer.WriteString("]")
  129.  
  130.         fmt.Printf("- getAllCode:\n%s\n", buffer.String())
  131.  
  132.         return shim.Success(buffer.Bytes())
  133. }
  134. //return all the codes from the ledger for the specified range
  135. func (s *SmartContract) getCodesForRange(APIstub shim.ChaincodeStubInterface,args []string) sc.Response {
  136.  
  137.         if(len(args)==2){
  138.           return shim.Error("Incorrect number of arguments. Expecting 2 args")
  139.         }
  140.         startKey := args[0]
  141.         endKey := args[1]
  142.  
  143.         resultsIterator, err := APIstub.GetStateByRange(startKey, endKey)
  144.         if err != nil {
  145.                 return shim.Error(err.Error())
  146.         }
  147.         defer resultsIterator.Close()
  148.  
  149.         // buffer is a JSON array containing QueryResults
  150.         var buffer bytes.Buffer
  151.         buffer.WriteString("[")
  152.  
  153.         bArrayMemberAlreadyWritten := false
  154.         for resultsIterator.HasNext() {
  155.                 queryResponse, err := resultsIterator.Next()
  156.                 if err != nil {
  157.                         return shim.Error(err.Error())
  158.                 }
  159.                 // Add a comma before array members, suppress it for the first array member
  160.                 if bArrayMemberAlreadyWritten == true {
  161.                         buffer.WriteString(",")
  162.                 }
  163.                 buffer.WriteString("{\"Key\":")
  164.                 buffer.WriteString("\"")
  165.                 buffer.WriteString(queryResponse.Key)
  166.                 buffer.WriteString("\"")
  167.  
  168.                 buffer.WriteString(", \"Record\":")
  169.                 // Record is a JSON object, so we write as-is
  170.                 buffer.WriteString(string(queryResponse.Value))
  171.                 buffer.WriteString("}")
  172.                 bArrayMemberAlreadyWritten = true
  173.         }
  174.         buffer.WriteString("]")
  175.  
  176.         fmt.Printf("- getAllCode:\n%s\n", buffer.String())
  177.  
  178.         return shim.Success(buffer.Bytes())
  179. }
  180.  
  181. //return the code from the ledger for the specified timestamp
  182. func (s *SmartContract) getCode(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
  183.  
  184.         if len(args) != 1 {
  185.                 return shim.Error("Incorrect number of arguments. Expecting 1")
  186.         }
  187.  
  188.         codeBytes, _ := APIstub.GetState(args[0])
  189.         return shim.Success(codeBytes)
  190. }
  191. func makeTimestamp() int64 {
  192.     return time.Now().UnixNano() / int64(time.Millisecond)
  193. }
  194. func checkHashLen(hash string) bool{
  195.         if(len(hash)==32){
  196.                 return true
  197.         }
  198.         return false
  199. }
  200.  
  201. // The main function is only relevant in unit test mode.
  202. func main() {
  203.  
  204.         // Create a new Smart Contract
  205.         err := shim.Start(new(SmartContract))
  206.         if err != nil {
  207.                 fmt.Printf("Error creating new Smart Contract: %s", err)
  208.         }
  209. }
Add Comment
Please, Sign In to add comment