Issue while using fabric client java sdk (since th

2019-02-21 00:42发布

I have done the following as per the suggestion that I have got from my previous post to communicate with locally running Hyperledger Fabric V1.0 network from java application. But I am getting the exceptions given below and unable to sort it out why it is happening.

public class Test {

    final HFClient client = HFClient.createNewInstance();
    Channel channel;
    TransactionProposalRequest proposalRequest;

    void setupCryptoMaterialsForClient() throws CryptoException, InvalidArgumentException{
        // Set default crypto suite for HF client

        client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

        client.setUserContext(new User() {

            public String getName() {
                return "PeerAdmin";
            }

            public Set<String> getRoles() {
                return null;
            }

            public String getAccount() {
                return null;
            }

            public String getAffiliation() {
                return null;
            }

            public Enrollment getEnrollment() {
                return new Enrollment() {
                    public PrivateKey getKey() {
                        PrivateKey privateKey = null;
                        try {
                            File privateKeyFile = findFileSk("C:/Users/Public/HyperledgerFabricV1/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore");
                            privateKey = getPrivateKeyFromBytes(IOUtils.toByteArray(new FileInputStream(privateKeyFile)));
                        } catch (InvalidKeySpecException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (NoSuchProviderException e) {
                            e.printStackTrace();
                        } catch (NoSuchAlgorithmException e) {
                            e.printStackTrace();
                        }
                        return privateKey;
                    }

                    public String getCert() {

                        String certificate = null;
                        try {
                            File certificateFile = new File("C:/Users/Public/HyperledgerFabricV1/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem");
                            certificate = new String(IOUtils.toByteArray(new FileInputStream(certificateFile)), "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return certificate;
                    }
                };
            }

            public String getMspId() {
                return "Org1MSP";
            }
        });
    }

    static File findFileSk(String directorys) {

        File directory = new File(directorys);

        File[] matches = directory.listFiles((dir, name) -> name.endsWith("_sk"));

        if (null == matches) {
            throw new RuntimeException(format("Matches returned null does %s directory exist?", directory.getAbsoluteFile().getName()));
        }

        if (matches.length != 1) {
            throw new RuntimeException(format("Expected in %s only 1 sk file but found %d", directory.getAbsoluteFile().getName(), matches.length));
        }

        return matches[0];
    }

    static PrivateKey getPrivateKeyFromBytes(byte[] data) throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
        final Reader pemReader = new StringReader(new String(data));

        final PrivateKeyInfo pemPair;
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            pemPair = (PrivateKeyInfo) pemParser.readObject();
        }

        PrivateKey privateKey = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);

        return privateKey;
    }


void createChannel() throws InvalidArgumentException, TransactionException{
    channel = client.newChannel("mychannel");
    Properties ordererProperties = new Properties();
    ordererProperties.setProperty("pemFile", "C:/Users/Public/HyperledgerFabricV1/fabric-samples/first-network/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt");
    ordererProperties.setProperty("trustServerCertificate", "true"); //testing environment only NOT FOR PRODUCTION!
    ordererProperties.setProperty("hostnameOverride", "orderer.example.com");
    ordererProperties.setProperty("sslProvider", "openSSL");
    ordererProperties.setProperty("negotiationType", "TLS");
    ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] {5L, TimeUnit.MINUTES});
    ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] {8L, TimeUnit.SECONDS});
    channel.addOrderer(client.newOrderer("orderer.example.com", "grpc://192.168.99.100:7050",ordererProperties));

    Properties peerProperties = new Properties();
    peerProperties.setProperty("pemFile", "C:/Users/Public/HyperledgerFabricV1/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt"); 
    peerProperties.setProperty("trustServerCertificate", "true"); //testing environment only NOT FOR PRODUCTION!    
    peerProperties.setProperty("hostnameOverride", "peer0.org1.example.com");
    peerProperties.setProperty("sslProvider", "openSSL");
    peerProperties.setProperty("negotiationType", "TLS");
    peerProperties.put("grpc.NettyChannelBuilderOption.maxInboundMessageSize", 9000000);
    channel.addPeer(client.newPeer("peer0.org1.example.com", "grpc://192.168.99.100:7051",peerProperties));
    channel.initialize();
}

    void creteTransactionalProposal(){
        proposalRequest = client.newTransactionProposalRequest();

        final ChaincodeID chaincodeID = ChaincodeID.newBuilder()
                .setName("asset")
                .setVersion("1.0")
                .setPath("github.com/mygitId/myFabricRepo/assetChainCode")
                .build();

        proposalRequest.setChaincodeID(chaincodeID);
        proposalRequest.setFcn("createAsset");
        //proposalRequest.setFcn("init");
        proposalRequest.setProposalWaitTime(TimeUnit.SECONDS.toMillis(10));
        proposalRequest.setArgs(new String[]{"ORG1", "{\"assetKey\":\"a1\",\"assetName\":\"aname1\",\"assetType\":\"atype1\",\"slNo\":\"slno1\",\"orderDate\":\"19-05-2017\"}"});
    }

    void sendProposal() throws ProposalException, InvalidArgumentException, InterruptedException, ExecutionException{
        final Collection<ProposalResponse> responses = channel.sendTransactionProposal(proposalRequest);
        CompletableFuture<BlockEvent.TransactionEvent> txFuture = channel.sendTransaction(responses, client.getUserContext());
        BlockEvent.TransactionEvent event = txFuture.get();
        System.out.println(event.toString());
    }

    public static void main(String args[]) throws Exception {
        Test t = new Test();
        t.setupCryptoMaterialsForClient();
        t.createChannel();
        t.creteTransactionalProposal();
        t.sendProposal();
    }
}

