Chaincode shim:键的更多值或允许值中的非整数

Chaincode shim: more values for a key or allowing non-integer in the value

在链码初始化期间,可以部署键值对,例如:["a","100", "b", "200"]

不过,我想部署键值对,例如:["a", "100, v1, v2"] 使得 100、v1、v2 是 a 的值。两个注意事项: 1. 值是非整数 2. 值之间用逗号“,”

隔开

这可能吗?

我检查链码 shim:/home/standards/go/src/github.com/hyperledger/fabric/core/chaincode/shim/chaincode.go

函数:

// PutState writes the specified `value` and `key` into the ledger.
func (stub *ChaincodeStub) PutState(key string, value []byte) error {
    return handler.handlePutState(key, value, stub.UUID)

调用 handlePutState(键,值,stub.UUID)。关于如何修改它以使其按预期工作的任何灯?谢谢,

在链代码中,每个状态只能有一个与之关联的值。但是,可以通过将 "one value" 设为列表来模拟多个值。所以你可以这样做

stub.PutState("a",[]byte("100,v1,v2"))

"a" 的状态现在是逗号分隔的列表。当您想要检索这些值时,请执行以下操作:

Avals, err := stub.GetState("a")
AvalsString := string(Avals)
fmt.Println(AvalsString)

应该打印以下字符串

100,v1,v2

如果您需要其中的各个参数,只需将字符串拆分为逗号,然后转换为适当的类型。 Bam,您现在可以存储和检索元素了。

或者,如果您的数据结构比这更复杂,那么将您的数据放入 json 对象中可能是值得的。然后,您可以使用封送处理和解封处理在 []byte(可以直接存储在状态中)和对象(可能更易于使用)之间来回转换。

示例 Json,使用 init 方法,因为它是您提到的方法

type SomeStruct struct {
    AVal   string            `json:"Aval"`
    BVal   []string            `json:"Bval"`
}

func (t *MyChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
    //recieve args ["someStringA","BVal1","Bval2","Bval3"]

    //constructing and storing json object
    myStruct := SomeStruct{
        AVal: args[0],
        BVal: []string{args[1],args[2],args[3]},
    }
    myStructBytes, err := json.Marshal(myStruct)
    _ = err //ignore errors for example
    stub.PutState("myStructKey",myStructBytes)

    //get state back to object
    var retrievedStruct SomeStruct
    retrievedBytes, err := stub.GetState("myStructKey")
    json.Unmarshal(retrievedBytes,retrievedStruct)

    //congratulations, retrievedStruct now contains the data you stored earlier
    return nil,nil
}