hyperledger - 在链代码中维护键以存储值(状态)的正确方法。?

标签 hyperledger hyperledger-fabric smartcontracts

链码基本上将数据存储在键值对(STATE)中。

如果我必须存储学生数据,我必须传递键值,例如1001-{学生信息}。简单地说,我可以创建任意数量的学生。

但问题是如果学生想动态注册。要管理它,学生必须传递唯一的 studentId 或必须创建动态 key 。?

哪个是实现它的正确方法?

谁能帮我理解这个基本流程。?

谢谢

最佳答案

由于您需要确保背书在背书同行之间是一致的,因此最好是客户,例如该应用程序将生成学生 ID 并将其传递到链代码中。沿着这些路线的东西可能是个好方法:

package main

import (
    "encoding/json"
    "fmt"

    "github.com/hyperledger/fabric/core/chaincode/shim"
    "github.com/hyperledger/fabric/protos/peer"
)

// Student
type Person struct {
    ID      string `json:"id"`
    Name    string `json:"name"`
    Faculty string `json:"faculty"`
    Address string `json:"address"`
}

// StudentAction
type StudentAction func(params []string, stub shim.ChaincodeStubInterface) peer.Response

// studentManagement the chaincode interface implementation to manage
// the ledger of person records
type studentManagement struct {
    actions map[string]StudentAction
}

// Init initialize chaincode with mapping between actions and real methods
func (pm *studentManagement) Init(stub shim.ChaincodeStubInterface) peer.Response {
    pm.actions = map[string]StudentAction{
        "addStudent": pm.AddStudent,
    }

    fmt.Println("Chaincode has been initialized")
    fmt.Println("Following actions are available")
    for action := range pm.actions {
        fmt.Printf("\t\t%s\n", action)
    }
    return shim.Success(nil)
}

// Invoke handles chaincode invocation logic, executes actual code
// for given action name
func (pm *studentManagement) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
    actionName, params := stub.GetFunctionAndParameters()

    if action, ok := pm.actions[actionName]; ok {
        return action(params, stub)
    }

    return shim.Error(fmt.Sprintf("No <%s> action defined", actionName))
}

// AddStudent inserts new person into ledger
func (pm *personManagement) AddStudent(params []string, stub shim.ChaincodeStubInterface) peer.Response {
    jsonObj := params[0]
    var student Student

    // Read person info into struct
    json.Unmarshal([]byte(jsonObj), &student)

    // Make uniqueness check 
    val, err := stub.GetState(student.ID)
    if err != nil {
        fmt.Printf("[ERROR] cannot get state, because of %s\n", err)
        return shim.Error(fmt.Sprintf("%s", err))
    }

    if val != nil {
        errMsg := fmt.Sprintf("[ERROR] student already exists, cannot create two accounts with same ID <%d>", student.ID)
        fmt.Println(errMsg)
        return shim.Error(errMsg)
    }

    fmt.Println("Adding new student", person)
    if err = stub.PutState(student.ID, []byte(jsonObj)); err != nil {
        errMsg := fmt.Sprintf("[ERROR] cannot store student record with id <%d>, due to %s", student.ID, err)
        fmt.Println(errMsg)
        return shim.Error(errMsg)
    }
    return shim.Success(nil)
}

现在一旦安装了链码,您就可以尝试通过以下方式使用 peer cli 命令添加新学生:

peer chaincode invoke -o localhost:7050 \
                       -n students1 -v 1.0 -C exampleChannel \
                       -c '{"Args": ["addStudent”, "{ \"id\": \”12345678\”, \"Name\": \”John Doe\”, \”Faculty\”: \”Mathematics\”, \"address\": \”MIT\”}”]}’

当然有SDK就方便多了。

关于hyperledger - 在链代码中维护键以存储值(状态)的正确方法。?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45562918/

相关文章:

docker - 在 Hypeledger Fabric 中重新启动 ca 服务器时出错

hyperledger-fabric - ./startFabric错误 - 背书者客户端无法连接到peer0.org1.example.com :7051: failed to create new connection: context deadline exceeded

go - Hyperledger Fabric V1.0 中日期范围的复合键形成

go - 在 HyperLedger Fabric 中对等节点安装链码

node.js - Hyperledger Fabric 版本 2 : How to query Block Header such as data hash, 使用 Fabric Node SDK 2.2 的先前哈希

blockchain - 在不使用 geth 或 tuffle 或 ganache 的情况下仅使用 EVM API 在区 block 链上部署智能合约?

hyperledger - Hyperledger Fabric 共识服务可以分发吗?

docker - super 账本结构 : Understanding Docker Containers

执行智能合约时的 Solidity 错误消息 : “The called function should be payable if you send value...”

solidity - 如何可靠地返回地址数组?