SyntaxError: 尝试从Hyperledger 2.2查询交易详情时出现意外的JSON输入结束。

huangapple go评论78阅读模式
英文:

SyntaxError: Unexpected end of JSON input when trying to query transaction details from the hyperledger 2.2

问题

以下是您提供的代码的翻译部分:

我正在尝试在 .hyperledger 2.2 上运行奖励示例。合同已成功打包和部署。我还能够成功运行应用程序并注册管理员和用户。

链码成功部署:

已提交链码定义以在通道 'mychannel' 上的链码 'customerloyalty' 上:
版本:1.0,序列:1,背书插件:escc,验证插件:vscc,批准:[Org1MSP:true,Org2MSP:true]
成功在通道 'mychannel' 上的 peer0.org2 上查询链码定义


成功注册管理员:

钱包路径:../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
成功注册管理员用户 "admin" 并导入到钱包中


成功注册用户:

应用程序运行在端口:8000
使用参数 - firstname: Test lastname: User email: test@example.com phonenumber: 111-111-1111 accountNumber: 123456 cardId: 123
有效的条目
钱包路径:../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
成功注册并注册了管理员用户 123 并将其导入到钱包中
管理员用户已断开连接

提交创建会员交易。
createMemberResponse:
{
accountNumber: '123456',
firstName: 'Test',
lastName: 'User',
email: 'test@example.com',
phoneNumber: '111-111-1111',
points: 0
}

获取会员状态
memberResponse.parse_response:
{
accountNumber: '123456',
firstName: 'Test',
lastName: 'User',
email: 'test@example.com',
phoneNumber: '111-111-1111',
points: 0
}
使用参数获取会员状态 - accountNumber: 123456 cardId: 123
钱包路径:../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet

获取会员状态
{
accountNumber: '123456',
firstName: 'Test',
lastName: 'User',
email: 'test@example.com',
phoneNumber: '111-111-1111',
points: 0
}
钱包路径:../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet


但是,当我尝试在应用程序中获取交易信息时,出现以下错误,而来自对等方的响应为空:

获取会员 123456 的使用积分交易状态
2023-01-05T21:28:46.042Z - 错误:[事务]:错误:来自任何对等方的有效响应均不存在。错误:
peer=peer0.org1.example.com:7051, status=500, message=模拟中的错误:事务返回失败:SyntaxError:JSON 输入意外结束
peer=peer0.org2.example.com:9051, status=500, message=模拟中的错误:事务返回失败:SyntaxError:JSON 输入意外结束
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12 处的 newEndorsementError
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23 处获取响应有效负载
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28 处提交事务
在 node:internal/process/task_queues:95:5 处的 process.processTicksAndRejections 处理
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:592:41 处的异步对象使用点事务信息
错误:来自任何对等方的有效响应均不存在。错误:
peer=peer0.org1.example.com:7051, status=500, message=模拟中的错误:事务返回失败:SyntaxError:JSON 输入意外结束
peer=peer0.org2.example.com:9051, status=500, message=模拟中的错误:事务返回失败:SyntaxError:JSON 输入意外结束
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12 处的 newEndorsementError
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23 处获取响应有效负载
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28 处提交事务
在 node:internal/process/task_queues:95:5 处的 process.processTicksAndRejections 处理
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:592:41 处的异步对象使用点事务信息
{
responses: [
{
version: 0,
timestamp: null,
response: [Object],
payload: <Buffer >,
endorsement: null,
connection: [Object],
peer: 'peer0.org1.example.com:7051'
},
{
version: 0,
timestamp: null,
response: [Object],
payload: <Buffer >,
endorsement: null,
connection: [Object],
peer: 'peer0.org2.example.com:9051'
}
],
errors: []
}
钱包路径:../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet

获取会员 123456 的赚取积分交易状态
2023-01-05T21:28:46.192Z - 错误:[事务]:错误:来自任何对等方的有效响应均不存在。错误:
peer=peer0.org1.example.com:7051, status=500, message=模拟中的错误:事务返回失败:SyntaxError:JSON 输入意外结束
peer=peer0.org2.example.com:9051, status=500, message=模拟中的错误:事务返回失败:SyntaxError:JSON 输入意外结束
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12 处的 newEndorsementError
在 ../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23 处获取响应有效

英文:

I am trying to run a rewards example on .hyperledger 2.2. The contract is successfully packaged and deployed. I was also able to run the application successfully and enroll admin and user.

Chaincode successfully deployed :

