Giter VIP home page Giter VIP logo

fabric-chaincode-node's Introduction

Hyperledger Fabric - Node.js Contracts

Build Status fabric-contract-api npm module fabric-shim npm module fabric-shim-api npm module Discord

This is the project to support the writing of Contracts with the node.js runtime.

Documentation

As an application developer, to learn about how to implement "Smart Contracts" for Hyperledger Fabric using Node.js, please visit the API documentation and follow the tutorial links.

Compatibility

For details on what Nodejs runtime and versions of Hyperledger Fabric can be used please see the compatibility document.

npm Shrinkwrap

In line with the advice from npm on shrinkwrap the modules published do not contain a npm-shrinkwrap.json file.

It is STRONGLY recommended therefore that after testing, and before putting your contract into production a npm-shrinkwrap.json file is created. When the chaincode is install it will be via a npm install --production command.

Contributing

If you are interested in contributing updates to this project, please start with the contributing guide.

There is also a release guide describing the process for publishing new versions.


License

Hyperledger Project source code files are made available under the Apache License, Version 2.0 (Apache-2.0), located in the LICENSE file. Hyperledger Project documentation files are made available under the Creative Commons Attribution 4.0 International License (CC-BY-4.0), available at http://creativecommons.org/licenses/by/4.0/.

fabric-chaincode-node's People

Contributors

asararatnakar avatar awjh-ibm avatar bestbeforetoday avatar christo4ferris avatar davidkel avatar davidkhala avatar denyeart avatar fravlaca avatar harrisob avatar heatherlp avatar jerrylum avatar jimthematrix avatar jkneubuh avatar jt-nti avatar kemi04 avatar lesleyannjordan avatar liam-grace avatar lindluni avatar mastersingh24 avatar mbwhite avatar mergify[bot] avatar rameshthoomu avatar ryjones avatar s7santosh avatar sammyrasha avatar shimos avatar vijaypunugubati avatar winderica avatar yuki-kon avatar zhaochy1990 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fabric-chaincode-node's Issues

iterator of getHistoryForKey() sdk method is not returning the txId and timestamp

Hi @mbwhite ,

I work as an Oracle BlockChain Platform developer. Our product "Oracle Blockchain Platform - AppBuilder" is used by end users to create smart contracts based on their business logic.

Following the grpc issue, we recently upgraded the fabric-shim version to 2.5.1 in Node.js chaincode. The fabric-shim has been updated, and the iterator output of getHistoryForKey(), no longer returns the txId and timestamp.

The iterator output from getHistoryForKey() previously returned the txId, timestamp, and value; however, in the most recent release, it only returns the value and does not return the txId and timestamp.

An Example:

getHistoryForKey() iterator result of fabric-shim 2.2.3:

KeyModification {
txId: '7c8a377c9334075d0770deb844f009fd04200dcb4d485ea449f8a3b8069bba6d',
value: <Buffer 7b 22 61 73 73 65 74 54 79 70 65 22 3a 22 6f 61 63 63 6f 75 6e 74 22 2c 22 61 63 63 6f 75 6e 74 49
64 22 3a 22 6f 61 63 63 6f 75 6e 74 7e 34 32 65 38 ... 136 more bytes>,
timestamp: Timestamp {
seconds: Long { low: 1673967527, high: 0, unsigned: false },
nanos: 346000000
}
}

getHistoryForKey() iterator result of fabric-shim 2.5.1:

{
value: Buffer(729)
}

Because this is an enterprise organisation, we are only allowed to use the most recent version for licensing purposes, so we cannot use any older versions of the APIs'. So a quick resolution will help us.

Bundling Node.js chaincode for offline install

Node.js chaincode build containers require access to the npm registry when installing chaincode.
This becomes an issue for peers that are "offline" (e.g. peers from cloud providers) and do not have access to the npm registry. Simply running "npm install" before packaging chaincode with "peer lifecycle package" does not solve the problem alone, since the package command ignores the node_modules directory.

We have identified two possible ways to solve this:

  • Creating the tarball package manually without using "peer lifecycle package".
  • Bundling the application (e.g. with esbuild) before packaging it with "peer lifecycle package".

While the first option works fine, it does make the process of deploying Node.js chaincode a lot more complex than deploying Go or Java chaincode. We would therefore prefer the second option, however, we are still required to add fabric-shim as a module outside the bundle, so that "fabric-chaincode-node start" is available when bootstrapping the chaincode.

