GithubHelp home page GithubHelp logo

hyperledger / fabric-sdk-java Goto Github PK

View Code? Open in Web Editor NEW
1.1K 110.0 711.0 6.06 MB

Home Page: https://wiki.hyperledger.org/display/fabric

License: Apache License 2.0

Java 97.66% Shell 0.10% Go 1.77% JavaScript 0.48%
java-sdk fabric blockchain hyperledger distributed-ledger hyperledger-fabric java

fabric-sdk-java's Introduction

Hyperledger Fabric SDK for Java Build status

Note: This API is deprecated. When developing applications for Hyperledger Fabric v2.4 and later, you should use the Fabric Gateway client API. When developing applications for earlier Fabric versions, you are strongly encouraged to use the high-level API detailed below.

This project provides a low-level API for interacting with Hyperledger Fabric blockchain networks, and is used by the high-level Hyperledger Fabric Gateway SDK for Java:

The information below is intended for contributors to this repository.


Introduction for contributors

The SDK provides a layer of abstraction on top of the wire-level protobuf based communication protocol used by client applications to interact with a Hyperledger Fabric blockchain network. It allows Java applications to manage the lifecycle of Hyperledger channels and user chaincode. The SDK also provides a means to execute user chaincode, query blocks and transactions on the channel, and monitor events on the channel.

The SDK acts on behalf of a particular User which is defined by the embedding application through the implementation of the SDK's User interface.

Note, the SDK does not provide a means of persistence for the application defined channels and user artifacts on the client. This is left for the embedding application to best manage. Channels may be serialized via Java serialization in the context of a client. Channels deserialized are not in an initialized state. Applications need to handle migration of serialized files between versions.

The SDK also provides a client for Hyperledger's certificate authority. The SDK is however not dependent on this particular implementation of a certificate authority. Other Certificate authority's maybe used by implementing the SDK's Enrollment interface.

This provides a summary of steps required to get you started with building and using the Java SDK. Please note that this is not the API documentation or a tutorial for the SDK, this will only help you familiarize to get started with the SDK if you are new in this domain.

Release notes

Release Notes Summary
2.1 v2.1 release notes Minor update
2.0 v2.0 release notes
  • New lifecycle chaincode management
  • Connection config handlers
  • Application setting executor service
  • Queued block listener
1.4 None Minor updates no Fabric changes
1.3 v1.3 release notes
  • Java chaincode support
  • Query chaincode collection configuration
  • Identity Mixer transaction unlinkabilty support
1.2 v1.2 release notes
  • Private data collection support
  • Service discovery
  • Fabric CA certificate API
1.1 v1.1 release notes
  • Channel service events
  • FilterBlocks
  • JCA/JCE compliance
  • Chaincode events
  • Node chaincode

Checkout SDK from Github

git clone https://github.com/hyperledger/fabric-sdk-java.git
cd fabric-sdk-java/

Production Java applications

For Java applications use the latest released version of the SDK v1.4.x releases:

     <!-- https://mvnrepository.com/artifact/org.hyperledger.fabric-sdk-java/fabric-sdk-java -->
     <dependency>
         <groupId>org.hyperledger.fabric-sdk-java</groupId>
         <artifactId>fabric-sdk-java</artifactId>
         <version>1.4.7</version>
     </dependency>

For v2.0 work in progress use 2.0.0-SNAPSHOT builds

Work in progress 2.0.0 SNAPSHOT builds can be used by adding the following to your application's pom.xml

    <repositories>
        <repository>
            <id>snapshots-repo</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

<dependencies>

        <!-- https://mvnrepository.com/artifact/org.hyperledger.fabric-sdk-java/fabric-sdk-java -->
        <dependency>
            <groupId>org.hyperledger.fabric-sdk-java</groupId>
            <artifactId>fabric-sdk-java</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>

</dependencies>

Java and Node Chaincode environment

You may also need to on your v2.1 Fabric network docker deployment explicitly pull the Java and Node chaincode environments for now.

docker pull hyperledger-fabric.jfrog.io/fabric-nodeenv:amd64-2.1.0-stable&&docker tag hyperledger-fabric.jfrog.io/fabric-nodeenv:amd64-2.1.0-stable hyperledger/fabric-nodeenv:amd64-latest&&docker tag hyperledger-fabric.jfrog.io/fabric-nodeenv:amd64-2.1.0-stable hyperledger/fabric-nodeenv

docker pull hyperledger-fabric.jfrog.io/fabric-javaenv:amd64-2.1.0-stable&&docker tag hyperledger-fabric.jfrog.io/fabric-javaenv:amd64-2.1.0-stable hyperledger/fabric-javaenv:amd64-latest&&docker tag hyperledger-fabric.jfrog.io/fabric-javaenv:amd64-2.1.0-stable hyperledger/fabric-javaenv

Known limitations and restrictions


SDK dependencies

SDK depends on few third party libraries that must be included in your classpath when using the JAR file. To get a list of dependencies, refer to pom.xml file or run mvn dependency:tree or mvn dependency:list. Alternatively, mvn dependency:analyze-report will produce a report in HTML format in target directory listing all the dependencies in a more readable format.

To build this project, the following dependencies must be met

  • JDK 1.8 or above
  • Apache Maven 3.5.0

To run the integration tests Fabric and Fabric CA is needed which require

  • Docker 18.03
  • Docker compose 1.21.2

Using the SDK

Setting Up Eclipse

If you want to get started using the Fabric Java SDK with Eclipse, refer to the instructions at: ./docs/EclipseSetup.md