Committed chaincode definition for chaincode &#39;customerloyalty&#39; on channel &#39;mychannel&#39;:
Version: 1.0, Sequence: 1, Endorsement Plugin: escc, Validation Plugin: vscc, Approvals: [Org1MSP: true, Org2MSP: true]
Query chaincode definition successful on peer0.org2 on channel &#39;mychannel&#39;

Enroll admin successfully :

 
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
Successfully enrolled admin user &quot;admin&quot; and imported it into the wallet

was able to successfully register user :

app running on port: 8000
Using param - firstname: Test lastname: User email: test@example.com phonenumber: 111-111-1111 accountNumber: 123456 cardId: 123
Valid Entries
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
Successfully registered and enrolled admin user 123 and imported it into the wallet
admin user admin disconnected

Submit Create Member transaction.
createMemberResponse: 
{
  accountNumber: &#39;123456&#39;,
  firstName: &#39;Test&#39;,
  lastName: &#39;User&#39;,
  email: &#39;test@example.com&#39;,
  phoneNumber: &#39;111-111-1111&#39;,
  points: 0
}

Get member state 
memberResponse.parse_response: 
{
  accountNumber: &#39;123456&#39;,
  firstName: &#39;Test&#39;,
  lastName: &#39;User&#39;,
  email: &#39;test@example.com&#39;,
  phoneNumber: &#39;111-111-1111&#39;,
  points: 0
}
memberData using param -  accountNumber: 123456 cardId: 123
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet

Get member state 
{
  accountNumber: &#39;123456&#39;,
  firstName: &#39;Test&#39;,
  lastName: &#39;User&#39;,
  email: &#39;test@example.com&#39;,
  phoneNumber: &#39;111-111-1111&#39;,
  points: 0
}
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet

However, when I try to get transaction information in the app I get the following error with no response from peers :

Get use points transactions state for member 123456
2023-01-05T21:28:46.042Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
    peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
    at getResponsePayload (/../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
    at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.usePointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:592:41)
Error: No valid responses from any peers. Errors:
    peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
    at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
    at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.usePointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:592:41) {
  responses: [
    {
      version: 0,
      timestamp: null,
      response: [Object],
      payload: &lt;Buffer &gt;,
      endorsement: null,
      connection: [Object],
      peer: &#39;peer0.org1.example.com:7051&#39;
    },
    {
      version: 0,
      timestamp: null,
      response: [Object],
      payload: &lt;Buffer &gt;,
      endorsement: null,
      connection: [Object],
      peer: &#39;peer0.org2.example.com:9051&#39;
    }
  ],
  errors: []
}
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet

Get earn points transactions state for member 123456
2023-01-05T21:28:46.192Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
    peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
    at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
    at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.earnPointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:545:25)
Error: No valid responses from any peers. Errors:
    peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
    at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
    at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.earnPointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:545:25) {
  responses: [
    {
      version: 0,
      timestamp: null,
      response: [Object],
      payload: &lt;Buffer &gt;,
      endorsement: null,
      connection: [Object],
      peer: &#39;peer0.org1.example.com:7051&#39;
    },
    {
      version: 0,
      timestamp: null,
      response: [Object],
      payload: &lt;Buffer &gt;,
      endorsement: null,
      connection: [Object],
      peer: &#39;peer0.org2.example.com:9051&#39;
    }
  ],
  errors: []
}
node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:393:5)
    at ServerResponse.setHeader (node:_http_outgoing:644:11)
    at ServerResponse.header (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:278:15)
    at ../fabric-samples/asset-transfer-basic/application-customerloyalty/app.js:278:37
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: &#39;ERR_HTTP_HEADERS_SENT&#39;
}

