hyperledger / fabric-chaincode-node Goto Github PK
View Code? Open in Web Editor NEWHyperledger Fabric Node.js Smart Contracts
Home Page: https://hyperledger.github.io/fabric-chaincode-node/
License: Apache License 2.0
Hyperledger Fabric Node.js Smart Contracts
Home Page: https://hyperledger.github.io/fabric-chaincode-node/
License: Apache License 2.0
fatal: could not read Password for '[https://<PAT>@github.com'](https://<PAT>@github.com%27/): terminal prompts disabled
As a chaincode developer
I want chaincode contained images tagged as 3.0
in Docker Hub
So that I can deploy chaincode to Fabric v3 using the default (Docker) chaincode builder
By default, Fabric uses chaincode container images tagged with the same major/minor version number as the Fabric peer. For example, Fabric v3.0.x will look for a hyperledger/fabric-nodeenv:3.0
Docker image in Docker Hub.
Visit the link https://github.com/hyperledger/fabric-chaincode-node this .
Now click on "npm on shrinkwrap" links as mentioned below
https://docs.npmjs.com/files/shrinkwrap.json#description
we will be redirected to Github " 404 file not found " page.
Release v2.5.3 has been published - tagged in this repository and published to the npm registry - but v2.5.2 is still tagged in the npm registry as the latest release.
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
(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.
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.
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
.
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.
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.
As mentioned here
https://hlf.readthedocs.io/en/latest/developapps/transactioncontext.html#stub
and also
https://github.com/hyperledger/fabric-chaincode-go/blob/main/shim/interfaces.go
The information about it only be usable in the outer most chaincode should be added
posting chain code and dependencies res from getHistoryForKey is not returning txid and timestamps
Add the private data purge support.
Add ESLint TypeScript support and format the code
Commits: https://github.com/Jerrylum/fabric-chaincode-node/commits/dev-417/
Related to #415
I looked on
https://hyperledger.github.io/fabric-chaincode-node/release-2.2/api/index.html
and cannot find this class documented yet it is important for users who want to use state based endorsement
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:
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.
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
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:
-unstable
(or some other qualifier) appended to their version.unstable
.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.
# 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
# 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.
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
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
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
As a Node chaincode developer
I want to build and run my chaincode with Node 22
So that I can stay current with latest features and bug fixes
Node 22 is scheduled to become the active LTS release on 2024-10-29. Update fabric-nodeenv Docker image to use Node 22.
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.
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?
Both Visual Studio Code and tsc emit the error TS2307: Cannot find module 'fabric-contract-api' or its corresponding type declarations.
. It can be solved by adding "../../types/" as type package to **/test/typescript/tsconfig.json
Patch commit: Jerrylum@4b3a2ca
Related to #415
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
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?
With the change to the new protobuf libraries, and it's different API, the nOutOf was missed from statebased KeyEndorsementPolicy
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)
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.
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
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)
In the docs published at https://hyperledger.github.io/fabric-chaincode-node/main/api/, documentation for the newly added annotations are their effect is missing.
These annotations can be found at - https://github.com/hyperledger/fabric-chaincode-node/tree/main/apis/fabric-contract-api/lib/annotations
While these are also used in the fabric-samples, these are not documented for new developers.
[copied from https://github.com/hyperledger/fabric/issues/4219]
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
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
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.
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
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.
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:
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
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.
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.