Fabric:关于链码的编写及部署的问题记录

2024-08-21 14:36

本文主要是介绍Fabric:关于链码的编写及部署的问题记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本篇主要记录里在链码的编写及配置过程中遇到的问题及解决方法。

1. Init方法

  在Hyperledger Fabric中,链码的Init()方法是一个可选的方法,它主要用于链码实例化时执行一些初始化操作。如果希望账本的初始化方法可以在链码部署完成时执行,则可以将相关方法的执行放到Init()方法中。举例如下:

func (s *SmartContract) Init(ctx contractapi.TransactionContextInterface) error {//账本初始化操作err := s.InitLedger(ctx)if err != nil {return err}return nil
}
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
}

但关于这种写法,有以下几点需要说明:

  • 这种利用Init()方法进行账本初始化的操作不一定能生效,在用Fabric-gateway-go调用链码时能生效,但使用Peer CLI调用链码时不生效,仍然需要使用peer invoke命令执行InitLedger方法。原因暂时不明。
  • 虽然在fabric-contract-api-go的官方文档中的Init方法的返回类型为peer.Response。假如按照这种返回类型编写Init写法,具体如下:
func (s *SmartContract) Init(ctx contractapi.TransactionContextInterface) peer.Response {err := s.InitLedger(ctx)if err != nil {return peer.Response{Status:500,Message: "账本初始化失败",}}return peer.Response{Status:200,Message: "账本初始化成功",}
}

则在链码部署时会提示如下错误: Error creating business chaincode: Cannot use metadata. Metadata did not match schema:components.schemas..required: Array must have at least 1 items(需要进入链码所在的docker容器中才能该错误提示信息)

2. 链码返回类型

如果希望链码返回由多个JSON串组成的数组时,如果用[][]byte,则可能产生Error: endorsement failure during query. response: status:500 message:"Error handling success response. Value did not match schema:\n1. return: Invalid type. Expected: array, given: string" 。这种情况下,最后将返回类型改成[]string。具体案例如下:

func (s *SmartContract) GetTableAllItems(ctx contractapi.TransactionContextInterface, tableName string) ([]string, error) {query := `{"selector":{"docType":"` + tableName + `"}}`resultsIterator, err := ctx.GetStub().GetQueryResult(query)if err != nil {return nil, err}defer resultsIterator.Close()var tableItems []stringfor resultsIterator.HasNext() {queryResponse, err := resultsIterator.Next()if err != nil {return nil, err}tableItems = append(tableItems, string(queryResponse.Value))}return tableItems, nil
}

3. Struct、byte和string等的互相转换

  在Hyperledger Fabric的链码编写中,通常都遇到JSON串的编码、解码等问题,这里就涉及到很多bytestring及其数组的相互转换问题。这里就以简单的go语言代码为例做一个简单的说明。

3.1 Struct转化为JSON串和string类型

Go语言中用[]byte表示JSON串。从Struct变量到JSON串和string类型的转换举例如下:

package mainimport ("encoding/json""fmt"
)type User struct {UserID string `json:"customerID"`Name   string `json:"name"`Age    int    `json:"age"`Email  string `json:"email"`
}func main() {usersList := []User{{UserID: "user1", Name: "Alice", Age: 25, Email: "alice@example.com"},{UserID: "user2", Name: "Bob", Age: 30, Email: "bob@example.com"},{UserID: "user3", Name: "Charlie", Age: -5, Email: "charlie@example.com"},{UserID: "user4", Name: "David", Age: 40, Email: "david@@example.com"},{UserID: "user5", Name: "Eve", Age: 35, Email: "eve@example,com"},}//将Struct数组转换成JSON串,返回类型为[]byteuserListJson, err := json.Marshal(usersList)if err != nil {fmt.Println(err)}//将[]byte转换为stringfmt.Println(string(userListJson))//将单独的Struct变量转换成JSON串,返回类型仍然为[]byteuserJson, err := json.Marshal(usersList[0])fmt.Println(string(userJson))
}

代码执行结果如下:

[{"customerID":"user1","name":"Alice","age":25,"email":"alice@example.com"},{"customerID":"user2","name":"Bob","age":30,"email":"bob@example.com"},{"customerID":"user3","name":"Charlie","age":-5,"email":"charlie@example.com"},{"customerID":"user4","name":"David","age":40,"email":"david@@example.com"},{"customerID":"user5","name":"Eve","age":35,"email":"eve@example,com"}]
{"customerID":"user1","name":"Alice","age":25,"email":"alice@example.com"}

从上述代码中可以看到,无论是单独的Struct变量还是Struct变量组成的数组,使用json.Marshal()方法生成的JSON串都是[]byte类型。

3.2 JSON串转化为Struct变量

这里先用string类型保存JSON串,再转化为Struct变量。其具体代码如下:

