一个利用fabric-java-sdk调用balance-tranfer的例子

一个完整的fabric-java-sdk调用chaincode的例子

利用fabric-java-sdk调用chaincode的例子;包括:

  1. 发送proposal
  2. 分析proposalResponse内容(分析RWSet)
  3. 发送给orderer
  4. 接受EventHub事件。
$ cat SimpleClient.java 

import static java.lang.String.format;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import java.util.Properties;
import java.util.Set;

import org.hyperledger.fabric.protos.ledger.rwset.kvrwset.KvRwset;
import org.hyperledger.fabric.sdk.BlockEvent;
import org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent;
import org.hyperledger.fabric.sdk.ChaincodeID;
import org.hyperledger.fabric.sdk.ChaincodeResponse.Status;
import org.hyperledger.fabric.sdk.Channel;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.EventHub;
import org.hyperledger.fabric.sdk.HFClient;
import org.hyperledger.fabric.sdk.Orderer;
import org.hyperledger.fabric.sdk.Peer;
import org.hyperledger.fabric.sdk.ProposalResponse;
import org.hyperledger.fabric.sdk.TransactionProposalRequest;
import org.hyperledger.fabric.sdk.TxReadWriteSetInfo.NsRwsetInfo;
import org.hyperledger.fabric.sdk.User;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.google.protobuf.InvalidProtocolBufferException;

/**
 * Reference:
 *      https://github.com/hyperledger/fabric-sdk-java/blob/master/src/test/java/org/hyperledger/fabric/sdkintegration/End2endIT.java
 */
public class SimpleClient {
    private static Logger logger = Logger.getLogger(SimpleClient.class.getName());

    class BCSConfig {
        public static final String CHANNEL_NAME                 = "mychannel";
        public static final String CHAINCODE_NAME               = "mychaincode";
        public static final String CHAINCODE_VERSION            = "v1";
        public static final String ORGANIZATION_NAME            = "Org1";
        public static final String MSP_ID                       = "org1MSP";
        public static final String USER_NAME                    = "Admin";
        public static final String USER_KEY_FILE                = ".../crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/fb84dd8ec41bf439dfb1723d322fc607bfec67fd64e9e98867a04e4f723df21a_sk";
        public static final String USER_CERT_FILE               = ".../crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem";


        public static final String ORDERER1_ADDRESS             = "grpcs://orderer.example.com:7050";
        public static final String ORDERER1_TLS_CACERT_FILE     = ".../crypto-config/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem";

        public static final String PEER1_ADDRESS                = "grpcs://peer0.org1.example.com:7051";
        public static final String PEER1_TLS_CACERT_FILE        = ".../crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem";

        public static final String EVENTHUB1_ADDRESS            = "grpcs://peer0.org1.example.com:7053";
        public static final String EVENTHUB1_TLS_CACERT_FILE    = ".../crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem";
    }

    public static void main(String[] args) {
        SimpleClient simpleClient = new SimpleClient();
        simpleClient.run();
    }

