前面废话不多说了,链码是什么懂的都懂
资产转移链码
这个应用是一个基础的样例链码,这个链码可以产生一个账本(这个账本能创建资产,读,更新,删除资产,检查是否一个资产存在,转移资产)
为你的代码选个位置
就在home目录下面创建即可,并建立链码go文件(到时候把代码放进去)
// atcc is shorthand for asset transfer chaincode
mkdir atcc && cd atcc
go mod init atcc
touch atcc.go
接下来是构建链码的几个模块函数
内务处理(housekeeping)
也就是给链码输入进一些必要的依赖
我们输入fabric合约api的包并且定义我们的samrtcontract
导入链码依赖包:
package main
import (
"fmt"
"log"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
// SmartContract provides functions for managing an Asset(智能合约提供的为了管理资产的函数)
type SmartContract struct {
contractapi.Contract
}
接下来,添加一个结构Asset
来表示在账本上的简单的资产
// Asset describes basic details of what makes up a simple asset
type Asset struct {
ID string `json:"ID"`
Color string `json:"color"`
Size int `json:"size"`
Owner string `json:"owner"`
AppraisedValue int `json:"appraisedValue"`
}
建立链码
用InitLedger
函数来让账本有些基础数据
// InitLedger adds a base set of assets to the ledger(这个函数把一系列基础的资产加入到账本)
func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
assets := []Asset{
{
ID: "asset1", Color: "blue", Size: 5, Owner: "Tomoko", AppraisedValue: 300},
{
ID: "asset2", Color: "red", Size: 5, Owner: "Brad", AppraisedValue: 400},
{
ID: "asset3", Color: "green", Size: 10, Owner: "Jin Soo", AppraisedValue: 500},
{
ID: "asset4", Color: "yellow", Size: 10, Owner: "Max", AppraisedValue: 600},
{
ID: "asset5", Color: "black", Size: 15, Owner: "Adriana", AppraisedValue: 700},
{
ID: "asset6", Color: "white", Size: 15, Owner: "Michel", AppraisedValue: 800},
}
for _, asset := range assets {
assetJSON, err := json.Marshal(asset)
if err != nil {
return err
}
err = ctx.GetStub().PutState(asset.ID, assetJSON)
if err != nil {
return fmt.Errorf("failed to put to world state. %v", err)
}
}
return nil
}
接下来写个函数来在账本上面创造一个还不存在的资产。写链码的时候,检查一下在账本上存在那些东西比直接操作要好。
// CreateAsset issues a new asset to the world state with given details.(函数发布一个新的资产到世界状态)
func (s *SmartContract) CreateAsset(ctx contractapi.TransactionContextInterface, id string, color string, size int, owner string, appraisedValue int