Compiling

Once your JAVA_HOME points to your installation of JDK 1.8 (or above) and JAVA_HOME/bin and Apache maven are in your PATH, issue the following command to build the jar file: mvn install or mvn install -DskipTests if you don't want to run the unit tests

Running the unit tests

To run the unit tests, please use mvn install which will run the unit tests and build the jar file.

Many unit tests will test failure condition's resulting in exceptions and stack traces being displayed. This is not an indication of failure!

[INFO] BUILD SUCCESS At the end is usually a very reliable indication that all tests have passed successfully!

Running the integration tests

The script below both sets up the test environment and runs the tests.

./scripts/run-integration-tests.sh

End to end test scenario

Following the below integration tests/example code shows almost all that the SDK can do. To learn the SDK you must have some understanding first of Fabric Hyperledger. Then it's best to study the integrations tests and better yet work with them in a debugger to follow the code ( a live demo ). Start first with End2endIT.java and then End2endAndBackAgainIT.java samples before exploring the other samples. Then once you understand them you can cut and paste from there to your own application. ( the code is done for you! )

Note These samples are for testing, validating your environment and showing how to use the APIs. Most show a simple balance transfer. They are not meant to represent best practices in design or use of chaincode or the use of the SDK.

Integration Test Summary and notes
End2endLifecycleIT.java
End2endIT.java
  • Register and enroll users with Fabric certificate authority.
  • Constructing channel first time.
  • Installing chaincode. DEPRECATED see v2.0 release notes!
  • Instantiating chaincode. DEPRECATED see v2.0 release notes!
  • Executing chaincode.
  • Querying channel for block information.
  • Chaincode event listener
  • Traversing block for information.
  • Prerequisite for all other testcases.
End2endAndBackAgainIT.java
  • Recreate channel.
  • Update chaincode.
  • Checking installed and instantiated chaincode. DEPRECATED see v2.0 release notes!
End2endNodeIT.java
  • Shows running End2endIT.java but with Node chaincode.
  • Note subclasses En2endIT class.
End2endJavaIT.java
  • Shows running End2endIT.java but with Java chaincode.
  • Note subclasses En2endIT class.
End2endIdemixIT.java
  • Shows running End2endIT.java but with Idemix credentials.
  • Note subclasses En2endIT class.
NetworkConfigIT.java
  • Shows recreating channel with common connection profile.
  • User defined handlers for creating Peers and Orderers (v2.0) πŸ”₯ .
PrivateDataIT.java
  • Shows instantiating and installing chaincode that defines private data.
  • Information on Fabric private data can be found read the docs.
UpdateChannelIT.java
  • Shows updating channel configuration.
  • Details on channel configurations can be found on read the docs Channel Configuration
  • Queued block listener (v2.0) πŸ”₯
ServiceDiscoveryIT.java
  • Shows service discovery.
  • Details on service discovery can be found on read the docs Service Discovery
  • Note: requires adding entries in host file to remap docker fabric Peer and Orderers address to localhost

End to end test environment

The test defines one Fabric orderer and two organizations (peerOrg1, peerOrg2), each of which has 2 peers, one fabric-ca service.

Certificates and other cryptography artifacts

Fabric requires that each organization has private keys and certificates for use in signing and verifying messages going to and from clients, peers and orderers. Each organization groups these artifacts in an MSP (Membership Service Provider) with a corresponding unique MSPID .

Furthermore, each organization is assumed to generate these artifacts independently. The fabric-ca project is an example of such a certificate generation service. Fabric also provides the cryptogen tool to automatically generate all cryptographic artifacts needed for the end to end test. In the directory src/test/fixture/sdkintegration/e2e-2Orgs/channel

The command used to generate end2end crypto-config artifacts:

v1.0 build/bin/cryptogen generate --config crypto-config.yaml --output=crypto-config

v1.1 cryptogen generate --config crypto-config.yaml --output=v1.1/crypto-config

For ease of assigning ports and mapping of artifacts to physical files, all peers, orderers, and fabric-ca are run as Docker containers controlled via a docker-compose configuration file.

The files used by the end to end are:

  • src/test/fixture/sdkintegration/e2e-2Orgs/vX.0 (everything needed to bootstrap the orderer and create the channels)
  • src/test/fixture/sdkintegration/e2e-2Orgs/vX.0crypto-config (as-is. Used by configtxgen and docker-compose to map the MSP directories)
  • src/test/fixture/sdkintegration/docker-compose.yaml

The end to end test case artifacts are stored under the directory src/test/fixture/sdkintegration/e2e-2Org/channel .

TLS connection to Orderer and Peers

IBM Java needs the following properties defined to use TLS 1.2 to get an HTTPS connections to Fabric CA.

-Dcom.ibm.jsse2.overrideDefaultTLS=true   -Dhttps.protocols=TLSv1.2

Currently, the pom.xml is set to use netty-tcnative-boringssl for TLS connection to Orderer and Peers, however, you can change the pom.xml (uncomment a few lines) to use an alternative TLS connection via ALPN.

TLS Environment for SDK Integration Tests

The SDK Integration tests can be enabled by adding before the ./fabric restart the follow as:

ORG_HYPERLEDGER_FABRIC_SDKTEST_INTEGRATIONTESTS_TLS=true ORG_HYPERLEDGER_FABRIC_SDKTEST_INTEGRATIONTESTS_CA_TLS=--tls.enabled ./fabric.sh restart

Then run the Integration tests with:

