SDK修改账本机制
async saveUser (ctx) {
const body = ctx.request.body; //获取请求内容
console.log(`request`,body.k1) //打印请求k1内容
var fabric_client = new Fabric_Client(); //新建一个客户端实例
// setup the fabric network
//发送消息到order来构建一个新的channel,命名为mychannel,返回一个空对象
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(os.homedir(), '.hfc-key-store'); //设置文件存储路径
console.log('Store path:'+store_path); //打印文件存储路径
var tx_id = null; //设置空的交易ID
// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
let result = await 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');
}
//获取交易id:基于client对象上分配的用户身份
// get a transaction id object based on the current user assigned to fabric client
tx_id = fabric_client.newTransactionID();
console.log("Assigning transaction_id: ", tx_id._transaction_id);
//构建请求
// recordTuna - requires 5 args, ID, vessel, location, timestamp,holder - ex: args: ['10', 'Hound', '-12.021, 28.012', '1504054225', 'Hansel'],
// send proposal to endorser
const request = {
//targets : --- letting this default to the peers assigned to the channel
chaincodeId: 'dateContract10',
fcn: 'writeContract',
args: [body.k0,body.k1,body.k2,body.k3,body.k4,body.k5,body.k6,body.k7,body.k8],
chainId: 'mychannel',
txId: tx_id
};
//SDK根据request生成proposal,并调用sendPeersProposal()
// 将提案发送给背书节点,然后将返回的提案响应连同交易提案一起打包返回给client
// 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
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
//获取事件处理所使用的事务ID字符串
var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing
var promises = []; //构建promises数组
//将交易请求发送给orderer节点,内部调用sendBroadcast(envelope)
var sendPromise = channel.sendTransaction(request);
//将获得的请求结果添加到数组中
promises.push(sendPromise); //we want the send transaction first, so that we know where to check status
// 一旦fabric客户端分配了用户,就得到Evestub。用户必须签名事件中心登记。
// 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'); //将事件中心绑定到一个新的节点上
//设置promise
// 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) => { //设置一个promise实例(异步执行)
let handle = setTimeout(() => { //设置超时函数
event_hub.disconnect();
resolve({event_status : 'TIMEOUT'}); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));//我们也可以使用reject(newError(“Trnasaction在30秒内没有完成”));
}, 3000);
event_hub.connect(); //连接事件中心
//注册交易事件监听,当交易被peer提交到账本中时可以得到反馈
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(); //断开事件中心连接
//设置返回代码和交易ID
// 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)); //同理可以使用reject函数
} else { //交易已经提交到账本
console.log('The transaction has been committed on peer ' + event_hub._ep._endpoint.addr);
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);//将监听到的信息添加到promises
return Promise.all(promises); //返回promises对象
} else {
//如果出错,打印未能发送提案或收到有效响应。响应空或状态不是200。退出…
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'); //检查结果第一个参数交易提案是否在在order服务顺序的背书清单中
// 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.');
//res.send(tx_id.getTransactionID());//获取交易ID
return tx_id.getTransactionID();
} else {//打印出没有成功提交到排序服务
console.error('Failed to order the transaction. Error code: ' + response.status);
}
//检查交易响应及其返回代码是否有效
if(results && results[1] && results[1].event_status === 'VALID') {
console.log('Successfully committed the change to the ledger by the peer');
//res.send(tx_id.getTransactionID());//打印出交易ID
return tx_id.getTransactionID();
} 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);
});
ctx.body = result //获得交易ID
console.log('result===>',result) 打印出交易ID
}
}
流程:
与前端交互,获取前端输入内容,然后初始化客户端,注册通道、背书节点、排序节点,空的交易ID、设置文件存储路径,然后设置加密模块以及文件路径,通过SDK构建请求,将其发送到背书节点,获得交易提案和交易提案响应,同时检查提案和响应,之后将提案和响应构建请求,发送到排序服务,构建promises数组,将排序结果添加到promises数组中,注册一个事件监听中心,初始化监听后进行监听,之后监听成功则断开监听,获得监听消息和代码后,加入promises数组,否则检查代码,打印错误是否提交到排序服务和账本。最后获得交易ID,打印出交易ID。