Would it be possible to start the application without requiring "fabric-chaincode-node start" as an external script, e.g. by calling the bootstrap function in the chaincode's index.js instead?
Are there any other simple ways to solve this that I've missed or is manually creating the tarball the suggested approach for now?

This issue was also discussed in #197 but seems unresolved

fabric-shim1.4 has build issues in windows

fabric-shim does not build properly in windows.
It needs manual installation of openssl headers in C:/ drive manually for successful installation.

D:\Chaincode1\node_modules@theledger\fabric-mock-stub\node_modules\fabric-shim\node_modules@ampretia\x509>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\....\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "-m" switch.
addon.cc
x509.cc
win_delay_load_hook.cc
D:\Chaincode1\node_modules@theledger\fabric-mock-stub\node_modules\fabric-shim\node_modules@ampretia\x509\include\x509.h(14,10): fatal error C1083: Cannot open include file: 'openssl/asn1.h': No such file or directory (compil
ing source file ..\src\addon.cc) [D:\Chaincode1\node_modules@theledger\fabric-mock-stub\node_modules\fabric-shim\node_modules@ampretia\x509\build\x509.vcxproj]
D:\Chaincode1\node_modules@theledger\fabric-mock-stub\node_modules\fabric-shim\node_modules@ampretia\x509\include\x509.h(14,10): fatal error C1083: Cannot open include file: 'openssl/asn1.h': No such file or directory (compil
ing source file ..\src\x509.cc) [D:\Chaincode1\node_modules@theledger\fabric-mock-stub\node_modules\fabric-shim\node_modules@ampretia\x509\build\x509.vcxproj]

Is there a plan to upgrade fabric-shim1.4 to fabric-shim2.2 ?
These issues don't happen in fabric-shim2.2 because they have moved away from @ampretia\x509 in 2.2.

TypeError on chaincode start with fabric-shim >=2.5.1

A mismatch of @grpc/grpc-js versions between the @hyperledger/fabric-protos package and fabric-shim (version >=2.5.1) appears to cause the following error when the chaincode container is started:

TypeError: Channel credentials must be a ChannelCredentials object

A work-around appears to be to run npm dedupe following npm install (or as a postinstall npm script action).

Here are the Docker logs collected from a failure of the asset-transfer-sbe TypeScript chaincode from the fabric-samples repository:

+ CHAINCODE_DIR=/usr/local/src
+ cd /usr/local/src
+ npm start -- --peer.address peer0.org1.example.com:7052

> [email protected] start
> fabric-chaincode-node start --peer.address peer0.org1.example.com:7052

2023-09-17T14:26:14.091Z info [c-api:./lib/annotations/object.js]                 @Object args: Target -> %s "Function"
2023-09-17T14:26:14.092Z info [c-api:./lib/annotations/transaction.js]            @Transaction args: "Property Key -> CreateAsset, Commit -> true,","Target ->","AssetContract"
2023-09-17T14:26:14.093Z info [c-api:./lib/annotations/transaction.js]            @Transaction args: "Property Key -> ReadAsset, Commit -> false,","Target ->","AssetContract"
2023-09-17T14:26:14.093Z info [c-api:./lib/annotations/transaction.js]            @Transaction args: "Property Key -> UpdateAsset, Commit -> true,","Target ->","AssetContract"
2023-09-17T14:26:14.093Z info [c-api:./lib/annotations/transaction.js]            @Transaction args: "Property Key -> DeleteAsset, Commit -> true,","Target ->","AssetContract"
2023-09-17T14:26:14.093Z info [c-api:./lib/annotations/transaction.js]            @Transaction args: "Property Key -> TransferAsset, Commit -> true,","Target ->","AssetContract"
2023-09-17T14:26:14.094Z info [c-api:./lib/annotations/info.js]                   @Info args: "Info -> [object Object],","Target ->","AssetContract"
2023-09-17T14:26:14.101Z info [c-api:contracts-spi/bootstrap.js]                  No metadata file supplied in contract, introspection will generate all the data
2023-09-17T14:26:14.154Z info [c-api:lib/handler.js]                              Creating new Chaincode Support Client for peer comminications
fabric-chaincode-node start --peer.address localhost:7051 --chaincode-id-name mycc

