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

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

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

问题

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

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

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

  1. 成功注册管理员:

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

  1. 成功注册用户:

应用程序运行在端口: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

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

获取会员 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 :

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

Enroll admin successfully :

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

was able to successfully register user :

  1. app running on port: 8000
  2. Using param - firstname: Test lastname: User email: test@example.com phonenumber: 111-111-1111 accountNumber: 123456 cardId: 123
  3. Valid Entries
  4. Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
  5. Successfully registered and enrolled admin user 123 and imported it into the wallet
  6. admin user admin disconnected
  7. Submit Create Member transaction.
  8. createMemberResponse:
  9. {
  10. accountNumber: &#39;123456&#39;,
  11. firstName: &#39;Test&#39;,
  12. lastName: &#39;User&#39;,
  13. email: &#39;test@example.com&#39;,
  14. phoneNumber: &#39;111-111-1111&#39;,
  15. points: 0
  16. }
  17. Get member state
  18. memberResponse.parse_response:
  19. {
  20. accountNumber: &#39;123456&#39;,
  21. firstName: &#39;Test&#39;,
  22. lastName: &#39;User&#39;,
  23. email: &#39;test@example.com&#39;,
  24. phoneNumber: &#39;111-111-1111&#39;,
  25. points: 0
  26. }
  27. memberData using param - accountNumber: 123456 cardId: 123
  28. Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
  29. Get member state
  30. {
  31. accountNumber: &#39;123456&#39;,
  32. firstName: &#39;Test&#39;,
  33. lastName: &#39;User&#39;,
  34. email: &#39;test@example.com&#39;,
  35. phoneNumber: &#39;111-111-1111&#39;,
  36. points: 0
  37. }
  38. 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 :

  1. Get use points transactions state for member 123456
  2. 2023-01-05T21:28:46.042Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
  3. peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
  4. peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
  5. at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
  6. at getResponsePayload (/../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
  7. at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
  8. at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  9. at async Object.usePointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:592:41)
  10. Error: No valid responses from any peers. Errors:
  11. peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
  12. peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
  13. at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
  14. at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
  15. at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
  16. at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  17. at async Object.usePointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:592:41) {
  18. responses: [
  19. {
  20. version: 0,
  21. timestamp: null,
  22. response: [Object],
  23. payload: &lt;Buffer &gt;,
  24. endorsement: null,
  25. connection: [Object],
  26. peer: &#39;peer0.org1.example.com:7051&#39;
  27. },
  28. {
  29. version: 0,
  30. timestamp: null,
  31. response: [Object],
  32. payload: &lt;Buffer &gt;,
  33. endorsement: null,
  34. connection: [Object],
  35. peer: &#39;peer0.org2.example.com:9051&#39;
  36. }
  37. ],
  38. errors: []
  39. }
  40. Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
  41. Get earn points transactions state for member 123456
  42. 2023-01-05T21:28:46.192Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
  43. peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
  44. peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
  45. at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
  46. at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
  47. at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
  48. at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  49. at async Object.earnPointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:545:25)
  50. Error: No valid responses from any peers. Errors:
  51. peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
  52. peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
  53. at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
  54. at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
  55. at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
  56. at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  57. at async Object.earnPointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:545:25) {
  58. responses: [
  59. {
  60. version: 0,
  61. timestamp: null,
  62. response: [Object],
  63. payload: &lt;Buffer &gt;,
  64. endorsement: null,
  65. connection: [Object],
  66. peer: &#39;peer0.org1.example.com:7051&#39;
  67. },
  68. {
  69. version: 0,
  70. timestamp: null,
  71. response: [Object],
  72. payload: &lt;Buffer &gt;,
  73. endorsement: null,
  74. connection: [Object],
  75. peer: &#39;peer0.org2.example.com:9051&#39;
  76. }
  77. ],
  78. errors: []
  79. }
  80. node:internal/errors:484
  81. ErrorCaptureStackTrace(err);
  82. ^
  83. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
  84. at new NodeError (node:internal/errors:393:5)
  85. at ServerResponse.setHeader (node:_http_outgoing:644:11)
  86. at ServerResponse.header (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:794:10)
  87. at ServerResponse.send (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:174:12)
  88. at ServerResponse.json (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:278:15)
  89. at ../fabric-samples/asset-transfer-basic/application-customerloyalty/app.js:278:37
  90. at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  91. code: &#39;ERR_HTTP_HEADERS_SENT&#39;
  92. }

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

  1. /*
  2. * Get all EarnPoints transactions data
  3. * @param {String} cardId Card id to connect to network
  4. */
  5. earnPointsTransactionsInfo: async function (cardId, userType, userId) {
  6. // Create a new file system based wallet for managing identities.
  7. const walletPath = path.join(process.cwd(), &#39;/wallet&#39;);
  8. const wallet = await Wallets.newFileSystemWallet(walletPath);
  9. console.log(`Wallet path: ${walletPath}`);
  10. try {
  11. // Create a new gateway for connecting to our peer node.
  12. const gateway2 = new Gateway();
  13. await gateway2.connect(ccp, { wallet, identity: cardId, discovery: gatewayDiscovery });
  14. // Get the network (channel) our contract is deployed to.
  15. const network = await gateway2.getNetwork(&#39;mychannel&#39;);
  16. // Get the contract from the network.
  17. const contract = network.getContract(&#39;customerloyalty&#39;);
  18. console.log(`\nGet earn points transactions state for ${userType} ${userId}`);
  19. //for debug only
  20. console.log(await contract.submitTransaction(&#39;EarnPointsTransactionsInfo&#39;, &#39;userType&#39;, &#39;userId&#39;));
  21. //
  22. let earnPointsTransactions = await contract.submitTransaction(&#39;EarnPointsTransactionsInfo&#39;, userType, userId);
  23. //for debug only
  24. console.log(await contract.submitTransaction(&#39;EarnPointsTransactionsInfo&#39;, userType, userId));
  25. //
  26. earnPointsTransactions = JSON.parse(earnPointsTransactions.toString());
  27. console.log(earnPointsTransactions);
  28. // Disconnect from the gateway.
  29. await gateway2.disconnect();
  30. return earnPointsTransactions;
  31. }
  32. catch(err) {
  33. //print and return error
  34. console.log(err);
  35. let error = {};
  36. error.error = err.message;
  37. return error;
  38. }
  39. },
  1. usePointsTransactionsInfo: async function (cardId, userType, userId) {
  2. // Create a new file system based wallet for managing identities.
  3. const walletPath = path.join(process.cwd(), &#39;/wallet&#39;);
  4. const wallet = await Wallets.newFileSystemWallet(walletPath);
  5. console.log(`Wallet path: ${walletPath}`);
  6. try {
  7. // Create a new gateway for connecting to our peer node.
  8. const gateway2 = new Gateway();
  9. await gateway2.connect(ccp, { wallet, identity: cardId, discovery: gatewayDiscovery });
  10. // Get the network (channel) our contract is deployed to.
  11. const network = await gateway2.getNetwork(&#39;mychannel&#39;);
  12. // Get the contract from the network.
  13. const contract = network.getContract(&#39;customerloyalty&#39;);
  14. console.log(`\nGet use points transactions state for ${userType} ${userId}`);
  15. let usePointsTransactions = await contract.submitTransaction(&#39;UsePointsTransactionsInfo&#39;,userType, userId);
  16. usePointsTransactions = JSON.parse(usePointsTransactions.toString());
  17. console.log(usePointsTransactions);
  18. // Disconnect from the gateway.
  19. await gateway2.disconnect();
  20. return usePointsTransactions;
  21. }

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

  1. 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
  2. 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
  3. 2023-01-05 22:28:46 at JSON.parse (&lt;anonymous&gt;)
  4. 2023-01-05 22:28:46 at CustomerLoyalty.UsePointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:110:29)
  5. 2023-01-05 22:28:46 at processTicksAndRejections (node:internal/process/task_queues:96:5)
  6. 2023-01-05 22:28:46 at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
  7. 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
  8. 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
  9. 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
  10. 2023-01-05 22:28:46 at JSON.parse (&lt;anonymous&gt;)
  11. 2023-01-05 22:28:46 at CustomerLoyalty.EarnPointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:89:29)
  12. 2023-01-05 22:28:46 at processTicksAndRejections (node:internal/process/task_queues:96:5)
  13. 2023-01-05 22:28:46 at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
  14. 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
  15. 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
  16. 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
  17. 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
  18. 2023-01-05 22:32:53 at JSON.parse (&lt;anonymous&gt;)
  19. 2023-01-05 22:32:53 at CustomerLoyalty.UsePointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:110:29)
  20. 2023-01-05 22:32:53 at processTicksAndRejections (node:internal/process/task_queues:96:5)
  21. 2023-01-05 22:32:53 at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
  22. 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
  23. 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
  24. 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
  25. 2023-01-05 22:32:54 at JSON.parse (&lt;anonymous&gt;)
  26. 2023-01-05 22:32:54 at CustomerLoyalty.EarnPointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:89:29)
  27. 2023-01-05 22:32:54 at processTicksAndRejections (node:internal/process/task_queues:96:5)
  28. 2023-01-05 22:32:54 at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
  29. 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 :

  1. &#39;use strict&#39;;
  2. 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;;
  3. class CustomerLoyalty extends Contract {
  4. // Init function executed when the ledger is instantiated
  5. async instantiate(ctx) {
  6. console.info(&#39;============= START : Initialize Ledger ===========&#39;);
  7. await ctx.stub.putState(&#39;instantiate&#39;, Buffer.from(&#39;INIT-LEDGER&#39;));
  8. await ctx.stub.putState(allPartnersKey, Buffer.from(JSON.stringify([])));
  9. await ctx.stub.putState(earnPointsTransactionsKey, Buffer.from(JSON.stringify([])));
  10. await ctx.stub.putState(usePointsTransactionsKey, Buffer.from(JSON.stringify([])));
  11. console.info(&#39;============= END : Initialize Ledger ===========&#39;);
  12. }
  13. // Add a member on the ledger
  14. async CreateMember(ctx, member) {
  15. member = JSON.parse(member);
  16. await ctx.stub.putState(member.accountNumber, Buffer.from(JSON.stringify(member)));
  17. return JSON.stringify(member);
  18. }
  19. // Add a partner on the ledger, and add it to the all-partners list
  20. async CreatePartner(ctx, partner) {
  21. partner = JSON.parse(partner);
  22. await ctx.stub.putState(partner.id, Buffer.from(JSON.stringify(partner)));
  23. let allPartners = await ctx.stub.getState(allPartnersKey);
  24. allPartners = JSON.parse(allPartners);
  25. allPartners.push(partner);
  26. await ctx.stub.putState(allPartnersKey, Buffer.from(JSON.stringify(allPartners)));
  27. return JSON.stringify(partner);
  28. }
  29. // Record a transaction where a member earns points
  30. async EarnPoints(ctx, earnPoints) {
  31. earnPoints = JSON.parse(earnPoints);
  32. earnPoints.timestamp = new Date((ctx.stub.txTimestamp.seconds.low*1000)).toGMTString();
  33. earnPoints.transactionId = ctx.stub.txId;
  34. let member = await ctx.stub.getState(earnPoints.member);
  35. member = JSON.parse(member);
  36. member.points += earnPoints.points;
  37. await ctx.stub.putState(earnPoints.member, Buffer.from(JSON.stringify(member)));
  38. let earnPointsTransactions = await ctx.stub.getState(earnPointsTransactionsKey);
  39. earnPointsTransactions = JSON.parse(earnPointsTransactions);
  40. earnPointsTransactions.push(earnPoints);
  41. await ctx.stub.putState(earnPointsTransactionsKey, Buffer.from(JSON.stringify(earnPointsTransactions)));
  42. return JSON.stringify(earnPoints);
  43. }
  44. // Record a transaction where a member redeems points
  45. async UsePoints(ctx, usePoints) {
  46. usePoints = JSON.parse(usePoints);
  47. usePoints.timestamp = new Date((ctx.stub.txTimestamp.seconds.low*1000)).toGMTString();
  48. usePoints.transactionId = ctx.stub.txId;
  49. let member = await ctx.stub.getState(usePoints.member);
  50. member = JSON.parse(member);
  51. if (member.points &lt; usePoints.points) {
  52. throw new Error(&#39;Member does not have sufficient points&#39;);
  53. }
  54. member.points -= usePoints.points;
  55. await ctx.stub.putState(usePoints.member, Buffer.from(JSON.stringify(member)));
  56. let usePointsTransactions = await ctx.stub.getState(usePointsTransactionsKey);
  57. usePointsTransactions = JSON.parse(usePointsTransactions);
  58. usePointsTransactions.push(usePoints);
  59. await ctx.stub.putState(usePointsTransactionsKey, Buffer.from(JSON.stringify(usePointsTransactions)));
  60. return JSON.stringify(usePoints);
  61. }
  62. // Get earn points transactions of the particular member or partner
  63. async EarnPointsTransactionsInfo(ctx, userType, userId) {
  64. let transactions = await ctx.stub.getState(earnPointsTransactionsKey);
  65. transactions = JSON.parse(transactions);
  66. let userTransactions = [];
  67. for (let transaction of transactions) {
  68. if (userType === &#39;member&#39;) {
  69. if (transaction.member === userId) {
  70. userTransactions.push(transaction);
  71. }
  72. } else if (userType === &#39;partner&#39;) {
  73. if (transaction.partner === userId) {
  74. userTransactions.push(transaction);
  75. }
  76. }
  77. }
  78. return JSON.stringify(userTransactions);
  79. }
  80. // Get use points transactions of the particular member or partner
  81. async UsePointsTransactionsInfo(ctx, userType, userId) {
  82. let transactions = await ctx.stub.getState(usePointsTransactionsKey);
  83. transactions = JSON.parse(transactions);
  84. let userTransactions = [];
  85. for (let transaction of transactions) {
  86. if (userType === &#39;member&#39;) {
  87. if (transaction.member === userId) {
  88. userTransactions.push(transaction);
  89. }
  90. } else if (userType === &#39;partner&#39;) {
  91. if (transaction.partner === userId) {
  92. userTransactions.push(transaction);
  93. }
  94. }
  95. }
  96. return JSON.stringify(userTransactions);
  97. }
  98. // get the state from key
  99. async GetState(ctx, key) {
  100. let data = await ctx.stub.getState(key);
  101. let jsonData = JSON.parse(data.toString());
  102. return JSON.stringify(jsonData);
  103. }
  104. 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账本键中没有数据:

  1. % node --eval="JSON.parse(Buffer.from(''))"
  2. SyntaxError: JSON输入意外结束
  3. at JSON.parse (<anonymous>)

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

  1. async getEarnPointsTransactions(ctx) {
  2. const data = await ctx.stub.getState(earnPointsTransactionsKey);
  3. if (!data || data.length === 0) {
  4. return [];
  5. }
  6. return JSON.parse(data);
  7. }

还要考虑,您所有更新账本的交易都会修改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:

  1. % node --eval=&quot;JSON.parse(Buffer.from(&#39;&#39;))&quot;
  2. SyntaxError: Unexpected end of JSON input
  3. 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:

  1. async getEarnPointsTransactions(ctx) {
  2. const data = await ctx.stub.getState(earnPointsTransactionsKey);
  3. if (!data || data.length === 0) {
  4. return [];
  5. }
  6. return JSON.parse(data);
  7. }

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:

确定