五、基于fabric-node-sdk后端代码搭建

在完成了链码的撰写和部署安装实例化之后,我们开始koa后端搭建

1. fabric区块链查询nodejs代码

基础思路是调用node-sdk的queryChaincode方法

async searchAllTrail ( ctx ) {
		
        const title = 'admin page'
        let result = ''

        var fabric_client = new Fabric_Client();
		var key = "name"

		// setup the fabric network
		var channel = fabric_client.newChannel('mychannel');
		var peer = fabric_client.newPeer('grpc://localhost:7051');
		channel.addPeer(peer);

		//
		var member_user = null;

		// var store_path = path.join(os.homedir(), '.hfc-key-store');
		var store_path = path.join('/home/fabric/Documents/carChain/app/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
		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');
		    }

		    // queryTuna - requires 1 argument, ex: args: ['4'],
		    const request = {
		        chaincodeId: 'trail',
		        txId: tx_id,
		        fcn: 'searchAllTrail',
				args: [""],
		    };

		    // send the query proposal to the peer
		    return channel.queryByChaincode(request);
		}).then((query_responses) => {
		    console.log("Query has completed, checking results");
		    // query_responses could have more than one  results if there multiple peers were used as targets
		    if (query_responses && query_responses.length == 1) {
		        if (query_responses[0] instanceof Error) {
		            console.error("error from query = ", query_responses[0]);
		            result = "Could not locate tuna"
		        } else {
		            console.log("Response is ", query_responses[0].toString());
                    return query_responses[0].toString()
		        }
		    } else {
		        console.log("No payloads were returned from query");
                result = "Could not locate tuna"
		    }
		}).catch((err) => {
            console.error('Failed to query successfully :: ' + err);
            result = 'Failed to query successfully :: ' + err
            
		});

        // await ctx.render('index', {
        //     title, result
		// })
		ctx.body = result
	},

2. fabric区块链修改(插入,删除)nodejs代码

基础思路是调用node-sdk的sendTransactionProposal()方法提交提案和sendTransaction()执行区块链账本存储,执行PutState操作,再在Order队列中进行校验

async insertTrail (ctx) {
		const queryBody = ctx.request.query;
		const Trid = queryBody.Trid;
        console.log(`Trid.....${Trid}`)
        const jsonStr = queryBody.jsonStr;
		console.log(`jsonStr.....${jsonStr}`)
		

        var fabric_client = new Fabric_Client();

		// setup the fabric network
		var channel = fabric_client.newChannel('mychannel');
		var peer = fabric_client.newPeer('grpc://localhost:7051');
		
		var order = fabric_client.newOrderer('grpc://localhost:7050')
		channel.addOrderer(order);
		channel.addPeer(peer);
		var member_user = null;

		// var store_path = path.join(os.homedir(), '.hfc-key-store');
		var store_path = path.join('/home/fabric/Documents/carChain/app/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
		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');
		    }

		    // 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: 'trail',
		        fcn: 'insertTrail',
		        args : [Trid,jsonStr],
		        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
		        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('grpc://localhost:7053');
				// // let event_hub = new ChannelEventHub(channel, peer);
				// //接下来设置EventHub,用于监听Transaction是否成功写入,这里也是启用了TLS
				// let data = fs.readFileSync('/home/fabric/Documents/carChain/basic-network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt'); 
        		// let grpcOpts = { 
          		//       'pem': Buffer.from(data).toString(), 
           		// 	 'ssl-target-name-override': "peer0.org1.example.com"
       			//  } 
				// event_hub.setPeerAddr('grpc://localhost:7053',grpcOpts);
				// event_hub.connect();
				// console.log('data:'+data);
				// console.log('grpcOpts.pem:'+grpcOpts.pem);
				//------------------------------------------------------------
				let event_hub = channel.newChannelEventHub('localhost:7051');
				//------------------------------------------------------------
		        // 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.');
				//res.send(tx_id.getTransactionID());
				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());
				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
	},

3. fabric区块链交易追溯

