更新时间:2022-09-16 GMT+08:00
链代码示例(2.0风格)
如下是一个账户转账的链代码示例(2.0风格)仅供安装实例化,若您需要调测请参考Fabric官方示例中的链代码。
package main
import (
"errors"
"fmt"
"strconv"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
// 链码实现
type ABstore struct {
contractapi.Contract
}
// 初始化链码数据,实例化或者升级链码时自动调用
func (t *ABstore) Init(ctx contractapi.TransactionContextInterface, A string, Aval int, B string, Bval int) error {
// 使用println函数输出的信息会记录在链码容器日志中
fmt.Println("ABstore Init")
var err error
fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
// 将状态数据写入账本
err = ctx.GetStub().PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
return err
}
err = ctx.GetStub().PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return err
}
return nil
}
// A转账X给B
func (t *ABstore) Invoke(ctx contractapi.TransactionContextInterface, A, B string, X int) error {
var err error
var Aval int
var Bval int
// 从账本获取状态数据
Avalbytes, err := ctx.GetStub().GetState(A)
if err != nil {
return fmt.Errorf("Failed to get state")
}
if Avalbytes == nil {
return fmt.Errorf("Entity not found")
}
Aval, _ = strconv.Atoi(string(Avalbytes))
Bvalbytes, err := ctx.GetStub().GetState(B)
if err != nil {
return fmt.Errorf("Failed to get state")
}
if Bvalbytes == nil {
return fmt.Errorf("Entity not found")
}
Bval, _ = strconv.Atoi(string(Bvalbytes))
// 执行转账
Aval = Aval - X
Bval = Bval + X
fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
// 将状态数据重新写回账本
err = ctx.GetStub().PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
return err
}
err = ctx.GetStub().PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return err
}
return nil
}
// 账户注销
func (t *ABstore) Delete(ctx contractapi.TransactionContextInterface, A string) error {
// 从账本中删除账户状态
err := ctx.GetStub().DelState(A)
if err != nil {
return fmt.Errorf("Failed to delete state")
}
return nil
}
// 账户查询
func (t *ABstore) Query(ctx contractapi.TransactionContextInterface, A string) (string, error) {
var err error
// 从账本获取状态数据
Avalbytes, err := ctx.GetStub().GetState(A)
if err != nil {
jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
return "", errors.New(jsonResp)
}
if Avalbytes == nil {
jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
return "", errors.New(jsonResp)
}
jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
fmt.Printf("Query Response:%s\n", jsonResp)
return string(Avalbytes), nil
}
func main() {
cc, err := contractapi.NewChaincode(new(ABstore))
if err != nil {
panic(err.Error())
}
if err := cc.Start(); err != nil {
fmt.Printf("Error starting ABstore chaincode: %s", err)
}
}
父主题: Go语言链代码开发