the above log indicates that json syntax is not correct in network.js file both invoking submitTransaction function. excerpt from Network.js file is :

  /*
  * Get all EarnPoints transactions data
  * @param {String} cardId Card id to connect to network
  */
    earnPointsTransactionsInfo: async function (cardId, userType, userId) {

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), &#39;/wallet&#39;);
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        try {
            // Create a new gateway for connecting to our peer node.
            const gateway2 = new Gateway();
            await gateway2.connect(ccp, { wallet, identity: cardId, discovery: gatewayDiscovery });

            // Get the network (channel) our contract is deployed to.
            const network = await gateway2.getNetwork(&#39;mychannel&#39;);

            // Get the contract from the network.
            const contract = network.getContract(&#39;customerloyalty&#39;);

            console.log(`\nGet earn points transactions state for ${userType} ${userId}`);
            //for debug only
            console.log(await contract.submitTransaction(&#39;EarnPointsTransactionsInfo&#39;, &#39;userType&#39;, &#39;userId&#39;));
            //
            let earnPointsTransactions = await contract.submitTransaction(&#39;EarnPointsTransactionsInfo&#39;, userType, userId);
            //for debug only
            console.log(await contract.submitTransaction(&#39;EarnPointsTransactionsInfo&#39;, userType, userId));
            //
            earnPointsTransactions = JSON.parse(earnPointsTransactions.toString());
            console.log(earnPointsTransactions);

            // Disconnect from the gateway.
            await gateway2.disconnect();

            return earnPointsTransactions;
        }
        catch(err) {
            //print and return error
            console.log(err);
            let error = {};
            error.error = err.message;
            return error;
        }

    },
    usePointsTransactionsInfo: async function (cardId, userType, userId) {

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), &#39;/wallet&#39;);
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        try {
            // Create a new gateway for connecting to our peer node.
            const gateway2 = new Gateway();
            await gateway2.connect(ccp, { wallet, identity: cardId, discovery: gatewayDiscovery });

            // Get the network (channel) our contract is deployed to.
            const network = await gateway2.getNetwork(&#39;mychannel&#39;);

            // Get the contract from the network.
            const contract = network.getContract(&#39;customerloyalty&#39;);

            console.log(`\nGet use points transactions state for ${userType} ${userId}`);
            let usePointsTransactions = await contract.submitTransaction(&#39;UsePointsTransactionsInfo&#39;,userType, userId);
            usePointsTransactions = JSON.parse(usePointsTransactions.toString());
            console.log(usePointsTransactions);

            // Disconnect from the gateway.
            await gateway2.disconnect();

            return usePointsTransactions;
        }

I have tried to check logs from the peer using docker logs &lt;container name&gt; :

2023-01-05 22:28:46 2023-01-05T21:28:46.023Z error [c-api:contracts-spi/chaincodefromcontract.js]     [mychannel-fedc897c] SyntaxError: Unexpected end of JSON input  
2023-01-05 22:28:46 2023-01-05T21:28:46.033Z error [c-api:lib/handler.js]                             [mychannel-fedc897c] Calling chaincode Invoke() returned error response [SyntaxError: Unexpected end of JSON input
2023-01-05 22:28:46     at JSON.parse (&lt;anonymous&gt;)
2023-01-05 22:28:46     at CustomerLoyalty.UsePointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:110:29)
2023-01-05 22:28:46     at processTicksAndRejections (node:internal/process/task_queues:96:5)
2023-01-05 22:28:46     at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
2023-01-05 22:28:46     at async handleMessage (/usr/local/src/node_modules/fabric-shim/lib/handler.js:602:24)]. Sending ERROR message back to peer  
2023-01-05 22:28:46 2023-01-05T21:28:46.181Z error [c-api:contracts-spi/chaincodefromcontract.js]     [mychannel-644303c3] SyntaxError: Unexpected end of JSON input  
2023-01-05 22:28:46 2023-01-05T21:28:46.184Z error [c-api:lib/handler.js]                             [mychannel-644303c3] Calling chaincode Invoke() returned error response [SyntaxError: Unexpected end of JSON input
2023-01-05 22:28:46     at JSON.parse (&lt;anonymous&gt;)
2023-01-05 22:28:46     at CustomerLoyalty.EarnPointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:89:29)
2023-01-05 22:28:46     at processTicksAndRejections (node:internal/process/task_queues:96:5)
2023-01-05 22:28:46     at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
2023-01-05 22:28:46     at async handleMessage (/usr/local/src/node_modules/fabric-shim/lib/handler.js:602:24)]. Sending ERROR message back to peer  
2023-01-05 22:32:51 2023-01-05T21:32:51.616Z info [c-api:lib/handler.js]                              [mychannel-68bdfcd2] Calling chaincode Invoke() succeeded. Sending COMPLETED message back to peer  
2023-01-05 22:32:53 2023-01-05T21:32:53.977Z error [c-api:contracts-spi/chaincodefromcontract.js]     [mychannel-7f185a49] SyntaxError: Unexpected end of JSON input  
2023-01-05 22:32:53 2023-01-05T21:32:53.989Z error [c-api:lib/handler.js]                             [mychannel-7f185a49] Calling chaincode Invoke() returned error response [SyntaxError: Unexpected end of JSON input
2023-01-05 22:32:53     at JSON.parse (&lt;anonymous&gt;)
2023-01-05 22:32:53     at CustomerLoyalty.UsePointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:110:29)
2023-01-05 22:32:53     at processTicksAndRejections (node:internal/process/task_queues:96:5)
2023-01-05 22:32:53     at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
2023-01-05 22:32:53     at async handleMessage (/usr/local/src/node_modules/fabric-shim/lib/handler.js:602:24)]. Sending ERROR message back to peer  
2023-01-05 22:32:54 2023-01-05T21:32:54.195Z error [c-api:contracts-spi/chaincodefromcontract.js]     [mychannel-44d04ba9] SyntaxError: Unexpected end of JSON input  
2023-01-05 22:32:54 2023-01-05T21:32:54.197Z error [c-api:lib/handler.js]                             [mychannel-44d04ba9] Calling chaincode Invoke() returned error response [SyntaxError: Unexpected end of JSON input
2023-01-05 22:32:54     at JSON.parse (&lt;anonymous&gt;)
2023-01-05 22:32:54     at CustomerLoyalty.EarnPointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:89:29)
2023-01-05 22:32:54     at processTicksAndRejections (node:internal/process/task_queues:96:5)
2023-01-05 22:32:54     at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
2023-01-05 22:32:54     at async handleMessage (/usr/local/src/node_modules/fabric-shim/lib/handler.js:602:24)]. Sending ERROR message back to peer  

Here is the smart contract script customerloyalty.js :

&#39;use strict&#39;;

const { Contract } = require(&#39;fabric-contract-api&#39;); const allPartnersKey = &#39;all-partners&#39;; const earnPointsTransactionsKey = &#39;earn-points-transactions&#39;; const usePointsTransactionsKey = &#39;use-points-transactions&#39;;

class CustomerLoyalty extends Contract {
// Init function executed when the ledger is instantiated
async instantiate(ctx) {
    console.info(&#39;============= START : Initialize Ledger ===========&#39;);

    await ctx.stub.putState(&#39;instantiate&#39;, Buffer.from(&#39;INIT-LEDGER&#39;));
    await ctx.stub.putState(allPartnersKey, Buffer.from(JSON.stringify([])));
    await ctx.stub.putState(earnPointsTransactionsKey, Buffer.from(JSON.stringify([])));
    await ctx.stub.putState(usePointsTransactionsKey, Buffer.from(JSON.stringify([])));

    console.info(&#39;============= END : Initialize Ledger ===========&#39;);
}

// Add a member on the ledger
async CreateMember(ctx, member) {
    member = JSON.parse(member);

    await ctx.stub.putState(member.accountNumber, Buffer.from(JSON.stringify(member)));

    return JSON.stringify(member);
}

// Add a partner on the ledger, and add it to the all-partners list
async CreatePartner(ctx, partner) {
    partner = JSON.parse(partner);

    await ctx.stub.putState(partner.id, Buffer.from(JSON.stringify(partner)));

    let allPartners = await ctx.stub.getState(allPartnersKey);
    allPartners = JSON.parse(allPartners);
    allPartners.push(partner);
    await ctx.stub.putState(allPartnersKey, Buffer.from(JSON.stringify(allPartners)));

    return JSON.stringify(partner);
}

// Record a transaction where a member earns points
async EarnPoints(ctx, earnPoints) {
    earnPoints = JSON.parse(earnPoints);
    earnPoints.timestamp = new Date((ctx.stub.txTimestamp.seconds.low*1000)).toGMTString();
    earnPoints.transactionId = ctx.stub.txId;

    let member = await ctx.stub.getState(earnPoints.member);
    member = JSON.parse(member);
    member.points += earnPoints.points;
    await ctx.stub.putState(earnPoints.member, Buffer.from(JSON.stringify(member)));

    let earnPointsTransactions = await ctx.stub.getState(earnPointsTransactionsKey);
    earnPointsTransactions = JSON.parse(earnPointsTransactions);
    earnPointsTransactions.push(earnPoints);
    await ctx.stub.putState(earnPointsTransactionsKey, Buffer.from(JSON.stringify(earnPointsTransactions)));

    return JSON.stringify(earnPoints);
}

// Record a transaction where a member redeems points
async UsePoints(ctx, usePoints) {
    usePoints = JSON.parse(usePoints);
    usePoints.timestamp = new Date((ctx.stub.txTimestamp.seconds.low*1000)).toGMTString();
    usePoints.transactionId = ctx.stub.txId;

    let member = await ctx.stub.getState(usePoints.member);
    member = JSON.parse(member);
    if (member.points &lt; usePoints.points) {
        throw new Error(&#39;Member does not have sufficient points&#39;);
    }
    member.points -= usePoints.points;
    await ctx.stub.putState(usePoints.member, Buffer.from(JSON.stringify(member)));

    let usePointsTransactions = await ctx.stub.getState(usePointsTransactionsKey);
    usePointsTransactions = JSON.parse(usePointsTransactions);
    usePointsTransactions.push(usePoints);
    await ctx.stub.putState(usePointsTransactionsKey, Buffer.from(JSON.stringify(usePointsTransactions)));

    return JSON.stringify(usePoints);
}

// Get earn points transactions of the particular member or partner
async EarnPointsTransactionsInfo(ctx, userType, userId) {
    let transactions = await ctx.stub.getState(earnPointsTransactionsKey);
    transactions = JSON.parse(transactions);
    let userTransactions = [];

    for (let transaction of transactions) {
        if (userType === &#39;member&#39;) {
            if (transaction.member === userId) {
                userTransactions.push(transaction);
            }
        } else if (userType === &#39;partner&#39;) {
            if (transaction.partner === userId) {
                userTransactions.push(transaction);
            }
        }
    }

    return JSON.stringify(userTransactions);
}

// Get use points transactions of the particular member or partner
async UsePointsTransactionsInfo(ctx, userType, userId) {
    let transactions = await ctx.stub.getState(usePointsTransactionsKey);
    transactions = JSON.parse(transactions);
    let userTransactions = [];

    for (let transaction of transactions) {
        if (userType === &#39;member&#39;) {
            if (transaction.member === userId) {
                userTransactions.push(transaction);
            }
        } else if (userType === &#39;partner&#39;) {
            if (transaction.partner === userId) {
                userTransactions.push(transaction);
            }
        }
    }

    return JSON.stringify(userTransactions);
}

// get the state from key
async GetState(ctx, key) {
    let data = await ctx.stub.getState(key);

    let jsonData = JSON.parse(data.toString());
    return JSON.stringify(jsonData);
}

module.exports = CustomerLoyalty;`

it seems that there is an syntax error with json.stringify. I don't know what to do next, or how to solve this. Any ideas?

答案1

得分: 0

我怀疑您从未调用过instantiate交易函数,因此earnPointsTransactionsKey账本键中没有数据:

% node --eval="JSON.parse(Buffer.from(''))"

SyntaxError: JSON输入意外结束
    at JSON.parse (<anonymous>)

与其依赖初始化交易来设置有效的空初始状态,您可以考虑在智能合约中添加一个辅助函数,类似于这样:

async getEarnPointsTransactions(ctx) {
    const data = await ctx.stub.getState(earnPointsTransactionsKey);
    if (!data || data.length === 0) {
        return [];
    }

    return JSON.parse(data);
}

还要考虑,您所有更新账本的交易都会修改earnPointsTransactionsKey账本键的值。随着负载的增加,这将引入争用,并且您可能会遇到MVCC_READ_CONFLICT故障,因为交易同时更新此状态。可以通过在客户端应用程序中实现提交重试逻辑来减轻这些故障。您可以考虑不同的实施方法,例如:

  1. 使用复合键来分区数据。
  2. 使用键历史记录来读取与先前交易相关的数据。
英文:

I suspect that you have never invoked your instantiate transaction function and so the earnPointsTransactionsKey ledger key contains no data:

% node --eval=&quot;JSON.parse(Buffer.from(&#39;&#39;))&quot;

SyntaxError: Unexpected end of JSON input
    at JSON.parse (&lt;anonymous&gt;)

Rather than relying on an initialize transaction to set effectively empty initial state, you might consider a helper function in your smart contract, something like this:

async getEarnPointsTransactions(ctx) {
    const data = await ctx.stub.getState(earnPointsTransactionsKey);
    if (!data || data.length === 0) {
        return [];
    }

    return JSON.parse(data);
}

Also consider that all of your transactions that update the ledger are modifying the value of the earnPointsTransactionsKey ledger key. This is going to introduce contention as load increases and you are likely to experience MVCC_READ_CONFLICT failures as transactions concurrently update this state. These failures can be mitigated by implementing submit retry logic in your client application. You might consider different implementation approaches, such as:

  1. using composite keys to partition the data.
  2. using key history to read data associated with previous transactions.

答案2

得分: 0

这个错误信息表明HTTP响应的标头已经发送给客户端并且无法修改。通常发生在已经向客户端发送了响应,然后尝试发送另一个响应的情况。此错误被抛出的代码特定位置在“express”库的“response.js”文件中的“ServerResponse.header”,引起问题的具体函数是“UserController.js”中的“register”,位于第60行。

英文:

This error message is indicating that the headers for an HTTP response have already been sent to the client and cannot be modified. This typically occurs when a response has already been sent to the client and an attempt is made to send another response. The specific location in the code where this error is being thrown is at "ServerResponse.header" in the "response.js" file in the "express" library, and the specific function that is causing the issue is "register" in "UserController.js" at line 60.

huangapple
  • 本文由 发表于 2023年1月6日 06:11:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75024899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定