0
votes

I have started the Docker containers and channels as per the "Build your First network" example from the Hyperledger fabric docs . I am trying to query a value from the ledger using Fabric Java SDK . The Fabric samples release version I am using is fabric-samples-release-1.0.

I get a certificate verification failed exception during channel initialize Here is my Java code

public class javaSDKSample {

private static final Logger log = Logger.getLogger(HFJavaSDKBasicExample.class);


public static void main(String[] args) throws Exception {
    // create fabric-ca client
    HFCAClient caClient = getHfCaClient("http://{remotemachineURL}:7054", null);

    // enroll or load admin
    AppUser admin = getAdmin(caClient);
    log.info(admin);

    // register and enroll new user
   // AppUser appUser = getUser(caClient, admin, "hfuser7");
   // log.info(appUser);

    // get HFC client instance
    HFClient client = getHfClient();
    // set user context
    client.setUserContext(admin);

    // get HFC channel using the client
     Channel channel = getChannel(client);
    log.info("Channel: " + channel.getName());

   //createCar(client, channel, "CAR18", "MAKE7", "MODEL7", "BLACK", "JOHN", true); 


  // queryBlockChain(client);
}


/**
 * Invoke blockchain query
 *
 * @param client The HF Client
 * @throws ProposalException
 * @throws InvalidArgumentException
 */
static void queryBlockChain(HFClient client) throws ProposalException, InvalidArgumentException {
    // get channel instance from client
    Channel channel = client.getChannel("mychannel");
    // create chaincode request
    QueryByChaincodeRequest qpr = client.newQueryProposalRequest();
    // build cc id providing the chaincode name. Version is omitted here.
    ChaincodeID fabcarCCId = ChaincodeID.newBuilder().setName("mycc").build();
    qpr.setChaincodeID(fabcarCCId);
    // CC function to be called
    qpr.setFcn("query");
    qpr.setArgs(new String[]{"a"});
    Collection<ProposalResponse> res = channel.queryByChaincode(qpr);
    // display response
    for (ProposalResponse pres : res) {
        String stringResponse = new String(pres.getChaincodeActionResponsePayload());
        log.info(stringResponse);
    }
}


static void createCar(HFClient client,Channel channel, String key, String make,String model,String color,String owner, Boolean doCommit)
        throws Exception {
    TransactionProposalRequest req = client.newTransactionProposalRequest();
    ChaincodeID cid = ChaincodeID.newBuilder().setName("fabcar").build();
    req.setChaincodeID(cid);
    req.setFcn("createCar");
    req.setArgs(new String[] { key, make,model,color,owner });
    System.out.println("Executing for " + key);
    Collection<ProposalResponse> resps = channel.sendTransactionProposal(req);
    if (doCommit) {
        channel.sendTransaction(resps);
    }
} 




/**
 * Initialize and get HF channel
 *
 * @param client The HFC client
 * @return Initialized channel
 * @throws InvalidArgumentException
 * @throws TransactionException
 */
static Channel getChannel(HFClient client) throws InvalidArgumentException, TransactionException {
    // initialize channel
    // peer name and endpoint in fabcar network

    Properties peerProperties = new Properties();
    peerProperties.setProperty("pemFile", "D:/FabricCert/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);
    Peer peer = client.newPeer("peer0.org1.example.com", "grpcs://{remotemachineURL}:7051");
    // eventhub name and endpoint in fabcar network
    final Properties eventHubProperties = new Properties();
    eventHubProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] {5L, TimeUnit.MINUTES});
    eventHubProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] {8L, TimeUnit.SECONDS});
    EventHub eventHub = client.newEventHub("eventhub01", "grpcs://{remotemachineURL}:7053",eventHubProperties);
    // orderer name and endpoint in fabcar network
Properties ordererProperties = new Properties();
 ordererProperties.setProperty("pemFile", "D:/FabricCert/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});
    Orderer orderer = client.newOrderer("orderer.example.com", "grpcs://{remotemachineURL}:7050");
    // channel name in fabcar network
    Channel channel = client.newChannel("mychannel");
    channel.addPeer(peer);
    channel.addEventHub(eventHub);
    channel.addOrderer(orderer);
    channel.initialize();
    return channel;
}

/**
 * Create new HLF client
 *
 * @return new HLF client instance. Never null.
 * @throws CryptoException
 * @throws InvalidArgumentException
 */
static HFClient getHfClient() throws Exception {
    // initialize default cryptosuite
    CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
    // setup the client
    HFClient client = HFClient.createNewInstance();
    client.setCryptoSuite(cryptoSuite);
    return client;
}


/**
 * Register and enroll user with userId.
 * If AppUser object with the name already exist on fs it will be loaded and
 * registration and enrollment will be skipped.
 *
 * @param caClient  The fabric-ca client.
 * @param registrar The registrar to be used.
 * @param userId    The user id.
 * @return AppUser instance with userId, affiliation,mspId and enrollment set.
 * @throws Exception
 */