Options:
      --help                                  Show help  [boolean]
  -v, --version                               Show version number  [boolean]
      --peer.address  [string] [required]
      --grpc.max_send_message_length  [number] [default: -1]
      --grpc.max_receive_message_length  [number] [default: -1]
      --grpc.keepalive_time_ms  [number] [default: 110000]
      --grpc.http2.min_time_between_pings_ms  [number] [default: 110000]
      --grpc.keepalive_timeout_ms  [number] [default: 20000]
      --grpc.http2.max_pings_without_data  [number] [default: 0]
      --grpc.keepalive_permit_without_calls  [number] [default: 1]
      --ssl-target-name-override  [string]
      --chaincode-id-name  [string] [required]
      --module-path  [string] [default: "/usr/local/src"]

TypeError: Channel credentials must be a ChannelCredentials object
    at new ChannelImplementation (/usr/local/src/node_modules/@grpc/grpc-js/build/src/channel.js:28:19)
    at new Client (/usr/local/src/node_modules/@grpc/grpc-js/build/src/client.js:65:36)
    at new ServiceClientImpl (/usr/local/src/node_modules/@grpc/grpc-js/build/src/make-client.js:58:5)
    at new ChaincodeSupportClient (/usr/local/src/node_modules/fabric-shim/lib/handler.js:247:24)
    at Shim.start (/usr/local/src/node_modules/fabric-shim/lib/chaincode.js:129:24)
    at Bootstrap.register (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/bootstrap.js:43:18)
    at Bootstrap.bootstrap (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/bootstrap.js:56:25)
    at async exports.handler (/usr/local/src/node_modules/fabric-shim/lib/cmds/startCommand.js:38:5)

jsdocs are not getting published

The jsdocs are no longer getting published.

For example the source file:
https://github.com/hyperledger/fabric-chaincode-node/blob/main/docs/_jsdoc/tutorials/using-contractinterface.md

Should get pushed to gh-pages branch here:
https://github.com/hyperledger/fabric-chaincode-node/blob/gh-pages/main/api/tutorial-using-contractinterface.html

Which then gets rendered here:
https://hyperledger.github.io/fabric-chaincode-node/main/api/tutorial-using-contractinterface.html

Look at the "fabric-contract-api" version in the above pages, you'll see the first link references 2.5.0 while the latter links still reference the outdated 2.4.1.

It looks like the jsdocs used to get published in the Azure Pipelines job at:
https://github.com/hyperledger/fabric-chaincode-node/blob/main/ci/azure-pipelines.yml#L218-L283

However, when Azure Pipelines was replaced by GitHub Actions, it looks like the jsdoc job did not get migrated over.

@mbwhite @bestbeforetoday I assume we should still be publishing the jsdocs as part of the GitHub Actions? What trigger would be appropriate?

Also, I'm a little confused because the tutorial https://github.com/hyperledger/fabric-chaincode-node/blob/main/TUTORIAL.md looks like a copy paste of https://github.com/hyperledger/fabric-chaincode-node/blob/main/docs/_jsdoc/tutorials/using-contractinterface.md. Should one of them be removed?

npmjs.com shows latest version @2.2.3

Hi folks,

For npmjs.com packages fabric-shim and fabric-contract-api the latest release is still 2.2.3 and not 2.4.2. I don't know if it is within this scope here to upgrade it, but I figured I'd point it out if someone forgot to update the latest version at npmjs.com

Use Node 20

As a Node chaincode developer
I want to build and run my chaincode with Node 20
So that I can stay current with latest features and bug fixes

Node 20 became the active LTS release on 2023-10-24. Update chaincode NPM packages and fabric-nodeenv Docker image to use Node 20.

Transition the FV tests to use Microfab

As the the Java Chaincode, the Node.js FV tests need to transition to use the better approach of microfab.

Rather than the reliable but long widened pulling of the fabric-samples test-network

Fix minor TypeScript issues

I am willing to create a pull request with patch commits to fix some of the problems related to the TypeScript definitions and setups. I will point them out one by one and fix them with patch commits.

Document how to start node chaincode as a service, including how to set grpc parameters

In the doc tutorial at https://hyperledger.github.io/fabric-chaincode-node/main/api/ where it talks about how to start a chaincode:

"scripts": {
    "start": "fabric-chaincode-node start"
}

we should also talk about how to start chaincode as a service, and how to set grpc parameters in the startup, e.g.:

"scripts": {
                "start": "fabric-chaincode-node server --grpc.max_send_message_length 100000000 --grpc.max_receive_message_length 100000000"
        }

This would increase the grpc limit from the default of 4MB to 100MB.