根据历史交易的Hash追溯区块

async searchBlockByHash ( ctx ) {
		const queryBody = ctx.request.query;
        const hash = queryBody.hash;
        console.log(`hash.....${hash}`)
        const title = 'admin page'
        let result = ''

        var fabric_client = new Fabric_Client();
		var key = "name"

		// setup the fabric network
		var channel = fabric_client.newChannel('mychannel');
		var peer = fabric_client.newPeer('grpc://localhost:7051');
		channel.addPeer(peer);

		//
		var member_user = null;

		// var store_path = path.join(os.homedir(), '.hfc-key-store');
		var store_path = path.join('/home/fabric/Documents/carChain/app/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
		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');
		    }

		    // send the query proposal to the peer
			return channel.queryBlockByTxID(hash,peer,true,false);
			// return channel.queryByChaincode(request);
		}).then((query_responses) => {
		    console.log("Query has completed, checking results");
		    // query_responses could have more than one  results if there multiple peers were used as targets
		    if (query_responses) {
		        if (query_responses[0] instanceof Error) {
		            console.error("error from query = ", query_responses[0]);
		            result = "Could not locate tuna"
		        } else {
		            console.log("Response is ", query_responses);
                    return query_responses
		        }
		    } else {
		        console.log("No payloads were returned from query");
                result = "Could not locate tuna"
		    }
		}).catch((err) => {
            console.error('Failed to query successfully :: ' + err);
            result = 'Failed to query successfully :: ' + err
            
		});

        // await ctx.render('index', {
        //     title, result
		// })
		ctx.body = result
	},

4. 配置路由

const router = require('koa-router')()
const IndexController = require('./../controllers/index')
router
    // .get('/',IndexController.indexPage)
    .get('/saveUser', IndexController.saveUser)
    .get('/insertTrail',IndexController.insertTrail)
    .get('/searchAllTrail',IndexController.searchAllTrail)
    .get('/searchOneTrail',IndexController.searchOneTrail)
    .get('/deleteTrail',IndexController.deleteTrail)
    .get('/searchBlockByHash',IndexController.searchBlockByHash)

5. Vue调用测试

插入轨迹

this.$http.get("http://localhost:3000/insertTrail",{
              params: {
                  Trid : this.Trail.trid,
                  jsonStr : jsonStr
               },
            }).then(function(res){
            console.log(res);
            alert("交易hash tx_id: "+ res.data);
                // location.reload()
          });

查询轨迹

this.$http.get("http://localhost:3000/searchAllTrail", {
              params: {
               },
            }).then(function(res){
            console.log(res);
          });

删除轨迹

this.$http.get("http://localhost:3000/deleteTrail", {
               params: {
                   Trid : "002"
                },
             }).then(function(res){
             console.log(res);
             alert("删除交易hash tx_id: "+ res.data);
      //            location.reload()
           });

交易溯源

async getInfo() {
     var res = await this.$http.get("http://localhost:3000/searchOneTrail", {
             params: {
                 trid : "006"
              },
           });
     console.log("交易hash为:"+res.data.hash);
     console.log(res.data.hash);
     var hashStr = res.data.hash;
     var res = await this.$http.get("http://localhost:3000/searchBlockByHash", {
             params: {
                 hash : hashStr
              },
           });
     console.log("区块数据为:"+res.data);
     console.log(res.data);
     console.log("所在区块号为:"+res.data.header.number);
     console.log("所在区块hash为:"+res.data.header.data_hash);
     console.log("交易hash为为:"+res.data.data.data[0].payload.header.channel_header.tx_id);
     console.log("交易时间戳为为:"+res.data.data.data[0].payload.header.channel_header.timestamp);
   }

交易成功
插入数据之后访问http://localhost:5984/_utils/#/_all_dbs,点进CouchDB数据库网页端查看
插入账本数据成功
vue前端查询
vue项目查询

至此,基于fabric区块链的koa后端以及vue cli项目以及两者相关交互内容架构搭建已经完成

Logo

前往低代码交流专区

更多推荐