And this is my docker ps enter image description here

And by running the code in eclipse java project getting the following exception.

Exception in thread "main" org.hyperledger.fabric.sdk.exception.TransactionException: INTERNAL
    at org.hyperledger.fabric.sdk.OrdererClient.sendDeliver(OrdererClient.java:286)
    at org.hyperledger.fabric.sdk.Orderer.sendDeliver(Orderer.java:165)
    at org.hyperledger.fabric.sdk.Channel.getLatestBlock(Channel.java:1074)
    at org.hyperledger.fabric.sdk.Channel.getConfigurationBlock(Channel.java:898)
    at org.hyperledger.fabric.sdk.Channel.parseConfigBlock(Channel.java:826)
    at org.hyperledger.fabric.sdk.Channel.initialize(Channel.java:526)
    at com.ibs.blockchain.client.test.Test.createChannel(Test.java:151)
    at com.ibs.blockchain.client.test.Test.main(Test.java:179)
Caused by: io.grpc.StatusRuntimeException: INTERNAL
    at io.grpc.Status.asRuntimeException(Status.java:540)
    at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:392)
    at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:426)
    at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:76)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:512)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$700(ClientCallImpl.java:429)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:544)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:117)
    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)
Caused by: io.netty.handler.codec.http2.Http2Exception: First received frame was not SETTINGS. Hex dump for first 5 bytes: 1503010002
    at io.netty.handler.codec.http2.Http2Exception.connectionError(Http2Exception.java:85)
    at io.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.verifyFirstFrameIsSettings(Http2ConnectionHandler.java:309)
    at io.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.decode(Http2ConnectionHandler.java:217)
    at io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:401)
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:349)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:341)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:349)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:129)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:642)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:565)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:479)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:441)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
    ... 1 more

Someone please look into the code help me to find where I am doing wrong.

The ip 192.168.99.100 given is the virtual machine ip

Note: I am using Windows 7 with Docker Toolbox by following the steps Building Your First Network and running my java application through eclipse.

Update:
Updated the function createChannel by adding TLS as per @Gari Singh's answer by referring fabric-sdk-java source. But now also same error. Update:
This docker quick start terminal console after running the java client, seems no logs coming enter image description here

2条回答
Evening l夕情丶
2楼-- · 2019-02-21 01:07

If you used the first-network sample, it has TLS enabled and in your code above you are not using TLS. So my best guess is that the error is caused by not using TLS in your client.

查看更多
太酷不给撩
3楼-- · 2019-02-21 01:19

How did you created the crypto material?! I'm not asking about the tool that you used, my question is more related to the Common Name that you defined for the certificates. The CN of the certificates have to be the same to the host to which you are connecting.

If I were you, I'd create the crypto material with the cryptogen tool. Then, I'd change the URL for the call. I understand that you are in a localhost, so instead of 192.168.99.100, could you try to call orderer.example.com.

On the other hand, I think that you don't have to execute the createchannel, because you have create it before.

查看更多
登录 后发表回答