Note that passing grpc parameters recently became possible in node chaincode v2.5.4.

Note also that the source for this doc topic is at:
https://github.com/hyperledger/fabric-chaincode-node/blob/main/docs/_jsdoc/index.md

Release v2.5

  • Update the package.json
  • Changelog update
  • release notes

Update to use the newly published protobuf library

Update the chaincode to use the published node.js protobuf library. Instead of using a local copy hand crafted into the repo. On attempting to recreate this, the tooling used didn't appear to be readily available.

Therefore adopting the published library from fabric-protos is a good idea.

FYI @jt-nti @bestbeforetoday

fabirc-shim latest-1.4 support for nodejs v16.x.x

Hi Team,

When can we expect support for nodejs v16.x.x and npm v8.x.x for the latest 1.4.x version of fabric-shim?

Getting this error while trying to install [email protected]:

npm ERR! code 1
npm ERR! path C:\Users\PravallikaP\Documents\Syniverse\Workspace\ucs-chaincode\node_modules\fabric-shim\node_modules\grpc
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp rebuild
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | win32 | x64
npm ERR! gyp info find Python using Python version 3.10.6 found at "C:\Users\PravallikaP\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"
npm ERR! gyp info find VS using VS2017 (15.9.28307.1800) found at:
npm ERR! gyp info find VS "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools"
npm ERR! gyp info find VS run with --verbose for detailed information
npm ERR! gyp info spawn C:\Users\PravallikaP\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args 'C:\Users\PravallikaP\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\gyp\gyp_main.py',
npm ERR! gyp info spawn args 'binding.gyp',
npm ERR! gyp info spawn args '-f',
npm ERR! gyp info spawn args 'msvs',
npm ERR! gyp info spawn args '-I',
npm ERR! gyp info spawn args 'C:\Users\PravallikaP\Documents\Syniverse\Workspace\ucs-chaincode\node_modules\fabric-shim\node_modules\grpc\build\config.gypi',
npm ERR! gyp info spawn args '-I',
npm ERR! gyp info spawn args 'C:\Users\PravallikaP\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\addon.gypi',
npm ERR! gyp info spawn args '-I',
npm ERR! gyp info spawn args 'C:\Users\PravallikaP\AppData\Local\node-gyp\Cache\16.17.0\include\node\common.gypi',
npm ERR! gyp info spawn args '-Dlibrary=shared_library',
npm ERR! gyp info spawn args '-Dvisibility=default',
npm ERR! gyp info spawn args '-Dnode_root_dir=C:\Users\PravallikaP\AppData\Local\node-gyp\Cache\16.17.0',
npm ERR! gyp info spawn args '-Dnode_gyp_dir=C:\Users\PravallikaP\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp',
npm ERR! gyp info spawn args '-Dnode_lib_file=C:\\Users\\PravallikaP\\AppData\\Local\\node-gyp\\Cache\\16.17.0\\<(target_arch)\\node.lib',
npm ERR! gyp info spawn args '-Dmodule_root_dir=C:\Users\PravallikaP\Documents\Syniverse\Workspace\ucs-chaincode\node_modules\fabric-shim\node_modules\grpc',
npm ERR! gyp info spawn args '-Dnode_engine=v8',
npm ERR! gyp info spawn args '--depth=.',
npm ERR! gyp info spawn args '--no-parallel',
npm ERR! gyp info spawn args '--generator-output',
npm ERR! gyp info spawn args 'C:\Users\PravallikaP\Documents\Syniverse\Workspace\ucs-chaincode\node_modules\fabric-shim\node_modules\grpc\build',
npm ERR! gyp info spawn args '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp: Undefined variable module_name in binding.gyp while trying to load binding.gyp
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: gyp failed with exit code: 1
npm ERR! gyp ERR! stack at ChildProcess.onCpExit (C:\Users\PravallikaP\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\configure.js:284:16)
npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
npm ERR! gyp ERR! System Windows_NT 10.0.19044
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\PravallikaP\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd C:\Users\PravallikaP\Documents\Syniverse\Workspace\ucs-chaincode\node_modules\fabric-shim\node_modules\grpc
npm ERR! gyp ERR! node -v v16.17.0
npm ERR! gyp ERR! node-gyp -v v9.1.0
npm ERR! gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\PravallikaP\AppData\Local\npm-cache_logs\2022-09-06T06_27_11_493Z-debug-0.log

jsdoc publish task is failing