package mainimport ("encoding/json""fmt"
)type User struct {UserID    string `json:"customerID"`UserName  string `json:"name"`UserAge   int    `json:"age"`UserEmail string `json:"email"`
}func main() {userString := `[{"customerID":"user1","name":"Alice","age":25,"email":"alice@example.com"},{"customerID":"user2","name":"Bob","age":30,"email":"bob@example.com"}]`userJSON := []byte(userString)var user []Usererr := json.Unmarshal(userJSON, &user)if err != nil {fmt.Println(err)}fmt.Println(user)
}

其代码执行结果如下:

[{user1 Alice 25 alice@example.com} {user2 Bob 30 bob@example.com}]

3.3 json.Indent方法

在Go语言中,json.Indent是一个非常有用的函数,用于将原本压缩或者未格式化的JSON数据进行缩进处理,使其更加易读。它将JSON数据格式化为带有缩进和换行的形式,方便进行调试或展示。

package mainimport ("bytes""encoding/json""fmt"
)func main() {userString := `[{"customerID":"user1","name":"Alice","age":25,"email":"alice@example.com"},{"customerID":"user2","name":"Bob","age":30,"email":"bob@example.com"}]`userJSON := []byte(userString)var prettyJSON bytes.Buffererr := json.Indent(&prettyJSON, userJSON, "", "  ")if err != nil {fmt.Println(err)}fmt.Println(prettyJSON.String())
}

其代码执行结果如下:

[{"customerID": "user1","name": "Alice","age": 25,"email": "alice@example.com"},{"customerID": "user2","name": "Bob","age": 30,"email": "bob@example.com"}
]

这篇关于Fabric:关于链码的编写及部署的问题记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1093438

相关文章

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Zabbix在MySQL性能监控方面的运用及最佳实践记录

《Zabbix在MySQL性能监控方面的运用及最佳实践记录》Zabbix通过自定义脚本和内置模板监控MySQL核心指标(连接、查询、资源、复制),支持自动发现多实例及告警通知,结合可视化仪表盘,可有效... 目录一、核心监控指标及配置1. 关键监控指标示例2. 配置方法二、自动发现与多实例管理1. 实践步骤

Kotlin Map映射转换问题小结

《KotlinMap映射转换问题小结》文章介绍了Kotlin集合转换的多种方法,包括map(一对一转换)、mapIndexed(带索引)、mapNotNull(过滤null)、mapKeys/map... 目录Kotlin 集合转换:map、mapIndexed、mapNotNull、mapKeys、map

MySQL 主从复制部署及验证(示例详解)

《MySQL主从复制部署及验证(示例详解)》本文介绍MySQL主从复制部署步骤及学校管理数据库创建脚本,包含表结构设计、示例数据插入和查询语句,用于验证主从同步功能,感兴趣的朋友一起看看吧... 目录mysql 主从复制部署指南部署步骤1.环境准备2. 主服务器配置3. 创建复制用户4. 获取主服务器状态5

nginx中端口无权限的问题解决

《nginx中端口无权限的问题解决》当Nginx日志报错bind()to80failed(13:Permissiondenied)时,这通常是由于权限不足导致Nginx无法绑定到80端口,下面就来... 目录一、问题原因分析二、解决方案1. 以 root 权限运行 Nginx(不推荐)2. 为 Nginx

解决1093 - You can‘t specify target table报错问题及原因分析

《解决1093-Youcan‘tspecifytargettable报错问题及原因分析》MySQL1093错误因UPDATE/DELETE语句的FROM子句直接引用目标表或嵌套子查询导致,... 目录报js错原因分析具体原因解决办法方法一:使用临时表方法二:使用JOIN方法三:使用EXISTS示例总结报错原

Windows环境下解决Matplotlib中文字体显示问题的详细教程

《Windows环境下解决Matplotlib中文字体显示问题的详细教程》本文详细介绍了在Windows下解决Matplotlib中文显示问题的方法,包括安装字体、更新缓存、配置文件设置及编码調整,并... 目录引言问题分析解决方案详解1. 检查系统已安装字体2. 手动添加中文字体(以SimHei为例)步骤

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

nginx 负载均衡配置及如何解决重复登录问题

《nginx负载均衡配置及如何解决重复登录问题》文章详解Nginx源码安装与Docker部署,介绍四层/七层代理区别及负载均衡策略,通过ip_hash解决重复登录问题,对nginx负载均衡配置及如何... 目录一:源码安装:1.配置编译参数2.编译3.编译安装 二,四层代理和七层代理区别1.二者混合使用举例

golang程序打包成脚本部署到Linux系统方式

《golang程序打包成脚本部署到Linux系统方式》Golang程序通过本地编译(设置GOOS为linux生成无后缀二进制文件),上传至Linux服务器后赋权执行,使用nohup命令实现后台运行,完... 目录本地编译golang程序上传Golang二进制文件到linux服务器总结本地编译Golang程序