一个完整的fabric-java-sdk调用chaincode的例子
利用fabric-java-sdk调用chaincode的例子;包括:
- 发送proposal
- 分析proposalResponse内容(分析RWSet)
- 发送给orderer
- 接受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/[email protected]/msp/keystore/fb84dd8ec41bf439dfb1723d322fc607bfec67fd64e9e98867a04e4f723df21a_sk";
public static final String USER_CERT_FILE = ".../crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/signcerts/[email protected]";
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 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 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 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 invokePropResp) throws InterruptedException, ExecutionException, TimeoutException {
CompletableFuture 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 getRoles() {
return new HashSet();
}
@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 "";
}
}
};
}
}
}