fatal: could not read Password for '[https://<PAT>@github.com'](https://<PAT>@github.com%27/): terminal prompts disabled

Publish unstable / snapshot packages on every change

As a contributor
I want snapshot versions of fabric-chaincode-shim to be published on every change
So that I can use development fixes or features before a formal release is published

The push.yml workflow should be extended to publish an "unstable" version of the chaincode packages on every merged pull request. Publishing might be better to GitHub Packages rather than the public NPM registry to avoid any risk of publishing an unintended release version and to avoid too much clutter in the public NPM registry, but either acceptable solutions.

"Unstable" builds should:

  • Have -unstable (or some other qualifier) appended to their version.
  • Be tagged as unstable.
  • Have dependencies rewritten by the publishing process to point to similarly versioned chaincode packages.

The logic for rewriting dependency versions would be similar (or reuse directly) the updateversions.sh script.

The fabric-gateway publishing process might be useful as a reference:

The GitHub Actions documentation on publishing Node packages is also a useful reference.

Chat stream with peer cancelled or closed when starting chaincode

When using a NodeJS chaincode, the chaincode container will start but fail on the first transaction. In either the peer logs or chaincode logs there will be errors about the "chat stream being closed or cancelled."

The peer-chaincode connection will be dropped and the chaincode container will also exit.

Affected
We've seen this affect 2.2 2.4 and the 2.5 release; note that this is an issue pulling in an updated dependency of the chaincode-node libraries. Chaincode that is already running won't be affected.

IF you explicitly use the 2.2 or 2.4 and are fixed at a 2.2 or 2.4 level the problem should not exist. These are already locked into 1.8.1 grpc-js. However you may have a semver prefix that would resolve to the most recent 2.5.0

Cause

grpc-js, a dependency of fabric-shim for javascript chaincode has had a recent update that appears to have broken fabric-shim. New installs will pick up this latest grpc-js dependency and is causing javascript chaincodes to terminate.

The 1.8.2 grpc-js release is problematic release; 1.8.1 is the last good one.

grpc-js issue grpc/grpc-node#2318

Workaround

a) Lock your fabric-contract-api fabric-shim libraries to specifically 2.4.2

b) Install a specific version of grpc-js in your own chaincode's package.json

npm install --save @grpc/[email protected]

Double check the package.json has the version of exactly 1.8.1 - ensure there are no ^ or ~ or other prefix.
This should ensure that when the dependencies are resolved the 1.8.1 will be used. Note that we've not tested with all node module installers. We're confident this approach works with node16's npm.

It is also recommended to use the npm shrinkwrap mechanism to lock down as many dependencies as possible when deploying.

Fixes

  • Hopefully a fix will be made available with grpc-js at some point.
  • The release-2.5 branch of fabric-chaincode-node has locked grpc-js to 1.8.1
    - We will see if it's possible to do patch releases of 2.4/2.2 fabric-chaincode-node. The chaincode
  • Lock explicitly to 2.4.2 fabric node modules.

Inconsistent formatting of x509 string returned by ClientIdentity.getID()

The string returned by ClientIdentity.getID() in Node.js chaincode is formatted differently from the strings returned by Go and Java chaincode. To align with the other two implementations, the order of attributes in each DN should be reversed and forward slash delimeters should be replaced with commas.

An example:

  • Node.js: x509::/C=US/ST=California/L=San Francisco/OU=COP/CN=peer0.org1.example.com::/C=US/ST=California/L=San Francisco/O=org1.example.com/OU=COP/CN=ca.org1.example.com
  • Go: x509::CN=peer0.org1.example.com,OU=COP,L=San Francisco,ST=California,C=US::CN=ca.org1.example.com,OU=COP,O=org1.example.com,L=San Francisco,ST=California,C=US
  • Java: x509::CN=peer0.org1.example.com, OU=COP, L=San Francisco, ST=California, C=US::CN=ca.org1.example.com, OU=COP, O=org1.example.com, L=San Francisco, ST=California, C=US

This caused a bit of confusion for us when experimenting with chaincode written in multiple languages and I would expect that this could be a source of confusion for others as well. I believe that aligning the strings produced by each implementation would make parsing/comparison of the IDs more predictable.

Scheduled vulnerability scan

As a maintainer
I want a vulnerability scan of runtime dependencies to be run on a regular schedule
So that vulnerabilities in dependencies can be identified and fixed promptly