ORG_HYPERLEDGER_FABRIC_SDKTEST_INTEGRATIONTESTS_TLS=true mvn clean install -DskipITs=false -Dmaven.test.failure.ignore=false javadoc:javadoc

Chaincode endorsement policies

You create a policy using a Fabric tool ( an example is shown in JIRA issue FAB-2376) and give it to the SDK either as a file or a byte array. The SDK, in turn, will use the policy when it creates chaincode instantiation requests.

To input a policy to the SDK, use the ChaincodeEndorsementPolicy class.

For testing purposes, there are 2 policy files in the src/test/resources directory

  • policyBitsAdmin ( which has policy AND(DEFAULT.admin) meaning 1 signature from the DEFAULT MSP admin' is required )
  • policyBitsMember ( which has policy AND(DEFAULT.member) meaning 1 signature from a member of the DEFAULT MSP is required )

and one file in the src/test/fixture/sdkintegration/e2e-2Orgs/channel directory specifically for use in the end to end test scenario

  • members_from_org1_or_2.policy ( which has policy OR(peerOrg1.member, peerOrg2.member) meaning 1 signature from a member of either organizations peerOrg1, PeerOrg2 is required)

Alternatively, you can also use ChaincodeEndorsementPolicy class by giving it a YAML file that has the policy defined in it. See examples of this in the End2endIT testcases that use src/test/fixture/sdkintegration/chaincodeendorsementpolicy.yaml The file chaincodeendorsementpolicy.yaml has comments that help understand how to create these policies. The first section lists all the signature identities you can use in the policy. Currently, only ROLE types are supported. The policy section is comprised of n-of and signed-by elements. Then n-of (1-of 2-of) require that many (n) in that section to be true. The signed-by references an identity in the identities section.

Channel creation artifacts

Channel configuration files and orderer bootstrap files ( see directory src/test/fixture/sdkintegration/e2e-2Orgs ) are needed when creating a new channel. This is created with the Hyperledger Fabric configtxgen tool. This must be run after cryptogen and the directory you're running in must have a generated crypto-config directory.

If build/bin/configtxgen tool is not present run make configtxgen

For v1.0 integration test the commands are:

  • build/bin/configtxgen -outputCreateChannelTx foo.tx -profile TwoOrgsChannel -channelID foo
  • build/bin/configtxgen -outputCreateChannelTx bar.tx -profile TwoOrgsChannel -channelID bar

For v1.1 integration the commands use the v11 profiles in configtx.yaml. You need to for now copy the configtx.yaml in e2e-20orgs to the v1.1 directory and run from there:

  • configtxgen -outputBlock orderer.block -profile TwoOrgsOrdererGenesis_v11
  • configtxgen -outputCreateChannelTx bar.tx -profile TwoOrgsChannel_v11 -channelID bar
  • configtxgen -outputCreateChannelTx foo.tx -profile TwoOrgsChannel_v11 -channelID foo

For v1.2 integration the commands use the v12 profiles in configtx.yaml.

  • configtxgen --configPath . -outputBlock orderer.block -profile TwoOrgsOrdererGenesis_v12
  • configtxgen --configPath . -outputCreateChannelTx bar.tx -profile TwoOrgsChannel_v12 -channelID bar
  • configtxgen --configPath . -outputCreateChannelTx foo.tx -profile TwoOrgsChannel_v12 -channelID foo This should produce in the v1.2 directory: bar.tx,foo.tx, orderer.block

For v1.3 and 1.4 integration, cd to the src/test/fixture/sdkintegration/e2e-2Orgs/v1.3 directory and execute the following commands:

  • configtxgen --configPath . -outputBlock orderer.block -profile TwoOrgsOrdererGenesis_v13
  • configtxgen --configPath . -outputCreateChannelTx foo.tx -profile TwoOrgsChannel_v13 -channelID foo
  • configtxgen --configPath . -outputCreateChannelTx bar.tx -profile TwoOrgsChannel_v13 -channelID bar

For v2.1 integration, cd to the src/test/fixture/sdkintegration/e2e-2Orgs/v2.1 directory

  • configtxgen --configPath . -outputCreateChannelTx v2channel.tx -profile TwoOrgsChannel_v20 -channelID v2channel
  • configtxgen --configPath . -outputBlock orderer.block -profile TwoOrgsOrdererGenesis_v20 -channelID systemordererchannel

This should produce the following files in the same directory: orderer.block, foo.tx, and bar.tx

Note: The above describes how this was done. If you redo this there are private key files which are produced with unique names which won't match what's expected in the integration tests. One example of this is the docker-compose.yaml (search for _sk)

GO Lang chaincode

Go lang chaincode dependencies must be contained in vendor folder. For an explanation of this see Vendor folder explanation

Basic Troubleshooting and frequently asked questions:

Where can I find the Javadoc?

Look in the Maven repository for the release in question there should be a file fabric-sdk-java-<release>-javadoc.jar

For SNAPSHOT builds look in Sonatype repository Find the release <release>-SNAPSHOT directory then search for the latest fabric-sdk-java-<release>-<latest timestamp>-javadoc.jar

Is Android supported?

No.

Is there an API to query for all channels that exist?

No.

Should an application create more than one HFClient?

There should be no need to do that in a single application. All the SDK requests are threadsafe. The user context set on the client can be on all requests overridden by setting the user context on that specific request.

Idemix users or Idemix test cases (IdemixIdentitiesTest) just seems to hang or take forever.

Most likely this is running on a virtual machine that does not have sufficient entropy. Google for adding entropy on virtual machines or look at virtual machines entropy If linux try installing rng-tools package as this suggests.

Firewalls, load balancers, network proxies

These can sometimes silently kill a network connections and prevent them from auto reconnecting. To fix this look at adding to Peers and Orderer's connection properties: grpc.NettyChannelBuilderOption.keepAliveTime, grpc.NettyChannelBuilderOption.keepAliveTimeout, grpc.NettyChannelBuilderOption.keepAliveWithoutCalls. Examples of this are in End2endIT.java

Missing protobuf classes.

Please re-read this file doing exactly the steps to run all the tests. They can't be missing if the tests pass. πŸ˜ƒ

grpc message frame size exceeds maximum

The message being returned from the fabric server is too large for the default grpc frame size. On the Peer or Orderer add the property grpc.NettyChannelBuilderOption.maxInboundMessageSize See End2endIT's constructChannel

Configuration and setting default values - timeouts etc

The SDK's defaults are all in the file Config.java The config.properties also has some descriptions on what they do. Most server timeout request can be overridden with the specific request too.

What's difference between joining and adding a peer to a channel?

You only ever join a peer belonging to your own organization to a channel once at the beginning. You would only add peers from other organizations or peers of your own organization you've already joined like when recreating the channel SDK object.

Transaction sent to orderer results in future with exception validation code: xxx Where can I find what that means?

See Fabric protobuf protos/peer/transaction.proto's TxValidationCode

java.security.InvalidKeyException: Illegal key size

If you get this error, this means your JDK does not capable of handling unlimited strength crypto algorithms. To fix this issue, You will need to download the JCE libraries for your version of JDK. Please follow the instructions here to download and install the JCE for your version of the JDK.

Communicating with developers and fellow users.

Sign into Hyperledger project's Rocket chat For this you will also need a Linux Foundation ID

Join the fabric-sdk-java channel.

Reporting Issues

If your issue is with building Fabric development environment please discuss this on rocket.chat's #fabric-dev-env channel.

To report an issue please use: Hyperledger's JIRA. To login you will need a Linux Foundation ID (LFID) which you get at The Linux Foundation if you don't already have one.

JIRA Fields should be:

Type
Bug or New Feature
Component
fabric-sdk-java
Fix Versions
v1.4

Pleases provide as much information that you can with the issue you're experiencing: stack traces logs.

Please provide the output of java -XshowSettings:properties -version

Logging for the SDK can be enabled with setting environment variables:

ORG_HYPERLEDGER_FABRIC_SDK_LOGLEVEL=TRACE

ORG_HYPERLEDGER_FABRIC_CA_SDK_LOGLEVEL=TRACE

ORG_HYPERLEDGER_FABRIC_SDK_DIAGNOSTICFILEDIR=<full path to directory> # dumps protobuf and diagnostic data. Can be produce large amounts of data!

Fabric debug

Fabric debug is by default enabled in the SDK docker-compose.yaml file with

On Orderer:

ORDERER_GENERAL_LOGLEVEL=debug

On peers: CORE_LOGGING_LEVEL=DEBUG

Fabric CA by starting command have the -d parameter.

Upload full logs to JIRA, not just where the issue occurred if possible

Tracing

The SDK is set up to trace all gRPC communications:

  • All outgoing messages bear trace metadata, allowing correlation with peers.
  • Each request/response is computed as a span.
  • If you use OpenTelemetry in your program, the gRPC span will correlate using the thread local context to the parent context.

The SDK accepts all environment variables as described in the OpenTelemetry specification.

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.

fabric-sdk-java's People

Contributors

adecaro avatar andrew-coleman avatar ashku avatar bestbeforetoday avatar breina avatar choojoyq avatar chrism28282828 avatar christo4ferris avatar cr22rc avatar denyeart avatar dependabot[bot] avatar heatherlp avatar jimthematrix avatar lesleyannjordan avatar lindluni avatar literocks avatar liuwenliang0632 avatar malik-altaf avatar mastersingh24 avatar mergify[bot] avatar mohitkumarsethi avatar optimizing-ci-builds avatar paranjan avatar psaradhi avatar rameshthoomu avatar ryjones avatar tuand27613 avatar xspeedcruiser avatar yacovm avatar zhanghongquan-dianrong 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  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

fabric-sdk-java's Issues

Getting block time exceeded 5 seconds for channel mychannel when peer join channel

newChannel.joinPeer(peer, createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.CHAINCODE_QUERY, Peer.PeerRole.EVENT_SOURCE)));
17:02:00.735 [main] ERROR o.h.f.sdk.Channel - [joinPeer,896] - Channel{id: 2, name: mychannel} removing peer Peer{ id: 3, name: peer0.org1.example.com, channelName: null, url: grpcs://172.22.110.75:7051} due to exception Getting block time exceeded 5 seconds for channel mychannel
17:02:00.735 [main] ERROR o.h.f.sdk.Channel - [joinPeer,899] - org.hyperledger.fabric.sdk.exception.TransactionException: Getting block time exceeded 5 seconds for channel mychannel
Exception in thread "main" org.hyperledger.fabric.sdk.exception.ProposalException: Getting block time exceeded 5 seconds for channel mychannel
at org.hyperledger.fabric.sdk.Channel.joinPeer(Channel.java:900)
at org.hyperledger.fabric.sdk.Channel.joinPeer(Channel.java:817)
at com.ruoyi.fabric.FrabricSdk.constructChannel(FrabricSdk.java:137)
at com.ruoyi.fabric.FrabricSdk.main(FrabricSdk.java:190)
Caused by: org.hyperledger.fabric.sdk.exception.TransactionException: Getting block time exceeded 5 seconds for channel mychannel
at org.hyperledger.fabric.sdk.Channel.seekBlock(Channel.java:2691)
at org.hyperledger.fabric.sdk.Channel.getGenesisBlock(Channel.java:1855)
at org.hyperledger.fabric.sdk.Channel.joinPeer(Channel.java:859)
... 3 more

Unable to communicate from remote java client to Fabric network, ended with grpc://localhost:port#

How to reproduce :
1, Clone the fabrice samples,
2, goto fabricsamples\fabcar and start the network.
3, Copy the relevant files and the connection files, fabcar\java- src, pom.xml
4, Run the java client for fabcar from a different machine. ( in may case windows )

Response :
Able to add the Wallets, but getting below grpc comm error.

Steps tried :
Added the org2 peer in connection.yaml file still not resolving..
Added DNS entries, no improvement
Changed to org.hyperledger.fabric.sdk.service_discovery.as_localhost", "false", or true, no improvement.

expecting: Grpcs should take the hostname/fqdn peer name from the configured variable from the docker-compose file.
Any alternate options to override the setting ? How can i override the hostname setting from the grpcs://localhost:9051 ?

An identity for the admin user "admin" already exists in the wallet
An identity for the user "appUser" already exists in the wallet
Oct 28, 2021 10:18:17 AM io.grpc.internal.SerializingExecutor run
SEVERE: Exception while executing runnable io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed@59950e4a    
java.lang.NullPointerException
        at org.hyperledger.fabric.sdk.Channel.getExecutorService(Channel.java:1981)
        at org.hyperledger.fabric.sdk.Peer.getExecutorService(Peer.java:134)
        at org.hyperledger.fabric.sdk.Peer.reconnectPeerEventServiceClient(Peer.java:379)
        at org.hyperledger.fabric.sdk.PeerEventServiceClient$1.onError(PeerEventServiceClient.java:288)
        at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:442)
        at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
        at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
        at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
        at io.grpc.internal.CensusStatsModule$StatsClientInterceptor$1$1.onClose(CensusStatsModule.java:700)
        at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
        at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
        at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
        at io.grpc.internal.CensusTracingModule$TracingClientInterceptor$1$1.onClose(CensusTracingModule.java:399)
        at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:510)
        at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:66)
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:630)
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$700(ClientCallImpl.java:518)
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:692)        
        at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:681)       
        at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
        at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 34.931 sec <<< FAILURE!
