区块链系统开发测试----链码部署开发、系统开发验证

2024-05-28 23:52

本文主要是介绍区块链系统开发测试----链码部署开发、系统开发验证,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一.检查配置环境

检查虚拟机环境,确保有正在运行的Hyperledger Fabric区块链,并且其中chaincode_basic、credit_chaincode链码可以正常调用

查看chaincode_basic、credit_chaincode链码调用

二.开发征信链码代码 

基于现有征信链码,开发征信链码的升级版,使用chaincode-init文件夹中的基础链码模板,创建完善其中lib目录以及index.js内容,在lib中创建CreditPlusContract对象,在对象中添加createCreditSubjectPlus功能,实现征信主体的保存,定义subject变量属性包括(key:征信主体主键,  organizationName:征信主体评价机构名, type:评价类型,score:征信积分,creator:创建人,datetime:评价时间),其中属性除score外其余都为string类型。将subject内容上链保存  

在链码中添加征信主体查询功能(queryCreditSubjectPlus),要求能够查询所有主体内容(包括:key:征信主体主键,  organizationName:征信主体评价机构名, type:评价类型,score:征信积分,creator:创建人,datetime:评价时间)

'use strict';
const { Contract } = require("fabric-contract-api");
class CreditPlusContract extends Contract {async createCreditSubjectPlus(ctx, key, organizationName, type, creator, datetime) {console.info('=== START:创建征信主体 ===');const subject = {key: key,organizationName: organizationName,type: type,score: 0,creator: creator,datetime: datetime};await ctx.stub.putState(key, Buffer.from(JSON.stringify(subject)));console.info('=== END:创建征信主体 ===');return subject;}// 查询征信主体async queryCreditSubjectPlus(ctx, subjectKey) {console.info('=== START : 查询征信主体 ===');const bytes = await ctx.stub.getState(subjectKey);if (!bytes || bytes.length === 0) {const msg = `${subjectKey} 征信主体不存在`;console.warn(msg);throw new Error(msg);}const subject = JSON.parse(bytes.toString());console.info('=== END : 查询征信主体 ===');return subject;}}module.exports = CreditPlusContract;