A vulnerability scan is currently run in the build (see test.yaml). This is not optimal since it can prevent changes to address issues going in that are unrelated to a vulnerability that may have been identified in a dependency since the last commit, or due to a vulnerability that currently has no available fix. Decoupling the build and scan provides more flexibility to address issues and to run the vulnerability scan more regularly that the main build.

The vulnerability scan should only be run against runtime dependencies, and should exclude development (test) dependencies. This can be achieved similar to the existing audit, but using:

npm init --yes
npm install --save --package-lock-only --registry http://localhost:4873 \
    fabric-shim fabric-shim-api fabric-contract-api
npm audit --omit=dev

fabric-shim incorrectly implements interface ChaincodeStub from fabric-shim-api

(copied from https://jira.hyperledger.org/browse/BE-882)

I'm using TS and just upgraded to the new 2.2.2 version of fabric-shim ; getting the following error:

 

node_modules/fabric-shim/types/index.d.ts:89:18 - error TS2420: Class 'import("fabric-shim").ChaincodeStub' incorrectly implements interface 'import("fabric-shim-api").ChaincodeStub'.
Property 'getDateTimestamp' is missing in type 'import("fabric-shim").ChaincodeStub' but required in type 'import("fabric-shim-api").ChaincodeStub'.

89 export class ChaincodeStub implements IChaincodeStub {


node_modules/fabric-shim-api/types/index.d.ts:63:9
63 getDateTimestamp(): Date;

'getDateTimestamp' is declared here.

help me.. im a korean student

1. Build a network passively

  • I am now trying to build test-network manually by entering commands directly without using network.sh.
# These two lines are commands provided in fabric docs.
# ./network.sh will not be used.
$ ./network.sh up createChannel -c mychannel -ca
$ ./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-javascript/ -ccl javascript

2. Sequence of operations

  • This is the task sequence for manual construction of test-network.
  • Refer to the network.sh file below.
# ca container - orderer, org1, org2
$ docker-compose -f compose/compose-ca.yaml -f compose/docker/docker-compose-ca.yaml up -d

# Setting environment variables
export PATH=${PWD}/../bin:$PATH
export FABRIC_CFG_PATH=$PWD/../config/

# Generate certificate (orderer, org1, org2)
. organizations/fabric-ca/registerEnroll.sh
createOrg1
createOrg2
createOrderer

# Create connection.json file
./organizations/ccp-generate.sh

It worked fine up to this point.

3. next step & error

  • The next task requires creating orderer, org1, and org2 containers.
  • I think the command to create orderer, org1, and org2 containers is one of the two below.
  • However, errors occur in both cases.
docker-compose -f compose/compose-test-net.yaml -f compose/docker/docker-compose-test-net.yaml up -d
# An error occurs as follows
# invalid spec: :/host/var/run/docker.sock: empty section between colons

docker-compose -f compose/compose-test-net.yaml up -d
# The orderer container was created normally.
# The org1 and org2 containers are output as “exited”.
# The logs of org1 and org2 containers are as follows.
# Fatal error when initializing core config: FABRIC_CFG_PATH /etc/hyperledger/peercfg does not exist

4. Please save me

  • If you know a solution, please let me know.

Incorrect Type Definition of ChaincodeResponse

Shim.success and Shim.error functions return SuccessResponse and ErrorResponse. The return types are defined using JSDoc and both type definitions are also defined using JSDoc in the same file.

However, for the TypeScript definition, ChaincodeResponse is used instead. It requires three properties including status, message, and payload. But both users Shim.success and Shim.error do not return an object with all three properties at the same time. In this case, I believe the type definition of ChaincodeResponse is incorrect.

image image

Update @grpc/grpc-js

Security vulnerability scan found an issue with grpc-js:
https://github.com/hyperledger/fabric-chaincode-node/actions/runs/9475979432

I was going to update fabric-shim package.json to 1.8.22, but then realized I don't understand all the dependency files such as common/config/rush/pnpm-lock.yaml. Is this file managed by pnpm or rush? What command should be used to update the dependencies?

Is looks like CONTRIBUTING.md has information about rush, but I wanted to confirm that information is up to date and perhaps update it with the proper rush guidance for updating a dependency.

Also, is it typically safe and advisable to jump to new minor versions of grpc-js, e.g. 1.9.x or 1.10.x?

@bestbeforetoday @mbwhite Can you advise?

Update main CI pipeline

The 2.4.0 publish highlighted some build issues; with hindsight these have been hiding in plain sight.

The build-data.yaml script was failing; but wasn't correctly failing the build.
It also was pulling in a file that we removed thinking it wasn't used.

Resolve the failing issue, and also fix the location of the fabric version

getCreator and ProposedCreator documentation looks to be incorrect

Looking at the docs for getCreator you see

getCreator()
Returns the identity object of the chaincode invocation's submitter
Returns:
Type
ProposalCreator

But the type of ProposalCreator doesn't match the typescript definition which shows

getCreator(): SerializedIdentity;

Looking at the docs about ProposalCreator gives

new ProposalCreator()
This object contains the essential identity information of the chaincode invocation's submitter, including its organizational affiliation (mspid) and certificate (id_bytes)
Properties:
Name	Type	Description
mspid	string	The unique ID of the Membership Service Provider instance that is associated to the identity's organization and is able to perform digital signing and signature verification

not sure you would ever want to create one of these in your code but also the description on what this object is is not correct as it doesn't list the certificate bytes in the properties but does refer to it incorrectly in the description as id_bytes. Looking at the typescript definition for SerializedIdentity it shows

 interface SerializedIdentity {
        mspid: string;
        idBytes: Uint8Array;
    }

which describes it correctly

Wrong getTxTimestamp

[copied from https://github.com/hyperledger/fabric/issues/4219]

Description

I get the wrong format timestamp
node_modules/fabric-shim-api/types/index.d.ts

getTxTimestamp(): Timestamp;
/* ---- */
interface Timestamp {
  seconds: Long;
  nanos: number;
}

dependencies

"dependencies": {
    "fabric-contract-api": "^2.0.0",
    "fabric-shim": "^2.0.0"
},

Versions

fabric-ca-client:
Version: 1.5.5
Go version: go1.18.2
OS/Arch: linux/amd64

fabric-ca-server:
Version: 1.5.5
Go version: go1.18.2
OS/Arch: linux/amd64

Steps to reproduce

My code in contract emit the History event

const action = { action: 'deposit', amount, userId, timestamp: ctx.stub.getTxTimestamp()};
ctx.stub.setEvent('Balance:History', Buffer.from(JSON.stringify(action)));

My listener

let listener;
try {
    listener = async (event) => {
        const payload = JSON.parse(event.payload.toString());
        console.log(`*** Event: ${event.eventName}`);
        console.log(payload);
    };
    await contract.addContractListener(listener);
} catch (eventError) {
    console.log(`<-- Failed: Setup contract events - ${eventError}`);
}

I see in the console

*** Event: Balance:History
{
  action: 'deposit',
  amount: '100',
  userId: 'fedor',
  timestamp: {
    wrappers_: null,
    arrayIndexOffset_: -1,
    array: [ 1684164619, 536000000 ],
    pivot_: 1.7976931348623157e+308,
    convertedPrimitiveFields_: {}
  }
}

Bad format field timestamp

ChaincodeMessageHandler calls non-existent cancel() function on stream

The stream end event handler within the fabric-shim's ChaincodeMessageHandler chat() method calls stream.cancel(). This does not exist in the grpc-js duplex stream implementation. It maybe should be calling stream.end() instead.

TypeError: stream.cancel is not a function
    at ServerDuplexStreamImpl.<anonymous> (/home/runner/work/fabric-samples/fabric-samples/full-stack-asset-transfer-guide/contracts/asset-transfer-typescript/node_modules/fabric-shim/lib/handler.js:356:20)
    at ServerDuplexStreamImpl.emit (node:events:513:28)

Chaincode does not start due to missing dependency in fabric-shim

Container logs:

+ cd /usr/local/src
+ npm start -- --peer.address peer0.hospital.healthcert.io:7052

> [email protected] start
> fabric-chaincode-node start --peer.address peer0.hospital.healthcert.io:7052

node:internal/modules/cjs/loader:998
  throw err;
  ^

Error: Cannot find module 'fast-safe-stringify'
Require stack:
- /usr/local/src/node_modules/fabric-shim/lib/logger.js
- /usr/local/src/node_modules/fabric-shim/cli.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
    at Function.Module._load (node:internal/modules/cjs/loader:841:27)
    at Module.require (node:internal/modules/cjs/loader:1067:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/usr/local/src/node_modules/fabric-shim/lib/logger.js:12:23)
    at Module._compile (node:internal/modules/cjs/loader:1165:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
    at Module.load (node:internal/modules/cjs/loader:1043:32)
    at Function.Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1067:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/local/src/node_modules/fabric-shim/lib/logger.js',
    '/usr/local/src/node_modules/fabric-shim/cli.js'
  ]

Dependencies of the contract:

  "dependencies": {
    "fabric-contract-api": "^2.5.2",
    "fabric-shim": "^2.5.2"
  },
  "devDependencies": {
    "tslint": "^6.1.3",
    "typescript": "^4.9.5"
  }

I believe this is because the fast-safe-stringify package is used in fabric-shim but is not included in it's package.json. It is only included as a dependency of fabric-contract-api.

const safeStringify = require('fast-safe-stringify');

ChaincodeServer grpc.max_receive_message_length and grpc.max_send_message_length arguments

I'm having trouble passing grpc.max_receive_message_length and grpc.max_send_message_length arguments into a chaincode instance running as a server.

I've tried adding them to the cli command but haven't had any luck:
./src/chaincode.js --peer.address=0.0.0.0:9999 --grpc.max_receive_message_length=104857600 --grpc.max_send_message_length=104857600

I was wonder if someone could confirm that this functionality has been implemented yet, or if there's an alternative way to pass these values.

createCompositeKey function can't work normally

I test ctx.stub.createCompositeKey(objectType, attributes) ,but return undefined. I coded according to the requirements of the document, but it still can't be used normally.
my package.json

{
  "name": "vppcc",
  "version": "0.0.1",
  "description": "My Smart Contract",
  "main": "index.js",
  "engines": {
    "node": ">=8",
    "npm": ">=5"
  },
  "scripts": {
    "lint": "eslint .",
    "pretest": "npm run lint",
    "test": "nyc mocha --recursive",
    "start": "fabric-chaincode-node start"
  },
  "engineStrict": true,
  "author": "John Doe",
  "license": "Apache-2.0",
  "dependencies": {
    "fabric-contract-api": "^2.2.0",
    "fabric-shim": "^2.2.0"
  },
  "devDependencies": {
    "chai": "^4.2.0",
    "chai-as-promised": "^7.1.1",
    "eslint": "^6.8.0",
    "mocha": "^7.1.1",
    "nyc": "^15.0.0",
    "sinon": "^9.0.1",
    "sinon-chai": "^3.5.0",
    "winston": "^3.2.1"
  },
  "nyc": {
    "exclude": [
      ".eslintrc.js",
      "coverage/**",
      "test/**"
    ],
    "reporter": [
      "text-summary",
      "html"
    ],
    "all": true,
    "check-coverage": true,
    "statements": 100,
    "branches": 100,
    "functions": 100,
    "lines": 100
  }
}

my test file

'use strict';

const { ChaincodeStub, ClientIdentity } = require('fabric-shim');
const { VppccContract } = require('..');
const winston = require('winston');

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');

chai.should();
chai.use(chaiAsPromised);
chai.use(sinonChai);

class TestContext {

    constructor() {
        this.stub = sinon.createStubInstance(ChaincodeStub);
        this.clientIdentity = sinon.createStubInstance(ClientIdentity);
        this.logger = {
            getLogger: sinon.stub().returns(sinon.createStubInstance(winston.createLogger().constructor)),
            setLevel: sinon.stub(),
        };
    }

}

describe('VppccContract', () => {

    let contract;
    let ctx;

    beforeEach(() => {
        contract = new VppccContract();
        ctx = new TestContext();
        ctx.stub.getState.withArgs('1001').resolves(Buffer.from('{"value":"vppcc 1001 value"}'));
        ctx.stub.getState.withArgs('1002').resolves(Buffer.from('{"value":"vppcc 1002 value"}'));
    });

    describe('#vppccExists', () => {

        it('should return true for a vppcc', async () => {
            await contract.vppccExists(ctx, '1001').should.eventually.be.true;
        });

        it('should return false for a vppcc that does not exist', async () => {
            await contract.vppccExists(ctx, '1003').should.eventually.be.false;
        });

       console.log('ctx.stub.createCompositeKey  return value:', ctx.stub.createCompositeKey('test', ['1001']));

    });
});

running test file , the result is:

ctx.stub.createCompositeKey  return value: undefined

I also look up hyperledger/fabric-samples, I find them use await, like this:

let colorNameIndexKey = await ctx.stub.createCompositeKey(indexName, [asset.color, asset.assetID]);

I try it, but the result is the same.
For such the result, I feel very confused.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.