Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- /* Imports
- * 4 utility libraries for formatting, handling bytes, reading and writing JSON, and string manipulation
- * 2 specific Hyperledger Fabric specific libraries for Smart Contracts
- */
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "strconv"
- "time"
- "github.com/hyperledger/fabric/core/chaincode/shim"
- sc "github.com/hyperledger/fabric/protos/peer"
- )
- // Define the Smart Contract structure
- type SmartContract struct {
- }
- // Define the car structure. Structure tags are used by encoding/json library
- type Code struct {
- //TimeStamp int64 `json:"timestamp"`
- HashCode string `json:"HashCode"`
- }
- /*
- * The Init method is called when the Smart Contract is instantiated by the blockchain 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 is called as a result of an application request to run the Smart Contract
- * The calling application program has also specified the particular smart contract function to be called, with arguments
- */
- 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 appropriately
- if function == "init" {
- return s.initCodeLedger(APIstub, args)
- } else if function == "pushCode" {
- return s.pushCode(APIstub, args)
- } else if function == "getAllCode" {
- return s.getAllCode(APIstub)
- } else if function == "getCodesForRange"{
- return s.getCodesForRange(APIstub,args)
- } else if function == "getCode"{
- return s.getCode(APIstub,args)
- }
- return shim.Error("Invalid Smart Contract function name.")
- }
- func (s *SmartContract) initCodeLedger(APIstub shim.ChaincodeStubInterface, args[] string) sc.Response {
- if len(args) == 0 {
- return shim.Error("Incorrect number of arguments. Expecting atlease 1")
- }
- for k:=0;k < len(args);k++{
- fmt.Println("k is ", k)
- hsCode := args[k]
- lenChk:=checkHashLen(hsCode)
- if lenChk==false{
- fmt.Println("Length should be 32" )
- continue
- }
- codeBytes,_ := json.Marshal(hsCode)
- APIstub.PutState(strconv.FormatInt(makeTimestamp(),10), codeBytes)
- fmt.Println("Added: ", k)
- }
- return shim.Success(nil)
- }
- //push single code on the block
- func (s *SmartContract) pushCode(APIstub shim.ChaincodeStubInterface, args[] string) sc.Response {
- hsCode := args[0]
- lenChk:=checkHashLen(hsCode)
- if lenChk==false {
- fmt.Println("Length should be 32" )
- continue
- }
- codeBytes, _ := json.Marshal(hsCode)
- APIstub.PutState(strconv.FormatInt(makeTimestamp(),10), codeBytes)
- return shim.Success(nil)
- }
- //return all the codes from the ledger
- func (s *SmartContract) getAllCode(APIstub shim.ChaincodeStubInterface) sc.Response {
- startKey := "00000000000000000"
- endKey := strconv.FormatInt(makeTimestamp(),10)
- 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 a 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("- getAllCode:\n%s\n", buffer.String())
- return shim.Success(buffer.Bytes())
- }
- //return all the codes from the ledger for the specified range
- func (s *SmartContract) getCodesForRange(APIstub shim.ChaincodeStubInterface,args []string) sc.Response {
- if(len(args)==2){
- return shim.Error("Incorrect number of arguments. Expecting 2 args")
- }
- startKey := args[0]
- endKey := args[1]
- 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 a 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("- getAllCode:\n%s\n", buffer.String())
- return shim.Success(buffer.Bytes())
- }
- //return the code from the ledger for the specified timestamp
- func (s *SmartContract) getCode(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
- if len(args) != 1 {
- return shim.Error("Incorrect number of arguments. Expecting 1")
- }
- codeBytes, _ := APIstub.GetState(args[0])
- return shim.Success(codeBytes)
- }
- func makeTimestamp() int64 {
- return time.Now().UnixNano() / int64(time.Millisecond)
- }
- func checkHashLen(hash string) bool{
- if(len(hash)==32){
- return true
- }
- return false
- }
- // The main function is only relevant in unit test mode.
- func main() {
- // Create a new Smart Contract
- err := shim.Start(new(SmartContract))
- if err != nil {
- fmt.Printf("Error creating new Smart Contract: %s", err)
- }
- }
Add Comment
Please, Sign In to add comment