 在链码结构中test目录中添加对于createCreditSubjectPlus以及QueryCreditSubjectPlus功能的单元测试,提交测试代码和验证结果。

'use strict';
const sinon = require('sinon');
const chai = require('chai');
const sinonChai = require('sinon-chai');
const expect = chai.expect;
chai.use(sinonChai);
let assert = sinon.assert;
const { Context } = require('fabric-contract-api');
const { ChaincodeStub, ClientIdentity } = require('fabric-shim');
const CreditPlusContract = require('../lib/creditContract');
describe('Credit Chaincode Test', () => {let stub, ctx, ClientId;beforeEach(() => {ctx = new Context();stub = sinon.createStubInstance(ChaincodeStub);stub.getMspID.returns('Org1');ctx.setChaincodeStub(stub);ClientId = sinon.createStubInstance(ClientIdentity);stub.putState.callsFake((key, value) => {if (!stub.states) {stub.states = {};}stub.states[key] = value;});stub.getState.callsFake(async (key) => {let ret;if (stub.states) {ret = stub.states[key];}return Promise.resolve(ret);});stub.deleteState.callsFake(async (key) => {if (stub.states) {delete stub.states[key];}});});describe('Test CreditSubject function', () => {it('should return success on createCreditSubject', async () => {let creditContract = new CreditPlusContract();let creditSubject = await creditContract.createCreditSubjectPlus(ctx, "A001", "My Company", "Company","Admin","2024-05-28 14:35:00");let scroe = creditSubject.score;expect(scroe).to.equals(0);});it('should return success on queryCreditSubject', async () => {let creditContract = new CreditPlusContract();await creditContract.createCreditSubjectPlus(ctx, "A001", "My Company", "Company", "Admin", "2024-05-28 14:35:00");let creditSubject = await creditContract.queryCreditSubjectPlus(ctx, "A001");let name = creditSubject.organizationName;expect(name).to.equals("My Company");});});
})

测试代码:

 

三.部署征信链码

在虚拟机指定Hyperledger Fabric中实现对应链码的部署并验证部署情况。

将链码名修改切credit_chaincode_plus,删除node_modules目录以及对应package-lock.json文件,上传至服务器chaincode目录下:

打包测试:

export FABRIC_CFG_PATH=${PWD}/configpeer lifecycle chaincode package ./chaincode/credit_chaincode_plus.tar.gz --path ./chaincode/credit_chaincode_plus --lang node --label credit_chaincode_plus_1.0

 

查看打包结果:

安装链码:运行以下进入fabric-cli容器:

docker exec -it fabric-cli bash

1. 在org1中安装:运行以下链码安装:

. scripts/set-env.sh 1 0 7051
peer lifecycle chaincode install chaincode/credit_chaincode_plus.tar.gz

 

2. 在org2中安装,运行以下链码安装:

. scripts/set-env.sh 2 0 9051
peer lifecycle chaincode install chaincode/credit_chaincode_plus.tar.gz

 

3. 查看安装情况

peer lifecycle chaincode queryinstalled

 

批准链码
org1批准链码

1. 设置链码环境变量

export CC_PACKAGE_ID=credit_chaincode_plus_1.0:9415a0be8812a91c2e510619a4d2a6a5cd06a8cf8f9cef96ee4eec2f456ab7ec

2. 设置Org1环境变量

. scripts/set-env.sh 1 0 7051

3.批准链码

peer lifecycle chaincode approveformyorg -o orderer.example.com:7050 --ordererTLSHostnameOverride orderer.example.com --channelID $CHANNEL_NAME --name credit_chaincode_plus --version 1.0 --package-id $CC_PACKAGE_ID --sequence 1 --tls --cafile $ORDERER_CA

 

1. 设置Org2环境变量

. scripts/set-env.sh 2 0 9051

2.批准链码

peer lifecycle chaincode approveformyorg -o orderer.example.com:7050 --ordererTLSHostnameOverride orderer.example.com --channelID $CHANNEL_NAME --name credit_chaincode_plus --version 1.0 --package-id $CC_PACKAGE_ID --sequence 1 --tls --cafile $ORDERER_CA

 

检查提交准备

peer lifecycle chaincode checkcommitreadiness --channelID $CHANNEL_NAME --name credit_chaincode_plus --version 1.0 --sequence 1 --tls --cafile $ORDERER_CA --output json

 

提交链码

peer lifecycle chaincode commit -o orderer.example.com:7050 --ordererTLSHostnameOverride orderer.example.com --channelID $CHANNEL_NAME --name credit_chaincode_plus --version 1.0 --sequence 1 --tls --cafile $ORDERER_CA --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles $PEER0_ORG1_CA --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles $PEER0_ORG2_CA

 

查询提交的链码

peer lifecycle chaincode querycommitted --channelID $CHANNEL_NAME --name credit_chaincode_plus --tls --cafile $ORDERER_CA

 

查看运行镜像形成容器情况

docker logs -f b1ddd21303a5

 

调用createCreditSubject功能

peer chaincode invoke -o orderer.example.com:7050 --tls --cafile $ORDERER_CA --channelID $CHANNEL_NAME --name credit_chaincode_plus --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles $PEER0_ORG1_CA --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles $PEER0_ORG2_CA -c '{"function":"createCreditSubjectPlus", "Args":["A001", "My Company", "Company","Admin","2024-05-28 14:35:00"]}'

 

调用queryCreditSubject功能

peer chaincode query -C $CHANNEL_NAME --name credit_chaincode_plus -c '{"function":"queryCreditSubjectPlus","Args":["A001"]}'

 

四.部署删除和更新代码 

在链码中添加DeleteCreditSubject,实现按subject变量的key属性删除数据功能

在链码中添加UpdateSubjectScore功能,实现按key更新subject,更新subject变量中的score

'use strict';const { Contract } = require("fabric-contract-api");class CreditPlusContract extends Contract {async createCreditSubjectPlus(ctx, key, organizationName, type, creator, datetime) {console.info('=== START:创建征信主体 ===');const subject = {key: key,organizationName: organizationName,type: type,score: 0,creator: creator,datetime: datetime};await ctx.stub.putState(key, Buffer.from(JSON.stringify(subject)));console.info('=== END:创建征信主体 ===');return subject;}// 查询征信主体async queryCreditSubjectPlus(ctx, subjectKey) {console.info('=== START : 查询征信主体 ===');const bytes = await ctx.stub.getState(subjectKey);if (!bytes || bytes.length === 0) {const msg = `${subjectKey} 征信主体不存在`;console.warn(msg);throw new Error(msg);}const subject = JSON.parse(bytes.toString());console.info('=== END : 查询征信主体 ===');return subject;}async deleteCreditSubject(ctx, id) {const exists = await this.creditSubjectExists(ctx, id);if (!exists) {throw new Error(`The asset ${id} does not exist`);}return ctx.stub.deleteState(id);}async creditSubjectExists(ctx, id) {const assetJSON = await ctx.stub.getState(id);return assetJSON && assetJSON.length > 0;}async updateSubjectScore(ctx,subjectKey,inputScore) {const exists = await this.creditSubjectExists(ctx,subjectKey);if (!exists) {throw new Error(`The credit subject ${subjectKey} does not exist`);}const bytes = await ctx.stub.getState(subjectKey);if (!bytes || bytes.length ===0){const msg = `${subjectKey} 征信主体不存在`;console.warn(msg)throw new Error (msg);}var subject = JSON.parse(bytes.toString());subject.score=inputScore;return ctx.stub.putState(subjectKey, Buffer.from(JSON.stringify(subject)));}}module.exports = CreditPlusContract;

在链码结构中test目录中添加对于DeleteCreditSubject以及UpdateSubjectScore功能的单元测试 

 

'use strict';
const sinon = require('sinon');
const chai = require('chai');
const sinonChai = require('sinon-chai');
const expect = chai.expect;
chai.use(sinonChai);
let assert = sinon.assert;
const { Context } = require('fabric-contract-api');
const { ChaincodeStub, ClientIdentity } = require('fabric-shim');
const CreditPlusContract = require('../lib/creditContract');
describe('Credit Chaincode Test', () => {let stub, ctx, ClientId;beforeEach(() => {ctx = new Context();stub = sinon.createStubInstance(ChaincodeStub);stub.getMspID.returns('Org1');ctx.setChaincodeStub(stub);ClientId = sinon.createStubInstance(ClientIdentity);stub.putState.callsFake((key, value) => {if (!stub.states) {stub.states = {};}stub.states[key] = value;});stub.getState.callsFake(async (key) => {let ret;if (stub.states) {ret = stub.states[key];}return Promise.resolve(ret);});stub.deleteState.callsFake(async (key) => {if (stub.states) {delete stub.states[key];}});});describe('Test CreditSubject function', () => {it('should return success on createCreditSubject', async () => {let creditContract = new CreditPlusContract();let creditSubject = await creditContract.createCreditSubjectPlus(ctx, "A001", "My Company", "Company","Admin","2024-05-28 14:35:00");let scroe = creditSubject.score;expect(scroe).to.equals(0);});it('should return success on queryCreditSubject', async () => {let creditContract = new CreditPlusContract();await creditContract.createCreditSubjectPlus(ctx, "A001", "My Company", "Company", "Admin", "2024-05-28 14:35:00");let creditSubject = await creditContract.queryCreditSubjectPlus(ctx, "A001");let name = creditSubject.organizationName;expect(name).to.equals("My Company");});it('should return sucess on DeleteCreditSubject', async () => {let creditContract = new CreditPlusContract();await creditContract.createCreditSubjectPlus(ctx, "A001", "My Company", "Company", "Admin", "2024-05-28 14:35:00");await creditContract.deleteCreditSubject(ctx,"A001");let ret = await stub.getState('A001');expect(ret).to.equal(undefined);});it('should return sucess on updateSubjectScore', async () => {let creditContract = new CreditPlusContract();await creditContract.createCreditSubjectPlus(ctx, "A001", "My Company", "Company", "Admin", "2024-05-28 14:35:00");await creditContract.updateSubjectScore(ctx, "A001",10);let ret = JSON.parse(await stub.getState('A001'));expect(ret.score).to.eql(10);});});
})

测试代码:

 

五.更新部署征信链码

在链码中重新部署开发链码,实现链码更新(要求version、sequence有迭代痕迹)

打包测试:

export FABRIC_CFG_PATH=${PWD}/configpeer lifecycle chaincode package ./chaincode/credit_chaincode_plus.tar.gz --path ./chaincode/credit_chaincode_plus --lang node --label credit_chaincode_plus_1.1

 

安装链码
运行以下进入fabric-cli容器:

docker exec -it fabric-cli bash

1. 在org1中安装 | 运行以下链码安装:

. scripts/set-env.sh 1 0 7051
peer lifecycle chaincode install chaincode/credit_chaincode_plus.tar.gz

 

2. 在org2中安装
运行以下链码安装:

. scripts/set-env.sh 2 0 9051
peer lifecycle chaincode install chaincode/credit_chaincode_plus.tar.gz

 

3. 查看安装情况

peer lifecycle chaincode queryinstalled

 

三.批准链码
org1批准链码

设置链码环境变量

export CC_PACKAGE_ID=credit_chaincode_plus_1.1:a7d65de21f706c25029b84cbbf7de2163d06d9b8e9fc33fd20a5a59cc3a18b01

2. 设置Org1环境变量

. scripts/set-env.sh 1 0 7051

3.批准链码

peer lifecycle chaincode approveformyorg -o orderer.example.com:7050 --ordererTLSHostnameOverride orderer.example.com --channelID $CHANNEL_NAME --name credit_chaincode_plus --version 1.1 --package-id $CC_PACKAGE_ID --sequence 2 --tls --cafile $ORDERER_CA

 

1. 设置Org2环境变量

. scripts/set-env.sh 2 0 9051

2.批准链码

peer lifecycle chaincode approveformyorg -o orderer.example.com:7050 --ordererTLSHostnameOverride orderer.example.com --channelID $CHANNEL_NAME --name credit_chaincode_plus --version 1.1 --package-id $CC_PACKAGE_ID --sequence 2 --tls --cafile $ORDERER_CA

 

检查提交准备

peer lifecycle chaincode checkcommitreadiness --channelID $CHANNEL_NAME --name credit_chaincode_plus --version 1.1 --sequence 2 --tls --cafile $ORDERER_CA --output json

 

提交链码

peer lifecycle chaincode commit -o orderer.example.com:7050 --ordererTLSHostnameOverride orderer.example.com --channelID $CHANNEL_NAME --name credit_chaincode_plus --version 1.1 --sequence 2 --tls --cafile $ORDERER_CA --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles $PEER0_ORG1_CA --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles $PEER0_ORG2_CA

 

查询提交的链码

peer lifecycle chaincode querycommitted --channelID $CHANNEL_NAME --name credit_chaincode_plus --tls --cafile $ORDERER_CA

 

查看运行镜像形成容器情况

docker logs -f b1ddd21303a5

 

调用createCreditSubject功能

peer chaincode invoke -o orderer.example.com:7050 --tls --cafile $ORDERER_CA --channelID $CHANNEL_NAME --name credit_chaincode_plus --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles $PEER0_ORG1_CA --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles $PEER0_ORG2_CA -c '{"function":"createCreditSubjectPlus", "Args":["A001", "My Company", "Company","Admin","2024-05-28 14:35:00"]}'

调用queryCreditSubject功能

peer chaincode query -C $CHANNEL_NAME --name credit_chaincode_plus -c '{"function":"queryCreditSubjectPlus","Args":["A001"]}'

调用deleteCreditSubject功能

peer chaincode invoke -o orderer.example.com:7050 --tls --cafile $ORDERER_CA --channelID $CHANNEL_NAME --name credit_chaincode_plus --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles $PEER0_ORG1_CA --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles $PEER0_ORG2_CA -c '{"function":"deleteCreditSubject", "Args":["A001"]}'

 

调用updateSubjectScore功能(这边如果嫌麻烦的话可以更新功能之后再调用删除功能)

peer chaincode invoke -o orderer.example.com:7050 --tls --cafile $ORDERER_CA --channelID $CHANNEL_NAME --name credit_chaincode_plus --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles $PEER0_ORG1_CA --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles $PEER0_ORG2_CA -c '{"function":"updateSubjectScore", "Args":["A002","10"]}'

 

 


 

这篇关于区块链系统开发测试----链码部署开发、系统开发验证的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

python管理工具之conda安装部署及使用详解

《python管理工具之conda安装部署及使用详解》这篇文章详细介绍了如何安装和使用conda来管理Python环境,它涵盖了从安装部署、镜像源配置到具体的conda使用方法,包括创建、激活、安装包... 目录pytpshheraerUhon管理工具:conda部署+使用一、安装部署1、 下载2、 安装3

在C#中获取端口号与系统信息的高效实践

《在C#中获取端口号与系统信息的高效实践》在现代软件开发中,尤其是系统管理、运维、监控和性能优化等场景中,了解计算机硬件和网络的状态至关重要,C#作为一种广泛应用的编程语言,提供了丰富的API来帮助开... 目录引言1. 获取端口号信息1.1 获取活动的 TCP 和 UDP 连接说明:应用场景:2. 获取硬

JAVA系统中Spring Boot应用程序的配置文件application.yml使用详解

《JAVA系统中SpringBoot应用程序的配置文件application.yml使用详解》:本文主要介绍JAVA系统中SpringBoot应用程序的配置文件application.yml的... 目录文件路径文件内容解释1. Server 配置2. Spring 配置3. Logging 配置4. Ma

2.1/5.1和7.1声道系统有什么区别? 音频声道的专业知识科普

《2.1/5.1和7.1声道系统有什么区别?音频声道的专业知识科普》当设置环绕声系统时,会遇到2.1、5.1、7.1、7.1.2、9.1等数字,当一遍又一遍地看到它们时,可能想知道它们是什... 想要把智能电视自带的音响升级成专业级的家庭影院系统吗?那么你将面临一个重要的选择——使用 2.1、5.1 还是

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

高效管理你的Linux系统: Debian操作系统常用命令指南

《高效管理你的Linux系统:Debian操作系统常用命令指南》在Debian操作系统中,了解和掌握常用命令对于提高工作效率和系统管理至关重要,本文将详细介绍Debian的常用命令,帮助读者更好地使... Debian是一个流行的linux发行版,它以其稳定性、强大的软件包管理和丰富的社区资源而闻名。在使用

k8s部署MongDB全过程

《k8s部署MongDB全过程》文章介绍了如何在Kubernetes集群中部署MongoDB,包括环境准备、创建Secret、创建服务和Deployment,并通过Robo3T工具测试连接... 目录一、环境准备1.1 环境说明1.2 创建 namespace1.3 创建mongdb账号/密码二、创建Sec

Java中的Opencv简介与开发环境部署方法

《Java中的Opencv简介与开发环境部署方法》OpenCV是一个开源的计算机视觉和图像处理库,提供了丰富的图像处理算法和工具,它支持多种图像处理和计算机视觉算法,可以用于物体识别与跟踪、图像分割与... 目录1.Opencv简介Opencv的应用2.Java使用OpenCV进行图像操作opencv安装j

Ubuntu系统怎么安装Warp? 新一代AI 终端神器安装使用方法

《Ubuntu系统怎么安装Warp?新一代AI终端神器安装使用方法》Warp是一款使用Rust开发的现代化AI终端工具,该怎么再Ubuntu系统中安装使用呢?下面我们就来看看详细教程... Warp Terminal 是一款使用 Rust 开发的现代化「AI 终端」工具。最初它只支持 MACOS,但在 20

windows系统下shutdown重启关机命令超详细教程

《windows系统下shutdown重启关机命令超详细教程》shutdown命令是一个强大的工具,允许你通过命令行快速完成关机、重启或注销操作,本文将为你详细解析shutdown命令的使用方法,并提... 目录一、shutdown 命令简介二、shutdown 命令的基本用法三、远程关机与重启四、实际应用