    public void run() {
        try {
            HFClient client = initializeClient();
            Channel channel = initializeChannel(client, BCSConfig.CHANNEL_NAME);
            ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(BCSConfig.CHAINCODE_NAME).setVersion(BCSConfig.CHAINCODE_VERSION).build();

            // Send proposal
            Collection<ProposalResponse> propResp = sendProposal(client, channel, chaincodeID);
            // Send to orderer
            sendTransaction(channel, propResp);
                
            out("Done");  
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Create HFClient
    private HFClient initializeClient() throws CryptoException, InvalidArgumentException {
        HFClient client = HFClient.createNewInstance();
        client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
        client.setUserContext(new SimpleUser());
        return client;
    }
    
    // Create Channel
    private Channel initializeChannel( HFClient client, String channelName) throws InvalidArgumentException, TransactionException {
        Properties orderer1Prop = new Properties();
        orderer1Prop.setProperty("pemFile", BCSConfig.ORDERER1_TLS_CACERT_FILE);
        orderer1Prop.setProperty("sslProvider", "openSSL");
        orderer1Prop.setProperty("negotiationType", "TLS");
        orderer1Prop.setProperty("ordererWaitTimeMilliSecs", "300000");
        Orderer orderer1 = client.newOrderer("orderer", BCSConfig.ORDERER1_ADDRESS, orderer1Prop);

        Properties peer1Prop = new Properties();
        peer1Prop.setProperty("pemFile", BCSConfig.PEER1_TLS_CACERT_FILE);
        peer1Prop.setProperty("sslProvider", "openSSL");
        peer1Prop.setProperty("negotiationType", "TLS");
        Peer peer1 = client.newPeer("peer", BCSConfig.PEER1_ADDRESS, peer1Prop);

        Properties eventhub1Prop = new Properties();
        eventhub1Prop.setProperty("pemFile", BCSConfig.EVENTHUB1_TLS_CACERT_FILE);
        eventhub1Prop.setProperty("sslProvider", "openSSL");
        eventhub1Prop.setProperty("negotiationType", "TLS");
        EventHub eventHub = client.newEventHub("eventhub", BCSConfig.EVENTHUB1_ADDRESS, eventhub1Prop);

        Channel channel = client.newChannel(channelName);
        channel.addOrderer(orderer1);
        channel.addPeer(peer1);
        channel.addEventHub(eventHub);
        channel.initialize();
      
        return channel;
    }

    // Send proposal to endorser
    Collection<ProposalResponse> sendProposal(HFClient client, Channel channel, ChaincodeID chaincodeID) throws ProposalException, InvalidArgumentException {
        //String method = "query";
        //String[] args = {"b"};
        String method = "invoke";
        String[] args = {"a", "b", "1"};

        TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
        transactionProposalRequest.setChaincodeID(chaincodeID);
        transactionProposalRequest.setFcn(method);
        transactionProposalRequest.setArgs(args);
        
        out("Sending for proposal");
        Collection<ProposalResponse> invokePropResp = channel.sendTransactionProposal(transactionProposalRequest);
        for (ProposalResponse response : invokePropResp) {
            if (response.getStatus() == Status.SUCCESS) {
                out("Proposal response SUCC Txid=%s, peer=%s, data=[%s]", response.getTransactionID(), response.getPeer(), new String(response.getChaincodeActionResponsePayload()));
                dumpRWSet(response);
            } else {
                out("Proposal response FAIL Txid=%s, peer=%s, data=[%s]", response.getTransactionID(), response.getPeer(), new String(response.getChaincodeActionResponsePayload()));
            }
        }
        out("Sending to orderer");
        return invokePropResp;
    }

    // * Send transaction to orderer
    private void sendTransaction(Channel channel, Collection<ProposalResponse> invokePropResp) throws InterruptedException, ExecutionException, TimeoutException {
        CompletableFuture<BlockEvent.TransactionEvent> carfuture = channel.sendTransaction(invokePropResp);
        out("Wait event");
        TransactionEvent transactionEvent = carfuture.get(30, TimeUnit.SECONDS);
        out("Wait event return: " + transactionEvent.getChannelId() + " " + transactionEvent.getTransactionID() + " " + transactionEvent.getType() + " " + transactionEvent.getValidationCode());
    }

    private void out(String format, Object... args) {
        logger.info(format(format, args));
    }
    
    private String printableString(final String string) {
        int maxLogStringLength = 64;
        if (string == null || string.length() == 0) {
            return string;
        }

        String ret = string.replaceAll("[^\\p{Print}]", "?");
        ret = ret.substring(0, Math.min(ret.length(), maxLogStringLength)) + (ret.length() > maxLogStringLength ? "..." : "");
        return ret;
    }

    private void dumpRWSet(ProposalResponse response) {
        try {
            for (NsRwsetInfo nsRwsetInfo : response.getChaincodeActionResponseReadWriteSetInfo().getNsRwsetInfos()) {
                String namespace = nsRwsetInfo.getNamespace();
                KvRwset.KVRWSet rws = nsRwsetInfo.getRwset();

                int rsid = -1;
                for (KvRwset.KVRead readList : rws.getReadsList()) {
                    rsid++;
                    out("Namespace %s read  set[%d]: key[%s]=version[%d:%d]", namespace, rsid, readList.getKey(), readList.getVersion().getBlockNum(), readList.getVersion().getTxNum());
                }

                rsid = -1;
                for (KvRwset.KVWrite writeList : rws.getWritesList()) {
                    rsid++;
                    String valAsString = printableString(new String(writeList.getValue().toByteArray(), "UTF-8"));
                    out("Namespace %s write set[%d]: key[%s]=value[%s]", namespace, rsid, writeList.getKey(), valAsString);
                }
            }
        } catch (InvalidArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidProtocolBufferException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    class SimpleUser implements User {
        static {
            Security.addProvider(new BouncyCastleProvider());
        }

        @Override
        public String getName() {
            return BCSConfig.USER_NAME;
        }

        @Override
        public Set<String> getRoles() {
            return new HashSet<String>();
        }

        @Override
        public String getAccount() {
            return "";
        }

        @Override
        public String getAffiliation() {
            return "";
        }

        @Override
        public String getMspId() {
            return BCSConfig.MSP_ID;
        }

        @Override
        public Enrollment getEnrollment() {
            return new Enrollment() {
                @Override
                public PrivateKey getKey() {
                    try {
                        String privateKeyContent = new String(Files.readAllBytes(Paths.get(BCSConfig.USER_KEY_FILE)));
                        privateKeyContent = privateKeyContent.replaceAll("\\n", "").replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "");
                        KeyFactory kf = KeyFactory.getInstance("ECDSA");
                        PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyContent));
                        return kf.generatePrivate(keySpecPKCS8);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    } catch (GeneralSecurityException e) {
                        e.printStackTrace();
                        return null;
                    }
                }

                @Override
                public String getCert() {
                    try {
                        return new String(Files.readAllBytes(Paths.get(BCSConfig.USER_CERT_FILE)));
                    } catch (IOException e) {
                        e.printStackTrace();
                        return "";
                    }
                }
            };
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,193评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,306评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,130评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,110评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,118评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,085评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,007评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,844评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,283评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,508评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,667评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,395评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,985评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,630评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,797评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,653评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,553评论 2 352

推荐阅读更多精彩内容