Hyperledger Fabric 开发——开发用户链码

本文详细介绍了如何在Hyperledger Fabric中开发链码,包括Go语言编写链码的基本结构、Init和Invoke函数的使用、链码方法编写套路以及链码编写中应避免的禁忌,帮助开发者更好地理解智能合约的实现。
摘要由CSDN通过智能技术生成

前言

本系列文章代码均为Go语言。

链码文件 Chaincode.go 的基本结构

首先,我们来看一个示例代码。所有的链码都含有此基本结构

package main

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

type SimpleChaincode struct {
   
}

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
   
	return shim.Success(nil)
}

func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
   
	return shim.Success(nil)
}

func main() {
   
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
   
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

下面通过 fabric-samples 中的 chaincode 案例 sacc.go 来学习一下 chaincode 的各个部分以及编写。

  1. 导入资源包与定义结构体

首先导入fmt、shim、protos包。

Chaincode 接口定义了 Init 和 Invoke 函数,Shim 包定义了 Success、Error 等常用方法,shim 包的ChaincodeStubInterface 接口提供了一组方法,通过该组方法可以非常方便的操作账本数据。

详细说明请参照官方文档:

  • https://pkg.go.dev/github.com/hyperledger/fabric/core/chaincode/shim?tab=doc#ChaincodeStubInterface
  • https://pkg.go.dev/github.com/hyperledger/fabric/protos/peer?tab=doc

接下来定义一个属性为空的结构体 SimpleAsset 作为链码方法的接收参数。

package main

import (
	"fmt"

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

// SimpleAsset implements a simple chaincode to manage an asset
type SimpleAsset struct {
   
}
  1. Init 函数

Init 函数用于初始化链码。在链码实例化和升级的时候都会调用 Init方法。

链码初始化的时候,调用了 ChaincodeStubInterface.GetStringArgs 函数来获取初始化时输入的参数。这个例子中,我们期望传入两个参数,作为一个key/value对。接下来,将key/value作为 ChaincodeStubInterface.PutState 的参数,如果 shim 向客户端返回正确消息则表明初始化成功。

// Init is called during chaincode instantiation to initialize any
// data. Note that chaincode upgrade also calls this function to reset
// or to migrate data.
func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response {
   
	// Get the args from the transaction proposal
	args := stub.GetStringArgs()
	if len(args) != 2 {
   
		return shim.Error("Incorrect arguments. Expecting a key and a value")
	}

	// Set up any variables or assets here by calling stub.PutState()

	// We store the key and the value on the ledger
	err := stub.PutState(args[0], []byte(args[1]))
	if err != nil {
   
		return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0]))
	}
	return shim.Success
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值