美文网首页
Fabric链码开发---helloworld

Fabric链码开发---helloworld

作者: JC86 | 来源:发表于2020-02-29 11:54 被阅读0次

一、编写链码

编写helloworld.go,代码如下。把文件放在fabric-samples/chaincode/helloworld(helloworld需新建)

package main

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

type Helloworld struct {

}

func (t * Helloworld) Init(stub shim.ChaincodeStubInterface) peer.Response{
    args:= stub.GetStringArgs()
    err := stub.PutState(args[0],[]byte(args[1]))
    if err != nil {
        shim.Error(err.Error())
    }
    return shim.Success(nil)
}

func (t *Helloworld) Invoke (stub shim.ChaincodeStubInterface) peer.Response{
    fn, args := stub.GetFunctionAndParameters()

    if fn =="set" {
        return t.set(stub, args)
    }else if fn == "get" {
        return t.get(stub , args)
    }
    return shim.Error("Invoke fn error")
}

func (t *Helloworld) set(stub shim.ChaincodeStubInterface , args []string) peer.Response{
    err := stub.PutState(args[0],[]byte(args[1]))
    if err != nil {
        return shim.Error(err.Error())
    }
    return shim.Success(nil)
}

func (t *Helloworld) get (stub shim.ChaincodeStubInterface, args [] string) peer.Response{

    value, err := stub.GetState(args[0])
    if err != nil {
        return shim.Error(err.Error())
    }

    return shim.Success(value)
}

func main(){
    err := shim.Start(new(Helloworld))
    if err != nil {
        fmt.Println("start error")
    }
}

二、启动网络

  • 进入fabric-samples/chaincode-docker-devmode
  • 执行docker-compose -f docker-compose-simple.yaml up

三、编译并启动链码

# 启动新终端
docker exec -it chaincode bash      
cd helloworld       
# 编译得到helloworld可执行文件
go build
# 启动链码
CORE_PEER_ADDRESS=peer:7052 CORE_CHAINCODE_ID_NAME=mycc:0 ./helloworld

四、操作链码

# 启动新终端
docker exec -it chaincode bash   
# 安装链码
peer chaincode install -p chaincodedev/chaincode/helloworld -n mycc -v 0
# 实例化链码
peer chaincode instantiate -n mycc -v 0 -c '{"Args":["str","HelloWorld"]}' -C myc

# 查询
peer chaincode query -n mycc -c '{"Args":["get","str"]}' -C myc
# 修改
peer chaincode invoke -n mycc -c '{"Args":["set","str","newHelloWorld"]}' -C myc

参考:
Hyperledger Fabric 链码开发实战
HyperLedger Fabric chaincode 开发模式 docker-devmode

相关文章

网友评论

      本文标题:Fabric链码开发---helloworld

      本文链接:https://www.haomeiwen.com/subject/sxtphhtx.html