Created
June 18, 2020 03:27
-
-
Save kctam/f8ddf9d0eeff5b02b4f603202b652497 to your computer and use it in GitHub Desktop.
A testing chaincode to show what happens if more than a transaction acting on a state in a block cycle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
"github.com/hyperledger/fabric/core/chaincode/shim" | |
pb "github.com/hyperledger/fabric/protos/peer" | |
) | |
type TestBlockTime struct { | |
} | |
func (t *TestBlockTime) Init(stub shim.ChaincodeStubInterface) pb.Response { | |
var initValue int | |
initValue = 0 | |
err := stub.PutState("value", []byte(strconv.Itoa(initValue))) | |
if err != nil { | |
return shim.Error(err.Error()) | |
} | |
return shim.Success(nil) | |
} | |
func (t *TestBlockTime) Invoke(stub shim.ChaincodeStubInterface) pb.Response { | |
function, args := stub.GetFunctionAndParameters() | |
if function == "add" { | |
return t.add(stub, args) | |
} else if function == "get" { | |
return t.get(stub) | |
} else if function == "set" { | |
return t.set(stub, args) | |
} | |
return shim.Error("Invalid function") | |
} | |
func (t *TestBlockTime) add(stub shim.ChaincodeStubInterface, args []string) pb.Response { | |
var value, state int | |
var err error | |
if len(args) != 1 { | |
return shim.Error("Only one argument needed.") | |
} | |
value, err = strconv.Atoi(args[0]) | |
if err != nil { | |
return shim.Error("Expecting integer") | |
} | |
stateAsBytes, err := stub.GetState("value") | |
if err != nil { | |
return shim.Error("Failed to get state") | |
} | |
state, _ = strconv.Atoi(string(stateAsBytes)) | |
state = state + value | |
err = stub.PutState("value", []byte(strconv.Itoa(state))) | |
if err != nil { | |
return shim.Error(err.Error()) | |
} | |
return shim.Success(nil) | |
} | |
func (t *TestBlockTime) get(stub shim.ChaincodeStubInterface) pb.Response { | |
stateAsBytes, err := stub.GetState("value") | |
if err != nil { | |
return shim.Error("Failed to get state") | |
} | |
return shim.Success(stateAsBytes) | |
} | |
func (t *TestBlockTime) set(stub shim.ChaincodeStubInterface, args []string) pb.Response { | |
var value int | |
var err error | |
if len(args) != 1 { | |
return shim.Error("Only one argument needed.") | |
} | |
value, err = strconv.Atoi(args[0]) | |
if err != nil { | |
return shim.Error("Expecting integer") | |
} | |
err = stub.PutState("value", []byte(strconv.Itoa(value))) | |
if err != nil { | |
return shim.Error(err.Error()) | |
} | |
return shim.Success(nil) | |
} | |
func main() { | |
err := shim.Start(new(TestBlockTime)) | |
if err != nil { | |
fmt.Printf("Error starting chaincode: %s", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment