fabric-java-sdk ——建立简单的请求(脱离配置)

前言

一如既往的,直接通过参数进行对fabric节点的调用。

重写一个UserInfo和Enrollment

//改为直接传入string的key.

public class FCUserInfo implements User {
    protected String name;
    protected String mspid;
    private Set roles;
    private String account;
    private String affiliation;
    private Enrollment enrollment;

    public FCUserInfo(String mspid, String pem, String key) {
        this.name=UUID.randomUUID().toString();
        this.mspid = mspid;
        this.enrollment = new FCEnrollment(pem, key);
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setMspid(String mspid) {
        this.mspid = mspid;
    }

    public void setRoles(Set roles) {
        this.roles = roles;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void setAffiliation(String affiliation) {
        this.affiliation = affiliation;
    }

    public void setEnrollment(Enrollment enrollment) {
        this.enrollment = enrollment;
    }

    /**
     * Get the name that identifies the user.
     *
     * @return the user name.
     */
    @Override
    public String getName() {
        return name;
    }

    /**
     * Get the roles to which the user belongs.
     *
     * @return role names.
     */
    @Override
    public Set getRoles() {
        return roles;
    }

    /**
     * Get the user's account
     *
     * @return the account name
     */
    @Override
    public String getAccount() {
        return account;
    }

    /**
     * Get the user's affiliation.
     *
     * @return the affiliation.
     */
    @Override
    public String getAffiliation() {
        return affiliation;
    }

    /**
     * Get the user's enrollment certificate information.
     *
     * @return the enrollment information.
     */
    @Override
    public Enrollment getEnrollment() {
        return enrollment;
    }

    /**
     * Get the Membership Service Provider Identifier provided by the user's organization.
     *
     * @return MSP Id.
     */
    @Override
    public String getMspId() {
        return mspid;
    }
}



public class FCEnrollment implements Enrollment, Serializable {

    private static final long serialVersionUID = -4274445336349657179L;
    private PrivateKey key;
    private String cert;

    FCEnrollment(String signedPem, String key) {
        PrivateKey privateKey = null;
        try {
            privateKey = getPrivateKeyFromString(key);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.key = privateKey;
        this.cert = signedPem;
    }

    public PrivateKey getKey() {
        return key;
    }

    public String getCert() {
        return cert;
    }

    private static PrivateKey getPrivateKeyFromString(String data)
            throws IOException {

        final Reader pemReader = new StringReader(data);

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

        return new JcaPEMKeyConverter().getPrivateKey(pemPair);
    }
}

初步只是改了key相关。

接下来就是测试调用

package org.hyperledger.fabric.proxy;

import com.google.protobuf.ByteString;
import org.hyperledger.fabric.protos.peer.FabricProposal;
import org.hyperledger.fabric.protos.peer.FabricProposalResponse;
import org.hyperledger.fabric.protos.peer.Query;
import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.transaction.QueryInstalledChaincodesBuilder;
import org.hyperledger.fabric.sdk.transaction.TransactionContext;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.nio.charset.StandardCharsets;
import java.util.*;

import static java.lang.String.format;


public class HFClientTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    String ccName="mycc";
    String version="1.0";
    String path="chaincode/ecdspay/";
    public static HFClient client = null;
    public static Peer peer = null;
    public static Channel channel = null;
    public static Orderer orderer = null;
    public static String adminPem = "-----BEGIN CERTIFICATE-----\n" +
            "MIICJzCCAc6gAwIBAgIRAPKxzN10838MyAJVUQ3aEScwCgYIKoZIzj0EAwIwcTEL\n" +
            "MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG\n" +
            "cmFuY2lzY28xGDAWBgNVBAoTD29yZzAuZWNkc3BheS5jbjEbMBkGA1UEAxMSY2Eu\n" +
            "b3JnMC5lY2RzcGF5LmNuMB4XDTE4MDUyNTA0NTUxNVoXDTI4MDUyMjA0NTUxNVow\n" +
            "azELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\n" +
            "biBGcmFuY2lzY28xDzANBgNVBAsTBmNsaWVudDEeMBwGA1UEAwwVQWRtaW5Ab3Jn\n" +
            "MC5lY2RzcGF5LmNuMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGmJdPYk9TgaP\n" +
            "tDIt0JXmJcvREvcissIt+uEcTW50FxmnQby4N06c9nNKUO6Elcpe7JRl/nWs3h8+\n" +
            "fGK/ql4dBqNNMEswDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB/wQCMAAwKwYDVR0j\n" +
            "BCQwIoAg5rcB8oVIXVHo9/viPDR5hg14orkXucmF0M4JoqBsSJ4wCgYIKoZIzj0E\n" +
            "AwIDRwAwRAIgK3RkypY6KXQxffqvWA5+QRvo+CTBs/2GQosX7gEPJ7oCIGVfYdS1\n" +
            "EYv5YnUzjMAxjIeH4A2mk3vVdtXtuzxdglSR\n" +
            "-----END CERTIFICATE-----\n";
    public static String adminKey = "-----BEGIN PRIVATE KEY-----\n" +
            "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgdL2ip02CkjhQzjB6\n" +
            "3NRsGFAb9sA+SPZbGR/osV2Ba7ShRANCAAQaYl09iT1OBo+0Mi3QleYly9ES9yKy\n" +
            "wi364RxNbnQXGadBvLg3Tpz2c0pQ7oSVyl7slGX+dazeHz58Yr+qXh0G\n" +
            "-----END PRIVATE KEY-----\n";
    public static String pem = "-----BEGIN CERTIFICATE-----\n" +
            "MIICZDCCAgqgAwIBAgIRAJdl11zCkPNfxpSf88Kava8wCgYIKoZIzj0EAwIwgYIx\n" +
            "CzAJBgNVBAYTAkNOMRIwEAYDVQQIEwlndWFuZ2RvbmcxETAPBgNVBAcTCHNoZW56\n" +
            "aGVuMSIwIAYDVQQKExlwbGF0Zm9ybS5iYW5rYWxsaWFuY2Uub3JnMSgwJgYDVQQD\n" +
            "Ex90bHNjYS5wbGF0Zm9ybS5iYW5rYWxsaWFuY2Uub3JnMB4XDTE4MDkyMDEwMTYw\n" +
            "OFoXDTI4MDkxNzEwMTYwOFowgYIxCzAJBgNVBAYTAkNOMRIwEAYDVQQIEwlndWFu\n" +
            "Z2RvbmcxETAPBgNVBAcTCHNoZW56aGVuMSIwIAYDVQQKExlwbGF0Zm9ybS5iYW5r\n" +
            "YWxsaWFuY2Uub3JnMSgwJgYDVQQDEx90bHNjYS5wbGF0Zm9ybS5iYW5rYWxsaWFu\n" +
            "Y2Uub3JnMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIaCYjoh42oL7yyvWgufa\n" +
            "DbRWn8WuN4AdRrI4rVxuBChAxUoru8u6F8LPX783x0y0iFQFavviP0/0Sgo5fevx\n" +
            "cKNfMF0wDgYDVR0PAQH/BAQDAgGmMA8GA1UdJQQIMAYGBFUdJQAwDwYDVR0TAQH/\n" +
            "BAUwAwEB/zApBgNVHQ4EIgQgu6ELkHx4gBF9r2E1luR09N0LGtimYLZPNsZslI5K\n" +
            "8CkwCgYIKoZIzj0EAwIDSAAwRQIhAOHKOaN3c0UJCSIMIvF2BIzgwu9IttCw8GLi\n" +
            "6GD0ZNSNAiBnTgMAJc7kdot9LmXWiUrqoFRcuRpfcfO8ZsrFm0kVdA==\n" +
            "-----END CERTIFICATE-----\n";

    @BeforeClass
    public static void setupClient() {
        try {
            client = HFClient.createNewInstance();
            client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
            FCUserInfo user = new FCUserInfo("Org0MSP", adminPem, adminKey);
            client.setUserContext(user);
            channel = client.newChannel("channel01");
            Properties opts = new Properties();
//            opts.put("pemBytes", pem.getBytes());
//            opts.setProperty("trustServerCertificate", "true");
//            opts.put("clientKeyBytes", clientKey.getBytes());
//            opts.put("clientCertBytes", clientCert.getBytes());
//            peer = client.newPeer("peer0", "grpcs://peer0.platform.bankalliance.org:7051", opts);
            peer = client.newPeer("peer0", "grpc://192.168.184.130:7051", opts);
            orderer = client.newOrderer("orderer0", "grpc://192.168.184.130:7050", opts);

            channel.addPeer(peer, Channel.PeerOptions.createPeerOptions());
            channel.addOrderer(orderer);

            channel.initialize();
            System.out.println(channel.isShutdown());
//            channel.shutdown(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testQueryInstalledChaincodes() {
        try {
            List chaincodeInfos = client.queryInstalledChaincodes(peer);
            if (!chaincodeInfos.isEmpty())
                System.out.println(chaincodeInfos.get(0).toString());
        } catch (InvalidArgumentException e) {
            e.printStackTrace();
        } catch (ProposalException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testQueryChannels() {
        try {
            Set channels = client.queryChannels(peer);
            if (channels != null)
                System.out.println(channels.toString());
        } catch (InvalidArgumentException e) {
            e.printStackTrace();
        } catch (ProposalException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testQueryBlock() {
        try {
            BlockInfo blockInfo = channel.queryBlockByNumber(peer, 0);
            System.out.println(blockInfo.getChannelId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//测试调用任一cc
    @Test
    public void testInvokeCC() {
        ChaincodeID.Builder ccBuilder=ChaincodeID.newBuilder();
        ccBuilder.setName(ccName);
//        ccBuilder.setVersion(version);
//        ccBuilder.setPath(path);
        String func="OrderListQuery";
        ArrayList argList = new ArrayList<>();
        argList.add("");
        try {
            TransactionProposalRequest request = TransactionProposalRequest.newInstance(client.getUserContext());
            request.setFcn(func);
            request.setArgs(argList);
            request.setProposalWaitTime(15000);
            request.setChaincodeID(ccBuilder.build());
            Collection proposalResponses = channel.sendTransactionProposal(request, Collections.singletonList(peer));
            if (null == proposalResponses) {
                Assert.fail("proposalResponses is null");
            }
            if (proposalResponses.size() != 1) {
                Assert.fail(format("Peer %s expected one response but got back %d  responses ", peer.getName(), proposalResponses.size()));
            }
            ProposalResponse proposalResponse = proposalResponses.iterator().next();
            FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse();
            if (null == fabricResponse) {
                Assert.fail(format("Peer %s return with empty fabric response", peer.getName()));
            }
            final FabricProposalResponse.Response fabricResponseResponse = fabricResponse.getResponse();
            if (null == fabricResponseResponse) { //not likely but check it.
                Assert.fail(format("Peer %s return with empty fabricResponseResponse", peer.getName()));
            }
            if (200 != fabricResponseResponse.getStatus()) {
                Assert.fail(format("Peer %s  expected 200, actual returned was: %d. "
                        + fabricResponseResponse.getMessage(), peer.getName(), fabricResponseResponse.getStatus()));
            }
            System.out.println(fabricResponseResponse.getPayload());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

测试的是本地虚拟机起的一个dev环境。

启用tls的话,只需opts.put("pemBytes", pem.getBytes());

我们只需要单向验证,所以可以把信任证书校验去掉。修改Endpoint类的构造方法(注释掉的为原代码):

//                        try (InputStream myInputStream = new ByteArrayInputStream(pemBytes)) {
//                            sslContext = clientContextBuilder
//                                    .trustManager(myInputStream)
//                                    .build();
//                        }
                            sslContext = clientContextBuilder
                                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                                    .build();

 

你可能感兴趣的:(fabric,java)