testFabCar(org.example.ClientTest)  Time elapsed: 34.873 sec  <<< ERROR!
org.hyperledger.fabric.gateway.ContractException: No valid proposal responses received. 2 peer error responses: Channel Channel{id: 1, name: mychannel} Sending proposal with transaction: 2821bb263c90c67c0c4bb8ad94e93a6a34d0f72e8014bd19e8e69686781384d7 
to Peer{ id: 5, name: peer0.org2.example.com:9051, channelName: mychannel, url: grpcs://localhost:9051, mspid: Org2MSP} failed because of: gRPC failure=Status{code=UNAVAILABLE, description=io exception, cause=io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/0:0:0:0:0:0:0:1:9051
Caused by: java.net.ConnectException: Connection refused: no further information
        at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
        at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
        at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:327)
        at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:336)
        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:685)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:632)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:549)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:511)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Thread.java:745)
}; Channel Channel{id: 1, name: mychannel} Sending proposal with transaction: 2821bb263c90c67c0c4bb8ad94e93a6a34d0f72e8014bd19e8e69686781384d7 to Peer{ id: 7, name: peer0.org1.example.com:7051, channelName: mychannel, url: grpcs://localhost:7051, mspid: Org1MSP} failed because of: gRPC failure=Status{code=UNAVAILABLE, description=io exception, cause=io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/0:0:0:0:0:0:0:1:7051
Caused by: java.net.ConnectException: Connection refused: no further information
        at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
        at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
        at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:327)
        at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:336)
        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:685)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:632)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:549)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:511)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Thread.java:745)
}
        at org.hyperledger.fabric.gateway.impl.TransactionImpl.validatePeerResponses(TransactionImpl.java:196)
        at org.hyperledger.fabric.gateway.impl.TransactionImpl.submit(TransactionImpl.java:93)
        at org.hyperledger.fabric.gateway.impl.ContractImpl.submitTransaction(ContractImpl.java:50)
        at org.example.ClientApp.main(ClientApp.java:53)
        at org.example.ClientTest.testFabCar(ClientTest.java:15)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)