static AppUser getUser(HFCAClient caClient, AppUser registrar, String userId) throws Exception {
    AppUser appUser = tryDeserialize(userId);
    System.out.println("appUser"+appUser);
    if (appUser == null) {
        RegistrationRequest rr = new RegistrationRequest(userId, "org1");
        String enrollmentSecret = caClient.register(rr, registrar);            
        Enrollment enrollment = getEnrollment();
        enrollment =  caClient.enroll(userId, enrollmentSecret);
        byte[] certFile = Base64.encodeBase64(enrollment.getCert().getBytes()); 
        byte[] keyFile = Base64.encodeBase64(enrollment.getKey().toString().getBytes());   

        BufferedWriter bufferedWriter = null;
        File myFile = new File("D:/keyfile.key");
        // check if file exist, otherwise create the file before writing
        if (!myFile.exists()) {
            myFile.createNewFile();
        }
        Writer writer = new FileWriter(myFile);
        bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.write(enrollment.getKey().toString());
        bufferedWriter.close();
        appUser = new AppUser(userId, "org1", "Org1MSP", enrollment);
        serialize(appUser);
    }
    return appUser;
}


public static Enrollment getEnrollment() {
    return new Enrollment() {
        public PrivateKey getKey() {
            PrivateKey privateKey = null;
            try {
                File privateKeyFile = findFileSk("D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/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("D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/signcerts/[email protected]");
                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;
        }
    };
}

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;
}



/**
 * Enroll admin into fabric-ca using {@code admin/adminpw} credentials.
 * If AppUser object already exist serialized on fs it will be loaded and
 * new enrollment will not be executed.
 *
 * @param caClient The fabric-ca client
 * @return AppUser instance with userid, affiliation, mspId and enrollment set
 * @throws Exception
 */
static AppUser getAdmin(HFCAClient caClient) throws Exception {
    AppUser admin = tryDeserialize("admin");
    if (admin == null) {
        Enrollment adminEnrollment = caClient.enroll("admin", "adminpw");
        admin = new AppUser("admin", "org1", "Org1MSP", adminEnrollment);
        serialize(admin);
    }
    return admin;
}

/**
 * Get new fabric-ca client
 *
 * @param caUrl              The fabric-ca-server endpoint url
 * @param caClientProperties The fabri-ca client properties. Can be null.
 * @return new client instance. never null.
 * @throws Exception
 */
static HFCAClient getHfCaClient(String caUrl, Properties caClientProperties) throws Exception {
    CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
    HFCAClient caClient = HFCAClient.createNewInstance(caUrl, caClientProperties);
    caClient.setCryptoSuite(cryptoSuite);
    return caClient;
}


// user serialization and deserialization utility functions
// files are stored in the base directory

/**
 * Serialize AppUser object to file
 *
 * @param appUser The object to be serialized
 * @throws IOException
 */
static void serialize(AppUser appUser) throws IOException {
    try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(
            Paths.get(appUser.getName() + ".jso")))) {
        oos.writeObject(appUser);
    }
}

/**
 * Deserialize AppUser object from file
 *
 * @param name The name of the user. Used to build file name ${name}.jso
 * @return
 * @throws Exception
 */
static AppUser tryDeserialize(String name) throws Exception {
    if (Files.exists(Paths.get(name + ".jso"))) {
        return deserialize(name);
    }
    return null;
}

static AppUser deserialize(String name) throws Exception {
    try (ObjectInputStream decoder = new ObjectInputStream(
            Files.newInputStream(Paths.get(name + ".jso")))) {
        return (AppUser) decoder.readObject();
    }
}
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];
}}

And this is my error trace

DEBUG ReferenceCountedOpenSslContext - verification of certificate failed java.security.cert.CertificateException: No subject alternative DNS name matching {remotemachineURL} found. at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:191) at sun.security.util.HostnameChecker.match(HostnameChecker.java:93) at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:455) at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:436) at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:252) at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:136) at io.netty.handler.ssl.ReferenceCountedOpenSslClientContext$ExtendedTrustManagerVerifyCallback.verify(ReferenceCountedOpenSslClientContext.java:223) at io.netty.handler.ssl.ReferenceCountedOpenSslContext$AbstractCertificateVerifier.verify(ReferenceCountedOpenSslContext.java:606) at org.apache.tomcat.jni.SSL.readFromSSL(Native Method) at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.readPlaintextData(ReferenceCountedOpenSslEngine.java:470) at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:927) at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1033) at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1076) at io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:206) at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1117) at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1039) 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) at java.lang.Thread.run(Thread.java:745)

I am trying to initialize "mychannel" with peer0 from org1 and orderer and query for a value from the "byfn" network . Please ignore extra code if any or the comments .

Thanks

1

1 Answers

0
votes

Code worked , apparently there was some problem with the Enrollment . I had used a bad certificate . Changed certificate for enrollment and it worked Solved .Thanks