我正在按照大理石示例编写自己的链码。但是,putstate在Init函数外部不起作用。 GetState运行正常。我可以在Init函数中获得我声明的状态。如果我尝试调用试图置入另一个新记录的自定义函数,它将返回成功,但是我无法读取该记录。即使我将chaincode_example02.go函数复制到我的chaincode中,它仍然无法正常工作。然后我发现chaincode_example02.go在我的网络中也有同样的问题。有人能帮我吗?谢谢
package main
import (
"encoding/json"
"fmt"
"strconv"
// "github.com/hyperledger/fabric/discovery/support/chaincode"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
type SmartContract struct {
}
func (t *SmartContract) Init(stub shim.ChaincodeStubInterface) pb.Response {
var Aval, Bval int // Asset holdings
// Initialize the chaincode
Aval, err = strconv.Atoi("10")
Bval, err = strconv.Atoi("20")
fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
// Write the state to the ledger
err = stub.PutState("A", []byte(strconv.Itoa(Aval)))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState("B", []byte(strconv.Itoa(Bval)))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
func (t *SmartContract) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
fnc, args := stub.GetFunctionAndParameters()
fmt.Println(" ")
fmt.Println("Invoke, with function - " + fnc)
if fnc == "init" {
return t.Init(stub)
} else if fnc == "invoke" {
return t.invoke(stub)
} else if fnc == "query" {
return t.query(stub, args)
}
return shim.Error(fmt.Sprintf("Invalid function name: %s", fnc))
}
func (t *SmartContract) invoke(stub shim.ChaincodeStubInterface) pb.Response {
var A, B string // Entities
var Aval, Bval int // Asset holdings
var X int // Transaction value
var err error
A = "A"
B = "B"
X = 5
Avalbytes, err := stub.GetState(A)
if err != nil {
return shim.Error("Failed to get state")
}
if Avalbytes == nil {
return shim.Error("Entity not found")
}
Aval, _ = strconv.Atoi(string(Avalbytes))
Bvalbytes, err := stub.GetState(B)
if err != nil {
return shim.Error("Failed to get state")
}
if Bvalbytes == nil {
return shim.Error("Entity not found")
}
Bval, _ = strconv.Atoi(string(Bvalbytes))
// Perform the execution
Aval = Aval - X
Bval = Bval + X
err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
func (t *SmartContract) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var A string // Entities
var err error
A = args[0]
// Get the state from the ledger
Avalbytes, err := stub.GetState(A)
if err != nil {
jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
return shim.Error(jsonResp)
}
if Avalbytes == nil {
jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
return shim.Error(jsonResp)
}
jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
return shim.Success(Avalbytes)
}
func main() {
err := shim.Start(new(SmartContract))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}