Results :

Tests in error:
  testFabCar(org.example.ClientTest): No valid proposal responses received. 2 peer error responses: Channel Channel{id: 1, name: mychannel} Sending proposal with transaction: 2821bb263c90c67c0c4bb8ad94e93a6a34d0f72e8014bd19e8e69686781384d7 to Peer{ id: 5, name: peer0.org2.example.com:9051, channelName: mychannel, url: grpcs://localhost:9051, mspid: Org2MSP} failed because of: gRPC failure=Status{code=UNAVAILABLE, description=io exception, cause=io.netty.channel.AbstractChannel$AnnotatedConnectExcept(..) Connection refused: no further information: localhost/0:0:0:0:0:0:0:1:9051

Maven repository link is wrong

Visit the link https://github.com/hyperledger/fabric-sdk-java
Now click on "Fabric read the docs: Chaincode for Operators" and "Maven repository " and "virtual machines entropy" links as mentioned below

http://central.maven.org/maven2/org/hyperledger/fabric-sdk-java/fabric-sdk-java/
we will be redirected to below error page
This site can’t be reached
Check if there is a typo in central.maven.org.
If spelling is correct, try running Windows Network Diagnostics.
DNS_PROBE_FINISHED_NXDOMAIN

Intermittent test failure: chaincode event ordering

Error: Failures:
Error: End2endJavaIT.setup:60->End2endIT.runFabricTest:209->End2endIT.runChannel:791 expected:<[e8e7f5534d3b63dca0a652d16a7d29e4e61d5d4ab579bb0d9e9f23f501b7ac5f]> but was:<[88ed5616e9505389892d2e760d21a3cd61ad233eb1ca54df96a93d9b033c486a]>

The test code needs to be updated to either accurately capture the ordering (possibly a concurrency issue) or, if the implementation does not reliably maintain ordering, not to be sensitive to the ordering.

Service Discovery bug on insufficient endorsements

I think there's a couple of bugs in the fabric java sdk service discovery code during the sendTransactionProposalToEndorsers loop if it collects insufficient endorsements and has to retry. Specifically, it can rule out layouts and group where there have been valid endorsements as well as those groups that are actually no longer satisfiable.

For example if there were a group with 3 endorsers, of which 2 are required, we received 1 "good" endorsement and 1 "bad" endorsement:

  • what we'd expect to happen:
    • the SDLayout.SDGroup.endorsed counter increases by 1.
    • both endorsers are removed from the group (so as to not be re-selected).
    • the group is still flagged as able to be satisfied.
  • what actually happens:
    • the endorsed counter stays at 0
      • bug: endorsed = Math.min(required, endorsed++) (the value changed at endorsed++ is never used, i.e. endorsed will always stay at 0 irrespective of required or how many times this line is run)
    • both endorsers are removed as expected.
    • the group is still flagged as not able to be satisfied
      • bug: endorsers.size() >= required; should be endorsers.size() + endorsed >= required; (as we've removed the endorsers already).
      • this also needs the earlier bug to be fixed as well in order to return the correct result.

Obviously, I might be wrong in this, especially as this is code which hasn't changed in a long time yet nobody else has reported this problem that I'm aware of, but I think this is legitimate! Let me know if you want me to attempt a pull request.

You can reproduce by stopping a peer after it has been discovered. If it happens to be selected in the sendTransactionProposalToEndorsers then you should end up in the //still don't have the needed endorsements. section where the bugs are in:

  • sdChaindcodeEndorsementCopy.endorsedList(loopGood) for the endorsed counter bug.
  • sdChaindcodeEndorsementCopy.ignoreListSDEndorser(loopBad) for the comparator bug.

Obviously it depends on your network topology as to whether this will affect normal usage. I noticed it when running 3 orgs, each with 1 peer, each org's policy requires their peer to endorse, we require a strict majority of org policies, and then simulating a peer failure. I expected txs to still go through as sendTransactionProposalToEndorsers should end up selecting the layout not containing the bad peer eventually, but in reality only 1/3 of the txs work i.e. when it happens to pick the only remaining valid layout first time.

GeneratedMessageV3.isStringEmpty NoSuchMethodError issue

Hi,

I am using the fabric-gateway-java sdk for my api server connected to hyperledger. When it tries to call below function, seems like some error appear from fabric-sdk-java-2.2.11. Not sure if having compatibility issue with protobuf GeneratedMessageV3. Could you please help me on this ? Should I reduce the version to 2.2.10 ?

#############################################

Network network = gateway.getNetwork("main-channel");

############################################

ERROR LOG

java.lang.NoSuchMethodError: 'boolean com.google.protobuf.GeneratedMessageV3.isStringEmpty(java.lang.Object)'
at org.hyperledger.fabric.protos.msp.Identities$SerializedIdentity.getSerializedSize(Identities.java:237) ~[fabric-sdk-java-2.2.11.jar!/:na]
at com.google.protobuf.AbstractMessageLite.toByteString(AbstractMessageLite.java:58) ~[protobuf-java-3.13.0.jar!/:na]
at org.hyperledger.fabric.sdk.transaction.TransactionContext.(TransactionContext.java:70) ~[fabric-sdk-java-2.2.11.jar!/:na]
at org.hyperledger.fabric.sdk.Channel.newTransactionContext(Channel.java:2823) ~[fabric-sdk-java-2.2.11.jar!/:na]
at org.hyperledger.fabric.sdk.Channel.newTransactionContext(Channel.java:2819) ~[fabric-sdk-java-2.2.11.jar!/:na]
at org.hyperledger.fabric.sdk.Channel.getConfigBlock(Channel.java:907) ~[fabric-sdk-java-2.2.11.jar!/:na]
at org.hyperledger.fabric.sdk.Channel.parseConfigBlock(Channel.java:1964) ~[fabric-sdk-java-2.2.11.jar!/:na]
at org.hyperledger.fabric.sdk.Channel.loadCACertificates(Channel.java:1801) ~[fabric-sdk-java-2.2.11.jar!/:na]
at org.hyperledger.fabric.sdk.Channel.initialize(Channel.java:1222) ~[fabric-sdk-java-2.2.11.jar!/:na]
at org.hyperledger.fabric.gateway.impl.NetworkImpl.initializeChannel(NetworkImpl.java:59) ~[fabric-gateway-java-2.2.3.jar!/:na]
at org.hyperledger.fabric.gateway.impl.NetworkImpl.(NetworkImpl.java:50) ~[fabric-gateway-java-2.2.3.jar!/:na]
at org.hyperledger.fabric.gateway.impl.GatewayImpl.getNetwork(GatewayImpl.java:252) ~[fabric-gateway-java-2.2.3.jar!/:na]
at com.intelliwaremy.hyperledger.services.CoreServiceImpl.evaluateTransaction(CoreServiceImpl.java:255) ~[classes!/:0.0.16]
at com.intelliwaremy.hyperledger.controllers.CoreController.evaluateTransaction(CoreController.java:79) ~[classes!/:0.0.16]
.......

NetworkConfig.getPrivateKeyFromString read private key exception

Hello

When the private key is in a non-standard (in my case ECDSA), org.bouncycastle.openssl.PEMParser.readObject() returns an instance of the PEMKeyPair class (it's written in the documentation) and then the org.hyperledger.fabric.sdk.NetworkConfig.getPrivateKeyFromString crashes with an exception:

Caused by: java.lang.ClassCastException: class org.bouncycastle.openssl.PEMKeyPair cannot be cast to class org.bouncycastle.asn1.pkcs.PrivateKeyInfo (org.bouncycastle.openssl.PEMKeyPair and org.bouncycastle.asn1.pkcs.PrivateKeyInfo are in unnamed module of loader 'app')

Screenshot:
image_2021-12-18_23-47-25

Private key like this (values replace to '***'):
image

I`m use fabric-sdk-java:1.4.x, but this problem not fixed in last sources:
https://github.com/hyperledger/fabric-sdk-java/blob/v2.2.10/src/main/java/org/hyperledger/fabric/sdk/NetworkConfig.java#L945

Comment about `SERVICE_DISCOVERY` is incorrect and same with `EVENT_SOURCE`.

Comment about SERVICE_DISCOVERY is incorrect and same with EVENT_SOURCE.

        /**
         * Peer will monitor block events for the channel it belongs to.
         */
        EVENT_SOURCE("eventSource"),

        /**
         * Peer will monitor block events for the channel it belongs to.
         */
        SERVICE_DISCOVERY("serviceDiscovery");

Good habit that check after CtrlC & CtrlV πŸ”πŸ˜

Cannot commit chaincode approve

I'm trying to use the fabric sdk to install a chaincode on my network.
The chaincode gets correctly packaged. I then approve it. which returns some weird thing:

System.out.printf("[approve] chaincodeId: %s, message: %s\n",
                                                lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse
                                                                .getChaincodeID(),
                                                lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse
                                                                .getMessage());

prints:

[approve] chaincodeId: ChaincodeID(_lifecycle::), message: 

with status 200.

Then when I try to commit I get:

[commit] chaincodeId: ChaincodeID(_lifecycle::), message: failed to invoke backing implementation of 'CommitChaincodeDefinition': chaincode definition not agreed to by this org (Org1MSP)

I think there's some kind of issue with the install operation. I'm using version 2.2.2

log4j2 issue

Currently, security issues have occurred in the version below log4j22.15.0.
In version 2.2 of hyperledger-fabric-sdk java, log4j2 was updated to version 2.15.0. It would be nice to update all versions of hyperledger-fabric-sdk java 1.4.x to log4j2 2.15.0.

Vulnerable dependencies

NB: Please note that this issue is in progress and will be updated.

I have decided to amalgamate these all into one list to make things easier for the Hyperledger Fabric team. @denyeart explained that JARs/dependencies with known vulnerabilities are OK to report via GitHub issue. So here we go.

Name Found in Code CVEs Due Date Status
guava-31.1-android.jar Transitive dependency on grpc.io.grpc-netty-shaded found in https://github.com/hyperledger/fabric-sdk-java/blob/main/pom.xml#L112, and then if you look at the pom for netty shaded here https://mvnrepository.com/artifact/io.grpc/grpc-netty-shaded/1.56.0, you can see it depends on guava-31.1-android https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-2976 Oct 20, 2023 Confirmed Fixed by https://github.com/hyperledger/fabric-sdk-java/pull/286/files.
okio-jvm-3.2.0.jar Transitive dependency. fabric-sdk-java imports opentelemetry-exporter-otlp here https://github.com/hyperledger/fabric-sdk-java/blob/main/pom.xml#L252-L255. Version 1.27.0. opentelemetry-exporter-otlp includes opentelemetry-exporter-otlp-common at v1.27.0 as shown in https://mvnrepository.com/artifact/io.opentelemetry/opentelemetry-exporter-otlp/1.27.0. opentelemetry-exporter-otlp-common includes okhttp, which includes okio, which includes okio-jvm at v1.27.0, as shown in https://mvnrepository.com/artifact/com.squareup.okio/okio/3.2.0. https://nvd.nist.gov/vuln/detail/CVE-2023-3635 Aug 26, 2023 Needs Update

Separate logging of warnings and errors in channel.sendTransaction() method in low level java SDK

We have observed that below ERROR level log is getting printed for every invalid transaction sdk receives and we think that this log should be at INFO level.
Receiving invalid transaction should not be considered as failure case, it is a BAU case.

2021-11-22 12:00:02.254 [pool-6-thread-173] ERROR Channel - Future completed exceptionally: sendTransaction
org.hyperledger.fabric.sdk.exception.TransactionEventException: Received invalid transaction event. Transaction ID b9c18e9a84ef12a4e3b553816c5bf008c4c9469a675631f0f508539d55b851ff status 11
at org.hyperledger.fabric.sdk.Channel$TL.lambda$fire$2(Channel.java:6866) ~[fabric-sdk-java-2.2.3.jar!/:?]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_271]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_271]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_271]

Using low level java sdk 2.2.3.

After some discussion, the issue is that if the low-level fabric-sdk-java Channel.sendTransaction() method is used directly and configured (or defaults) to waiting for transaction commit events, an MVCC_READ_CONFLICT can occur and will be logged as an error in the SDK log. However this is not technically an error as an MVCC_READ_CONFLICT means the transaction is properly invalidated until the world state is read again.

Unfortunately, the logging for the Channel.sendTransaction() method uses the same code path for logging real transaction failures as well as non failures such as MVCC_READ_CONFLICTS.

The request is that a change be made such that actual errors are logged as errors and non errors are logged as info or warning. I believe this would require the code to try and guess the severity from a transaction validation code if one is associated with the error.

We also discussed changing the log level for any errors from Channel.sendTransaction() to warning. However, this would mask real errors in the logs and may affect other users who are scraping the logs for error messages.

The high level SDK uses a different flow so does not have this issue. Obviously though it's work for users to move to that SDK who are already using the low level SDK.

release-2.2 mutual tls config key and peer property key not matching

Here is the extraction from my connection profile:

 "peers":{
    "peer0": {
      "tlsCACerts": {
        "path": "./tls/tlscacerts/tlsca.pem",
        "client": {
          "certfile": "./tls/signcerts/sign.pem",
          "keyfile": "./tls/keystore/key.pem"
        }
      }, 
      "url": "grpcs://xx.xx.xx.xx:7051"
    }
  },

and here is the code:

Path walletDirectory = Paths.get("wallet");
Wallet wallet = Wallets.newFileSystemWallet(walletDirectory);

// Path to a common connection profile describing the network.
Path networkConfigFile = Paths.get("connection_profile.json");

// Configure the gateway connection used to access the network.
Gateway.Builder builder = Gateway.createBuilder()
        .identity(wallet, "admin")
        .networkConfig(networkConfigFile);

// Create a gateway connection
try (Gateway gateway = builder.connect()) {
 

    // Obtain a smart contract deployed on the network.
    Network network = gateway.getNetwork("dev");
    
    Contract contract = network.getContract("fabcar");

} catch (ContractException e) {
    e.printStackTrace();
}

The problem happens at 2 places. The first one is:

 .networkConfig(networkConfigFile);

where in NetworkConfig.java, it will put in props the key 'tlsClientKeyFile'.

if (keyfile != null) {
    props.put("tlsClientKeyFile", keyfile);
}

if (certfile != null) {
    props.put("tlsClientCertFile", certfile);
}

See

if (keyfile != null) {
props.put("tlsClientKeyFile", keyfile);
}
if (certfile != null) {
props.put("tlsClientCertFile", certfile);
}
String keyBytes = getJsonValueAsString(jsonTlsClientCerts.get("keyPem"));
String certBytes = getJsonValueAsString(jsonTlsClientCerts.get("certPem"));
if (keyBytes != null) {
props.put("tlsClientKeyBytes", keyBytes.getBytes());
}
if (certBytes != null) {
props.put("tlsClientCertBytes", certBytes.getBytes());
}

This change was introduced since v2.2.4.

Then it goes on to the line:

Network network = gateway.getNetwork("dev");

where, in Endpoint.java, it tries to find 'clientKeyFile' in the properties

if (properties.containsKey("clientKeyFile") || properties.containsKey("clientCertFile")) {

See

if (properties.containsKey("clientKeyFile") && properties.containsKey("clientKeyBytes")) {
throw new RuntimeException("Properties \"clientKeyFile\" and \"clientKeyBytes\" must cannot both be set");
} else if (properties.containsKey("clientCertFile") && properties.containsKey("clientCertBytes")) {
throw new RuntimeException("Properties \"clientCertFile\" and \"clientCertBytes\" must cannot both be set");
} else if (properties.containsKey("clientKeyFile") || properties.containsKey("clientCertFile")) {
if ((properties.getProperty("clientKeyFile") != null) && (properties.getProperty("clientCertFile") != null)) {
try {
logger.trace(format("Endpoint %s reading clientKeyFile: %s", url, properties.getProperty("clientKeyFile")));
ckb = Files.readAllBytes(Paths.get(properties.getProperty("clientKeyFile")));
logger.trace(format("Endpoint %s reading clientCertFile: %s", url, properties.getProperty("clientCertFile")));
ccb = Files.readAllBytes(Paths.get(properties.getProperty("clientCertFile")));
} catch (IOException e) {
throw new RuntimeException("Failed to parse TLS client key and/or cert", e);
}
} else {
throw new RuntimeException("Properties \"clientKeyFile\" and \"clientCertFile\" must both be set or both be null");
}
} else if (properties.containsKey("clientKeyBytes") || properties.containsKey("clientCertBytes")) {
ckb = (byte[]) properties.get("clientKeyBytes");
ccb = (byte[]) properties.get("clientCertBytes");
if ((ckb == null) || (ccb == null)) {
throw new RuntimeException("Properties \"clientKeyBytes\" and \"clientCertBytes\" must both be set or both be null");
}
}

Since the property has a different name, the method return null, which results on the peer side returning an error saying the client didn't send the certificate.

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.