
介绍
上篇内容中我们看到了chaincode
中包含了以下几个方法:
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := APIstub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger appropriately
if function == "queryCar" {
return s.queryCar(APIstub, args)
} else if function == "initLedger" {
return s.initLedger(APIstub)
} else if function == "createCar" {
return s.createCar(APIstub, args)
} else if function == "queryAllCars" {
return s.queryAllCars(APIstub)
} else if function == "changeCarOwner" {
return s.changeCarOwner(APIstub, args)
}
return shim.Error("Invalid Smart Contract function name.")
}
queryCar: 查询指定Car的信息
initLedger:初始化数据,在启动网络的时候,通过invoke指令已经调用了。上篇内容讲过了。
createCar:创建操作
queryAllCars:查询索引范围内的信息
changeCarOwner:改变所有者。
invoke 一般用来 创建 和 更新。query 一般用来查询。
解析 invoke.js
'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
* Chaincode Invoke
*/
var Fabric_Client = require('fabric-client');
var path = require('path');
var util = require('util');
var os = require('os');
//
var fabric_client = new Fabric_Client();
// setup the fabric network
var channel = fabric_client.newChannel('mychannel');
var peer = fabric_client.newPeer('grpc://localhost:7051');
channel.addPeer(peer);
var order = fabric_client.newOrderer('grpc://localhost:7050')
channel.addOrderer(order);
//
var member_user = null;
var store_path = path.join(__dirname, 'hfc-key-store');
console.log('Store path:' + store_path);
var tx_id = null;
// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
// 设置认证信息的存放路径,并使用 user1 用户进行 invoke 操作
Fabric_Client.newDefaultKeyValueStore({
path: store_path
}).then((state_store) => {
// assign the store to the fabric client
fabric_client.setStateStore(state_store);
var crypto_suite = Fabric_Client.newCryptoSuite();
// use the same location for the state store (where the users' certificate are kept)
// and the crypto store (where the users' keys are kept)
var crypto_store = Fabric_Client.newCryptoKeyStore({ path: store_path });
crypto_suite.setCryptoKeyStore(crypto_store);
fabric_client.setCryptoSuite(crypto_suite);
// get the enrolled user from persistence, this user will sign all requests
return fabric_client.getUserContext('user1', true);
}).then((user_from_store) => {
if (user_from_store && user_from_store.isEnrolled()) {
console.log('Successfully loaded user1 from persistence');
member_user = user_from_store;
} else {
throw new Error('Failed to get user1.... run registerUser.js');
}
// get a transaction id object based on the current user assigned to fabric client
// 生成一个交易ID
tx_id = fabric_client.newTransactionID();
console.log("Assigning transaction_id: ", tx_id._transaction_id);
// createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],
// changeCarOwner chaincode function - requires 2 args , ex: args: ['CAR10', 'Dave'],
// must send the proposal to endorsing peers
/* 构建invoke操作的请求,
chaincodeId表示chaincode名字,
fcn :调用的方法,
args :传递的参数,
chainId : channel 名字
txId :创建的交易ID
*/
var request = {
//targets: let default to the peer assigned to the client
chaincodeId: 'fabcar',
fcn: '',
args: [''],
chainId: 'mychannel',
txId: tx_id
};
// send the transaction proposal to the peers
// 发送交易提案到背书节点,背书节点是在链码实例化时指定的。
return channel.sendTransactionProposal(request);
}).then((results) => {
var proposalResponses = results[0];
var proposal = results[1];
let isProposalGood = false;
if (proposalResponses && proposalResponses[0].response &&
proposalResponses[0].response.status === 200) {
isProposalGood = true;
console.log('Transaction proposal was good');
} else {
console.error('Transaction proposal was bad');
}
if (isProposalGood) {
console.log(util.format(
'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s"',
proposalResponses[0].response.status, proposalResponses[0].response.message));
// build up the request for the orderer to have the transaction committed
// 将收集到的交易提案等内容,打包成一个交易,发送到 orderer 节点
var request = {
proposalResponses: proposalResponses,
proposal: proposal
};
// set the transaction listener and set a timeout of 30 sec
// if the transaction did not get committed within the timeout period,
// report a TIMEOUT status
var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing
var promises = [];
var sendPromise = channel.sendTransaction(request);
promises.push(sendPromise); //we want the send transaction first, so that we know where to check status
// get an eventhub once the fabric client has a user assigned. The user
// is required bacause the event registration must be signed
/*
let event_hub = fabric_client.newEventHub();
event_hub.setPeerAddr('grpc://localhost:7053');
*/
let event_hub = channel.newChannelEventHub(peer);
// using resolve the promise so that result status may be processed
// under the then clause rather than having the catch clause process
// the status
let txPromise = new Promise((resolve, reject) => {
// 设置超时时间,超时则断开连接,并返回超时提示
let handle = setTimeout(() => {
event_hub.disconnect();
resolve({ event_status: 'TIMEOUT' }); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));
}, 3000);
event_hub.connect();
// 注册事件监听
event_hub.registerTxEvent(transaction_id_string, (tx, code) => {
// this is the callback for transaction event status
// first some clean up of event listener
// 监听成功,则清除定时器并断开
clearTimeout(handle);
event_hub.unregisterTxEvent(transaction_id_string);
event_hub.disconnect();
// now let the application know what happened
var return_status = { event_status: code, tx_id: transaction_id_string };
if (code !== 'VALID') {
console.error('The transaction was invalid, code = ' + code);
resolve(return_status); // we could use reject(new Error('Problem with the tranaction, event status ::'+code));
} else {
/*
console.log('The transaction has been committed on peer ' + event_hub._ep._endpoint.addr);
*/
console.log('The transaction has been committed on peer ' + event_hub.getPeerAddr);
resolve(return_status);
}
}, (err) => {
//this is the callback if something goes wrong with the event registration or processing
reject(new Error('There was a problem with the eventhub ::' + err));
});
});
promises.push(txPromise);
return Promise.all(promises);
} else {
console.error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
}
}).then((results) => {
console.log('Send transaction promise and event listener promise have completed');
// check the results in the order the promises were added to the promise all list
if (results && results[0] && results[0].status === 'SUCCESS') {
console.log('Successfully sent transaction to the orderer.');
} else {
console.error('Failed to order the transaction. Error code: ' + results[0].status);
}
if (results && results[1] && results[1].event_status === 'VALID') {
console.log('Successfully committed the change to the ledger by the peer');
} else {
console.log('Transaction failed to be committed to the ledger due to ::' + results[1].event_status);
}
}).catch((err) => {
console.error('Failed to invoke successfully :: ' + err);
});
上面的代码部分,我改了点东西,实例的代码跑不通,发现源代码的内容修改了,事例的代码没有改。所以我改了两个部分的内容:
// 第一部分
/*
let event_hub = fabric_client.newEventHub();
event_hub.setPeerAddr('grpc://localhost:7053');
*/
let event_hub = channel.newChannelEventHub(peer);
// 第二部分
/*
console.log('The transaction has been committed on peer ' + event_hub._ep._endpoint.addr);
*/
console.log('The transaction has been committed on peer ' + event_hub.getPeerAddr);
从上面的代码中我们可以看到,fcn
和args
两个字段是没有参数的,这个是要根据你的需求来指定内容。
例如:创建一个新的CAR11
,你需要修改invoke.js
文件:
var request = {
//targets: let default to the peer assigned to the client
chaincodeId: 'fabcar',
fcn: 'createCar',
args:['CAR11', 'Honda', 'Accord', 'Black', 'Tom'],
chainId: 'mychannel',
txId: tx_id
};
保存,并执行node invoke.js
。你会得到如下内容:
VirtualBox:~/code/fabric/src/fabric-samples/fabcar$ node invoke.js
Store path:/home/sharex2/code/fabric/src/fabric-samples/fabcar/hfc-key-store
(node:10848) DeprecationWarning: grpc.load: Use the @grpc/proto-loader module with grpc.loadPackageDefinition instead
Successfully loaded user1 from persistence
Assigning transaction_id: 8df9194d4942018a80489dcf2e06fb797e11e2108a227379c3fcbfa73c431970
Transaction proposal was good
Successfully sent Proposal and received ProposalResponse: Status - 200, message - ""
The transaction has been committed on peer localhost:7051
Send transaction promise and event listener promise have completed
Successfully sent transaction to the orderer.
Successfully committed the change to the ledger by the peer
然后我们来查看这笔交易是否成功,修改query.js
:
const request = {
//targets : --- letting this default to the peers assigned to the channel
chaincodeId: 'fabcar',
fcn: 'queryCar',
args: ['CAR11']
};
保存之后,执行node query.js
,会得到以下结果:
VirtualBox:~/code/fabric/src/fabric-samples/fabcar$ node query.js
Store path:/home/sharex2/code/fabric/src/fabric-samples/fabcar/hfc-key-store
(node:10886) DeprecationWarning: grpc.load: Use the @grpc/proto-loader module with grpc.loadPackageDefinition instead
Successfully loaded user1 from persistence
Query has completed, checking results
Response is {"colour":"Black","make":"Honda","model":"Accord","owner":"Tom"}
查看数据库内容
我们在fabcar
事例中使用的是couchdb
。
在浏览器输入http://192.168.1.135:5984/_utils/
。将 IP 换成你自己的,如果是本地的服务,就换成127.0.0.1
。你会看到如下内容:

点击红色圈的内容,就可以查看你的数据了。

总结
一笔交易的完整流程:
- 发送交易提案到背书节点,进行背书。(背书节点在链码实例化的时候指定)
- 背书节点模拟交易,并生成背书签名。
- 收集交易的背书,构造交易请求发送给排序服务节点。
- 排序服务节点对交易进行排序,并生成区块。然后广播给组织的主节点。
- 记账节点验证区块内容并写入区块。
- 在组织内部同步区块。
网友评论