Java源码示例:org.hyperledger.fabric.sdk.exception.TransactionException
示例1
public ChaincodeManager(String username, FabricConfig fabricConfig)
throws CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, TransactionException {
this.config = fabricConfig;
orderers = this.config.getOrderers();
peers = this.config.getPeers();
chaincode = this.config.getChaincode();
client = HFClient.createNewInstance();
log.debug("Create instance of HFClient");
client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
log.debug("Set Crypto Suite of HFClient");
fabricOrg = getFabricOrg(username, config.openCATLS());
channel = getChannel();
chaincodeID = getChaincodeID();
client.setUserContext(fabricOrg.getPeerAdmin());
}
示例2
/**
* 安装智能合约
*
* @param org 中继组织对象
*/
JSONObject install(IntermediateOrg org) throws ProposalException, InvalidArgumentException, TransactionException {
/// Send transaction proposal to all peers
InstallProposalRequest installProposalRequest = org.getClient().newInstallProposalRequest();
installProposalRequest.setChaincodeName(chaincodeName);
installProposalRequest.setChaincodeVersion(chaincodeVersion);
installProposalRequest.setChaincodeSourceLocation(new File(chaincodeSource));
installProposalRequest.setChaincodePath(chaincodePath);
installProposalRequest.setChaincodeLanguage(TransactionRequest.Type.GO_LANG);
installProposalRequest.setProposalWaitTime(proposalWaitTime);
long currentStart = System.currentTimeMillis();
Collection<ProposalResponse> installProposalResponses = org.getClient().sendInstallProposal(installProposalRequest, org.getChannel().get().getPeers());
log.info("chaincode install transaction proposal time = " + (System.currentTimeMillis() - currentStart));
return toPeerResponse(installProposalResponses, false);
}
示例3
/**
* 实例化智能合约
*
* @param org 中继组织对象
* @param args 初始化参数数组
*/
JSONObject instantiate(IntermediateOrg org, String[] args) throws ProposalException, InvalidArgumentException, IOException, ChaincodeEndorsementPolicyParseException, TransactionException {
/// Send transaction proposal to all peers
InstantiateProposalRequest instantiateProposalRequest = org.getClient().newInstantiationProposalRequest();
instantiateProposalRequest.setChaincodeID(chaincodeID);
instantiateProposalRequest.setProposalWaitTime(proposalWaitTime);
instantiateProposalRequest.setArgs(args);
ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
chaincodeEndorsementPolicy.fromYamlFile(new File(chaincodePolicy));
instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
Map<String, byte[]> tm2 = new HashMap<>();
tm2.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
tm2.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
tm2.put("result", ":)".getBytes(UTF_8));
instantiateProposalRequest.setTransientMap(tm2);
long currentStart = System.currentTimeMillis();
Collection<ProposalResponse> instantiateProposalResponses = org.getChannel().get().sendInstantiationProposal(instantiateProposalRequest, org.getChannel().get().getPeers());
log.info("chaincode instantiate transaction proposal time = " + (System.currentTimeMillis() - currentStart));
return toOrdererResponse(instantiateProposalResponses, org);
}
示例4
/**
* 升级智能合约
*
* @param org 中继组织对象
* @param args 初始化参数数组
*/
JSONObject upgrade(IntermediateOrg org, String[] args) throws ProposalException, InvalidArgumentException, IOException, ChaincodeEndorsementPolicyParseException, TransactionException {
/// Send transaction proposal to all peers
UpgradeProposalRequest upgradeProposalRequest = org.getClient().newUpgradeProposalRequest();
upgradeProposalRequest.setChaincodeID(chaincodeID);
upgradeProposalRequest.setProposalWaitTime(proposalWaitTime);
upgradeProposalRequest.setArgs(args);
ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
chaincodeEndorsementPolicy.fromYamlFile(new File(chaincodePolicy));
upgradeProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
Map<String, byte[]> tm2 = new HashMap<>();
tm2.put("HyperLedgerFabric", "UpgradeProposalRequest:JavaSDK".getBytes(UTF_8));
tm2.put("method", "UpgradeProposalRequest".getBytes(UTF_8));
tm2.put("result", ":)".getBytes(UTF_8));
upgradeProposalRequest.setTransientMap(tm2);
long currentStart = System.currentTimeMillis();
Collection<ProposalResponse> upgradeProposalResponses = org.getChannel().get().sendUpgradeProposal(upgradeProposalRequest, org.getChannel().get().getPeers());
log.info("chaincode instantiate transaction proposal time = " + (System.currentTimeMillis() - currentStart));
return toOrdererResponse(upgradeProposalResponses, org);
}
示例5
/**
* 执行智能合约
*
* @param org 中继组织对象
* @param fcn 方法名
* @param args 参数数组
*/
JSONObject invoke(IntermediateOrg org, String fcn, String[] args) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
/// Send transaction proposal to all peers
TransactionProposalRequest transactionProposalRequest = org.getClient().newTransactionProposalRequest();
transactionProposalRequest.setChaincodeID(chaincodeID);
transactionProposalRequest.setFcn(fcn);
transactionProposalRequest.setArgs(args);
transactionProposalRequest.setProposalWaitTime(proposalWaitTime);
Map<String, byte[]> tm2 = new HashMap<>();
tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8));
tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8));
tm2.put("result", ":)".getBytes(UTF_8));
transactionProposalRequest.setTransientMap(tm2);
long currentStart = System.currentTimeMillis();
Collection<ProposalResponse> transactionProposalResponses = org.getChannel().get().sendTransactionProposal(transactionProposalRequest, org.getChannel().get().getPeers());
log.info("chaincode invoke transaction proposal time = " + (System.currentTimeMillis() - currentStart));
return toOrdererResponse(transactionProposalResponses, org);
}
示例6
/**
* 查询智能合约
*
* @param org 中继组织对象
* @param fcn 方法名
* @param args 参数数组
*/
JSONObject query(IntermediateOrg org, String fcn, String[] args) throws InvalidArgumentException, ProposalException, TransactionException {
QueryByChaincodeRequest queryByChaincodeRequest = org.getClient().newQueryProposalRequest();
queryByChaincodeRequest.setArgs(args);
queryByChaincodeRequest.setFcn(fcn);
queryByChaincodeRequest.setChaincodeID(chaincodeID);
queryByChaincodeRequest.setProposalWaitTime(proposalWaitTime);
Map<String, byte[]> tm2 = new HashMap<>();
tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
queryByChaincodeRequest.setTransientMap(tm2);
long currentStart = System.currentTimeMillis();
Collection<ProposalResponse> queryProposalResponses = org.getChannel().get().queryByChaincode(queryByChaincodeRequest, org.getChannel().get().getPeers());
log.info("chaincode query transaction proposal time = " + (System.currentTimeMillis() - currentStart));
return toPeerResponse(queryProposalResponses, true);
}
示例7
/**
* Send transaction to Order
*
* @param transaction transaction to be sent
*/
Ab.BroadcastResponse sendTransaction(Common.Envelope transaction) throws Exception {
if (shutdown) {
throw new TransactionException(format("Orderer %s was shutdown.", name));
}
logger.debug(format("Orderer.sendTransaction %s", toString()));
OrdererClient localOrdererClient = getOrdererClient();
try {
return localOrdererClient.sendTransaction(transaction);
} catch (Throwable t) {
removeOrdererClient(true);
throw t;
}
}
示例8
public static Channel initializeChannel(HFClient client, String channelName, FabricConfig fabricConfig) throws InvalidArgumentException, TransactionException {
Orderer orderer1 = getOrderer(client, fabricConfig);
Peer peer0 = getPeer(client, fabricConfig);
Channel channel = client.newChannel(channelName);
channel.addOrderer(orderer1);
channel.addPeer(peer0);
channel.initialize();
return channel;
}
示例9
/**
* 查询智能合约
*
* @param fcn
* 方法名
* @param args
* 参数数组
* @return
* @throws InvalidArgumentException
* @throws ProposalException
* @throws IOException
* @throws TransactionException
* @throws CryptoException
* @throws InvalidKeySpecException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
*/
public Map<String, String> query(String fcn, String[] args) throws InvalidArgumentException, ProposalException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CryptoException, TransactionException, IOException {
Map<String, String> resultMap = new HashMap<>();
String payload = "";
QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
queryByChaincodeRequest.setArgs(args);
queryByChaincodeRequest.setFcn(fcn);
queryByChaincodeRequest.setChaincodeID(chaincodeID);
Map<String, byte[]> tm2 = new HashMap<>();
tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
queryByChaincodeRequest.setTransientMap(tm2);
Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest, channel.getPeers());
for (ProposalResponse proposalResponse : queryProposals) {
if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
log.debug("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() + ". Messages: "
+ proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified());
resultMap.put("code", "error");
resultMap.put("data", "Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() + ". Messages: "
+ proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified());
} else {
payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
log.debug("Query payload from peer: " + proposalResponse.getPeer().getName());
log.debug("TransactionID: " + proposalResponse.getTransactionID());
log.debug("" + payload);
resultMap.put("code", "success");
resultMap.put("data", payload);
resultMap.put("txid", proposalResponse.getTransactionID());
}
}
return resultMap;
}
示例10
/** 获取Fabric Channel */
Channel get() throws InvalidArgumentException, TransactionException {
if (!channel.isInitialized()) {
initChannel();
}
return channel;
}
示例11
/** 查询当前频道的链信息,包括链长度、当前最新区块hash以及当前最新区块的上一区块hash */
JSONObject queryBlockChainInfo() throws InvalidArgumentException, ProposalException, TransactionException {
if (!channel.isInitialized()) {
initChannel();
}
JSONObject blockchainInfo = new JSONObject();
blockchainInfo.put("height", channel.queryBlockchainInfo().getHeight());
blockchainInfo.put("currentBlockHash", Hex.encodeHexString(channel.queryBlockchainInfo().getCurrentBlockHash()));
blockchainInfo.put("previousBlockHash", Hex.encodeHexString(channel.queryBlockchainInfo().getPreviousBlockHash()));
return getSuccess(blockchainInfo);
}
示例12
/**
* 在指定频道内根据transactionID查询区块
*
* @param txID transactionID
*/
JSONObject queryBlockByTransactionID(String txID) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
if (!channel.isInitialized()) {
initChannel();
}
return execBlockInfo(channel.queryBlockByTransactionID(txID));
}
示例13
/**
* 在指定频道内根据hash查询区块
*
* @param blockHash hash
*/
JSONObject queryBlockByHash(byte[] blockHash) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
if (!channel.isInitialized()) {
initChannel();
}
return execBlockInfo(channel.queryBlockByHash(blockHash));
}
示例14
/**
* 在指定频道内根据区块高度查询区块
*
* @param blockNumber 区块高度
*/
JSONObject queryBlockByNumber(long blockNumber) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
if (!channel.isInitialized()) {
initChannel();
}
return execBlockInfo(channel.queryBlockByNumber(blockNumber));
}
示例15
private void peerVent(TransactionContext transactionContext) throws TransactionException {
logger.trace(toString() + "peerVent transaction: " + transactionContext);
if (shutdown) { // check aagin
logger.debug("peerVent not starting, shutting down.");
return;
}
final Envelope envelope;
try {
Ab.SeekPosition.Builder start = Ab.SeekPosition.newBuilder();
if (null != peerOptions.getNewest()) {
start.setNewest(Ab.SeekNewest.getDefaultInstance());
} else if (peerOptions.getStartEvents() != null) {
start.setSpecified(Ab.SeekSpecified.newBuilder().setNumber(peerOptions.getStartEvents()));
} else {
start.setNewest(Ab.SeekNewest.getDefaultInstance());
}
envelope = ProtoUtils.createSeekInfoEnvelope(transactionContext,
start.build(),
Ab.SeekPosition.newBuilder()
.setSpecified(Ab.SeekSpecified.newBuilder().setNumber(peerOptions.getStopEvents()).build())
.build(),
SeekInfo.SeekBehavior.BLOCK_UNTIL_READY,
clientTLSCertificateDigest);
connectEnvelope(envelope);
} catch (Exception e) {
throw new TransactionException(toString() + " error message: " + e.getMessage(), e);
}
}
示例16
void initiateEventing(TransactionContext transactionContext, PeerOptions peersOptions) throws TransactionException {
this.transactionContext = transactionContext.retryTransactionSameContext();
if (peerEventingClient == null && !shutdown) {
peerEventingClient = new PeerEventServiceClient(this, Endpoint.createEndpoint(url, properties), properties, peersOptions);
peerEventingClient.connect(transactionContext);
}
}
示例17
@BeforeClass
public static void setupClient() {
try {
hfclient = TestHFClient.newInstance();
shutdownChannel = new Channel("shutdown", hfclient);
shutdownChannel.addOrderer(hfclient.newOrderer("shutdow_orderer", "grpc://localhost:99"));
setField(shutdownChannel, "shutdown", true);
throwOrderer = new Orderer("foo", "grpc://localhost:8", null) {
@Override
Ab.BroadcastResponse sendTransaction(Common.Envelope transaction) throws Exception {
throw new Exception(BAD_STUFF);
}
@Override
Ab.DeliverResponse[] sendDeliver(Common.Envelope transaction) throws TransactionException {
throw new TransactionException(BAD_STUFF);
}
};
throwChannel = new Channel("throw", hfclient);
throwChannel.addOrderer(throwOrderer);
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Unexpected Exception " + e.getMessage());
}
}
示例18
public ChaincodeManager getChaincodeManager()
throws CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeySpecException, TransactionException, IOException {
return new ChaincodeManager(!username.equals("") ? username : "Admin", getFabricConfig());
}
示例19
private Channel getChannel()
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, CryptoException, InvalidArgumentException, TransactionException {
client.setUserContext(fabricOrg.getPeerAdmin());
return getChannel(fabricOrg, client);
}
示例20
private Channel getChannel(FabricOrg fabricOrg, HFClient client)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, CryptoException, InvalidArgumentException, TransactionException {
Channel channel = client.newChannel(chaincode.getChannelName());
log.debug("Get Chain " + chaincode.getChannelName());
channel.setTransactionWaitTime(chaincode.getTransactionWaitTime());
channel.setDeployWaitTime(chaincode.getDeployWaitTime());
for (int i = 0; i < peers.get().size(); i++) {
File peerCert = Paths.get(config.getCryptoConfigPath(), "/peerOrganizations", peers.getOrgDomainName(), "peers", peers.get().get(i).getPeerName(), "tls/server.crt")
.toFile();
if (!peerCert.exists()) {
throw new RuntimeException(
String.format("Missing cert file for: %s. Could not find at location: %s", peers.get().get(i).getPeerName(), peerCert.getAbsolutePath()));
}
Properties peerProperties = new Properties();
peerProperties.setProperty("pemFile", peerCert.getAbsolutePath());
// ret.setProperty("trustServerCertificate", "true"); //testing
// environment only NOT FOR PRODUCTION!
peerProperties.setProperty("hostnameOverride", peers.getOrgDomainName());
peerProperties.setProperty("sslProvider", "openSSL");
peerProperties.setProperty("negotiationType", "TLS");
// 在grpc的NettyChannelBuilder上设置特定选项
peerProperties.put("grpc.ManagedChannelBuilderOption.maxInboundMessageSize", 9000000);
channel.addPeer(client.newPeer(peers.get().get(i).getPeerName(), fabricOrg.getPeerLocation(peers.get().get(i).getPeerName()), peerProperties));
if (peers.get().get(i).isAddEventHub()) {
channel.addEventHub(
client.newEventHub(peers.get().get(i).getPeerEventHubName(), fabricOrg.getEventHubLocation(peers.get().get(i).getPeerEventHubName()), peerProperties));
}
}
for (int i = 0; i < orderers.get().size(); i++) {
File ordererCert = Paths.get(config.getCryptoConfigPath(), "/ordererOrganizations", orderers.getOrdererDomainName(), "orderers", orderers.get().get(i).getOrdererName(),
"tls/server.crt").toFile();
if (!ordererCert.exists()) {
throw new RuntimeException(
String.format("Missing cert file for: %s. Could not find at location: %s", orderers.get().get(i).getOrdererName(), ordererCert.getAbsolutePath()));
}
Properties ordererProperties = new Properties();
ordererProperties.setProperty("pemFile", ordererCert.getAbsolutePath());
ordererProperties.setProperty("hostnameOverride", orderers.getOrdererDomainName());
ordererProperties.setProperty("sslProvider", "openSSL");
ordererProperties.setProperty("negotiationType", "TLS");
ordererProperties.put("grpc.ManagedChannelBuilderOption.maxInboundMessageSize", 9000000);
ordererProperties.setProperty("ordererWaitTimeMilliSecs", "300000");
channel.addOrderer(
client.newOrderer(orderers.get().get(i).getOrdererName(), fabricOrg.getOrdererLocation(orderers.get().get(i).getOrdererName()), ordererProperties));
}
log.debug("channel.isInitialized() = " + channel.isInitialized());
if (!channel.isInitialized()) {
channel.initialize();
}
if (config.isRegisterEvent()) {
log.debug("========================Event事件监听注册========================");
channel.registerBlockListener(new BlockListener() {
@Override
public void received(BlockEvent event) {
// TODO
log.debug("========================Event事件监听开始========================");
try {
log.debug("event.getChannelId() = " + event.getChannelId());
log.debug("event.getEvent().getChaincodeEvent().getPayload().toStringUtf8() = " + event.getEvent().getChaincodeEvent().getPayload().toStringUtf8());
log.debug("event.getBlock().getData().getDataList().size() = " + event.getBlock().getData().getDataList().size());
ByteString byteString = event.getBlock().getData().getData(0);
String result = byteString.toStringUtf8();
log.debug("byteString.toStringUtf8() = " + result);
String r1[] = result.split("END CERTIFICATE");
String rr = r1[2];
log.debug("rr = " + rr);
} catch (InvalidProtocolBufferException e) {
// TODO
e.printStackTrace();
}
log.debug("========================Event事件监听结束========================");
}
});
}
return channel;
}
示例21
/**
* 执行智能合约
*
* @param fcn
* 方法名
* @param args
* 参数数组
* @return
* @throws InvalidArgumentException
* @throws ProposalException
* @throws InterruptedException
* @throws ExecutionException
* @throws TimeoutException
* @throws IOException
* @throws TransactionException
* @throws CryptoException
* @throws InvalidKeySpecException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
*/
public Map<String, String> invoke(String fcn, String[] args)
throws InvalidArgumentException, ProposalException, InterruptedException, ExecutionException, TimeoutException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CryptoException, TransactionException, IOException {
Map<String, String> resultMap = new HashMap<>();
Collection<ProposalResponse> successful = new LinkedList<>();
Collection<ProposalResponse> failed = new LinkedList<>();
/// Send transaction proposal to all peers
TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
transactionProposalRequest.setChaincodeID(chaincodeID);
transactionProposalRequest.setFcn(fcn);
transactionProposalRequest.setArgs(args);
Map<String, byte[]> tm2 = new HashMap<>();
tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8));
tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8));
tm2.put("result", ":)".getBytes(UTF_8));
transactionProposalRequest.setTransientMap(tm2);
long currentStart = System.currentTimeMillis();
Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers());
for (ProposalResponse response : transactionPropResp) {
if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
successful.add(response);
} else {
failed.add(response);
}
}
log.info("channel send transaction proposal time = " + ( System.currentTimeMillis() - currentStart));
Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(transactionPropResp);
if (proposalConsistencySets.size() != 1) {
log.error("Expected only one set of consistent proposal responses but got " + proposalConsistencySets.size());
}
if (failed.size() > 0) {
ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
log.error("Not enough endorsers for inspect:" + failed.size() + " endorser error: " + firstTransactionProposalResponse.getMessage() + ". Was verified: "
+ firstTransactionProposalResponse.isVerified());
resultMap.put("code", "error");
resultMap.put("data", firstTransactionProposalResponse.getMessage());
return resultMap;
} else {
log.info("Successfully received transaction proposal responses.");
ProposalResponse resp = transactionPropResp.iterator().next();
log.debug("TransactionID: " + resp.getTransactionID());
byte[] x = resp.getChaincodeActionResponsePayload();
String resultAsString = null;
if (x != null) {
resultAsString = new String(x, "UTF-8");
}
log.info("resultAsString = " + resultAsString);
channel.sendTransaction(successful);
resultMap.put("code", "success");
resultMap.put("data", resultAsString);
resultMap.put("txid", resp.getTransactionID());
return resultMap;
}
// channel.sendTransaction(successful).thenApply(transactionEvent -> {
// if (transactionEvent.isValid()) {
// log.info("Successfully send transaction proposal to orderer. Transaction ID: " + transactionEvent.getTransactionID());
// } else {
// log.info("Failed to send transaction proposal to orderer");
// }
// // chain.shutdown(true);
// return transactionEvent.getTransactionID();
// }).get(chaincode.getInvokeWatiTime(), TimeUnit.SECONDS);
}
示例22
/** 安装智能合约 */
public JSONObject install() throws ProposalException, InvalidArgumentException, TransactionException {
return org.getChainCode().install(org);
}
示例23
/** 查询当前频道的链信息,包括链长度、当前最新区块hash以及当前最新区块的上一区块hash */
public JSONObject queryBlockChainInfo() throws ProposalException, InvalidArgumentException, TransactionException {
return org.getChannel().queryBlockChainInfo();
}
示例24
/**
* 获取实例化合约、升级合约以及invoke合约的返回结果集合
*
* @param proposalResponses 请求返回集合
* @param org 中继组织对象
*/
private JSONObject toOrdererResponse(Collection<ProposalResponse> proposalResponses, IntermediateOrg org) throws InvalidArgumentException, UnsupportedEncodingException, TransactionException {
JSONObject jsonObject = new JSONObject();
ProposalResponse first = null;
Collection<ProposalResponse> successful = new LinkedList<>();
Collection<ProposalResponse> failed = new LinkedList<>();
for (ProposalResponse response : proposalResponses) {
if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
successful.add(response);
} else {
failed.add(response);
}
}
Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(proposalResponses);
if (proposalConsistencySets.size() != 1) {
log.error("Expected only one set of consistent proposal responses but got " + proposalConsistencySets.size());
}
if (failed.size() > 0) {
for (ProposalResponse fail : failed) {
log.error("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + fail.getMessage() + ", on peer" + fail.getPeer());
}
first = failed.iterator().next();
log.error("Not enough endorsers for inspect:" + failed.size() + " endorser error: " + first.getMessage() + ". Was verified: "
+ first.isVerified());
}
if (successful.size() > 0) {
log.info("Successfully received transaction proposal responses.");
ProposalResponse resp = proposalResponses.iterator().next();
log.debug("TransactionID: " + resp.getTransactionID());
byte[] x = resp.getChaincodeActionResponsePayload();
String resultAsString = null;
if (x != null) {
resultAsString = new String(x, "UTF-8");
}
log.info("resultAsString = " + resultAsString);
// org.getChannel().get().sendTransaction(successful).get(transactionWaitTime, TimeUnit.SECONDS);
org.getChannel().get().sendTransaction(successful);
jsonObject = parseResult(resultAsString);
jsonObject.put("code", BlockListener.SUCCESS);
jsonObject.put("txid", resp.getTransactionID());
return jsonObject;
} else {
jsonObject.put("code", BlockListener.ERROR);
jsonObject.put("error", null != first ? first.getMessage() : "error unknown");
return jsonObject;
}
// channel.sendTransaction(successful).thenApply(transactionEvent -> {
// if (transactionEvent.isValid()) {
// log.info("Successfully send transaction proposal to orderer. Transaction ID: " + transactionEvent.getTransactionID());
// } else {
// log.info("Failed to send transaction proposal to orderer");
// }
// // chain.shutdown(true);
// return transactionEvent.getTransactionID();
// }).get(chaincode.getInvokeWatiTime(), TimeUnit.SECONDS);
}
示例25
DeliverResponse[] sendDeliver(Common.Envelope transaction) throws TransactionException {
if (shutdown) {
throw new TransactionException(format("Orderer %s was shutdown.", name));
}
OrdererClient localOrdererClient = getOrdererClient();
logger.debug(format("%s Orderer.sendDeliver", toString()));
try {
return localOrdererClient.sendDeliver(transaction);
} catch (Throwable t) {
logger.error(format("%s removing %s due to %s", this.toString(), localOrdererClient, t.getMessage()));
removeOrdererClient(true);
throw t;
}
}
示例26
void connect(TransactionContext transactionContext) throws TransactionException {
if (shutdown) {
return;
}
peerVent(transactionContext);
}
示例27
void reconnectPeerEventServiceClient(final PeerEventServiceClient failedPeerEventServiceClient,
final Throwable throwable) {
if (shutdown) {
logger.debug(toString() + "not reconnecting PeerEventServiceClient shutdown ");
return;
}
PeerEventingServiceDisconnected ldisconnectedHandler = disconnectedHandler;
if (null == ldisconnectedHandler) {
return; // just wont reconnect.
}
TransactionContext ltransactionContext = transactionContext;
if (ltransactionContext == null) {
logger.warn(toString() + " not reconnecting PeerEventServiceClient no transaction available ");
return;
}
final TransactionContext fltransactionContext = ltransactionContext.retryTransactionSameContext();
final ExecutorService executorService = getExecutorService();
final PeerOptions peerOptions = null != failedPeerEventServiceClient.getPeerOptions() ? failedPeerEventServiceClient.getPeerOptions() :
PeerOptions.createPeerOptions();
if (!shutdown && executorService != null && !executorService.isShutdown() && !executorService.isTerminated()) {
executorService.execute(() -> ldisconnectedHandler.disconnected(new PeerEventingServiceDisconnectEvent() {
@Override
public BlockEvent getLatestBLockReceived() {
return lastBlockEvent;
}
@Override
public long getLastConnectTime() {
return lastConnectTime;
}
@Override
public long getReconnectCount() {
return reconnectCount.longValue();
}
@Override
public Throwable getExceptionThrown() {
return throwable;
}
@Override
public void reconnect(Long startBLockNumber) throws TransactionException {
logger.trace(format("%s reconnecting. Starting block number: %s", Peer.this.toString(), startBLockNumber == null ? "newest" : startBLockNumber));
reconnectCount.getAndIncrement();
if (startBLockNumber == null) {
peerOptions.startEventsNewest();
} else {
peerOptions.startEvents(startBLockNumber);
}
if (!shutdown) {
PeerEventServiceClient lpeerEventingClient = new PeerEventServiceClient(Peer.this,
Endpoint.createEndpoint(url, properties), properties, peerOptions);
lpeerEventingClient.connect(fltransactionContext);
peerEventingClient = lpeerEventingClient;
}
}
}));
}
}
示例28
/**
* 实例化智能合约
*
* @param args 初始化参数数组
*/
public JSONObject instantiate(String[] args) throws ProposalException, InvalidArgumentException, IOException, ChaincodeEndorsementPolicyParseException, TransactionException {
return org.getChainCode().instantiate(org, args);
}
示例29
/**
* 升级智能合约
*
* @param args 初始化参数数组
*/
public JSONObject upgrade(String[] args) throws ProposalException, InvalidArgumentException, IOException, ChaincodeEndorsementPolicyParseException, TransactionException {
return org.getChainCode().upgrade(org, args);
}
示例30
/**
* 执行智能合约
*
* @param fcn 方法名
* @param args 参数数组
*/
public JSONObject invoke(String fcn, String[] args) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
return org.getChainCode().invoke(org, fcn, args);
}