From 10d2358177dd3f87bd39e1008774e66e38174376 Mon Sep 17 00:00:00 2001 From: "Mark S. Lewis" Date: Tue, 3 Sep 2019 15:49:16 +0100 Subject: [PATCH] Update to latest protobufs from fabric-protos Change-Id: I5660e25ac20faf872cd44cc5405294c12cc92b4a Signed-off-by: Mark S. Lewis --- pom.xml | 35 +- .../hyperledger/fabric/sdk/BlockEvent.java | 22 +- .../org/hyperledger/fabric/sdk/BlockInfo.java | 170 ++------- .../sdk/ChaincodeActionDeserializer.java | 41 +- .../ChaincodeActionPayloadDeserializer.java | 46 +-- .../ChaincodeEndorsedActionDeserializer.java | 43 +-- .../fabric/sdk/ChaincodeEvent.java | 30 +- .../ChaincodeProposalPayloadDeserializer.java | 34 +- .../org/hyperledger/fabric/sdk/Channel.java | 358 ++++-------------- .../fabric/sdk/EndorserClient.java | 10 +- .../fabric/sdk/EnvelopeDeserializer.java | 32 +- ...eCheckCommitReadinessProposalResponse.java | 5 +- ...ryChaincodeDefinitionProposalResponse.java | 12 +- ...yChaincodeDefinitionsProposalResponse.java | 5 +- ...eryInstalledChaincodeProposalResponse.java | 14 +- ...ryInstalledChaincodesProposalResponse.java | 13 +- .../java/org/hyperledger/fabric/sdk/Peer.java | 48 +-- .../fabric/sdk/PeerEventServiceClient.java | 60 +-- .../fabric/sdk/ProposalResponse.java | 71 +--- .../ProposalResponsePayloadDeserializer.java | 34 +- .../fabric/sdk/ServiceDiscovery.java | 91 +---- .../sdk/TransactionActionDeserializer.java | 39 +- .../fabric/sdk/TransactionDeserializer.java | 30 +- .../fabric/sdk/TransactionInfo.java | 23 +- .../fabric/sdk/TransactionRequest.java | 6 - .../PeerEventingServiceException.java | 8 +- .../sdk/transaction/CSCCProposalBuilder.java | 11 +- .../transaction/InstallProposalBuilder.java | 17 +- .../InstantiateProposalBuilder.java | 7 +- .../sdk/transaction/LSCCProposalBuilder.java | 4 +- ...codeDefinitionForMyOrgProposalBuilder.java | 4 +- .../LifecycleCheckCommitReadinessBuilder.java | 4 +- ...mitChaincodeDefinitionProposalBuilder.java | 21 +- .../LifecycleInstallProposalBuilder.java | 4 +- .../transaction/LifecycleProposalBuilder.java | 7 +- ...ecycleQueryChaincodeDefinitionBuilder.java | 4 +- ...cycleQueryChaincodeDefinitionsBuilder.java | 4 +- ...fecycleQueryInstalledChaincodeBuilder.java | 6 +- .../sdk/transaction/ProposalBuilder.java | 56 +-- .../fabric/sdk/transaction/ProtoUtils.java | 136 ++----- .../sdk/transaction/TransactionBuilder.java | 33 +- src/main/proto/common/collection.proto | 17 +- src/main/proto/common/common.proto | 63 ++- src/main/proto/common/configtx.proto | 22 +- src/main/proto/common/configuration.proto | 23 +- src/main/proto/common/ledger.proto | 20 +- src/main/proto/common/policies.proto | 24 +- src/main/proto/discovery/protocol.proto | 17 +- src/main/proto/gossip/message.proto | 110 +++--- .../ledger/queryresult/kv_query_result.proto | 29 ++ .../proto/ledger/rwset/kvrwset/kv_rwset.proto | 10 +- src/main/proto/ledger/rwset/rwset.proto | 24 +- src/main/proto/msp/identities.proto | 15 +- src/main/proto/msp/msp_config.proto | 19 +- src/main/proto/msp/msp_principal.proto | 33 +- src/main/proto/orderer/ab.proto | 46 +-- src/main/proto/orderer/cluster.proto | 64 ++++ src/main/proto/orderer/configuration.proto | 64 ++++ .../orderer/etcdraft/configuration.proto | 36 ++ .../proto/orderer/etcdraft/metadata.proto | 30 ++ src/main/proto/orderer/kafka.proto | 71 ++++ src/main/proto/peer/chaincode.proto | 32 +- src/main/proto/peer/chaincode_event.proto | 23 +- src/main/proto/peer/chaincode_shim.proto | 179 +++++++++ src/main/proto/peer/configuration.proto | 29 +- src/main/proto/peer/events.proto | 39 +- .../peer/lifecycle/chaincode_definition.proto | 31 ++ src/main/proto/peer/lifecycle/db.proto | 30 ++ src/main/proto/peer/lifecycle/lifecycle.proto | 27 +- src/main/proto/peer/peer.proto | 21 +- src/main/proto/peer/policy.proto | 10 +- src/main/proto/peer/proposal.proto | 131 +++---- src/main/proto/peer/proposal_response.proto | 110 ++---- src/main/proto/peer/query.proto | 20 +- src/main/proto/peer/resources.proto | 54 +++ src/main/proto/peer/signed_cc_dep_spec.proto | 30 ++ src/main/proto/peer/transaction.proto | 149 ++++---- .../proto/transientstore/transientstore.proto | 22 ++ .../hyperledger/fabric/sdk/ChannelTest.java | 148 +------- .../org/hyperledger/fabric/sdk/PeerTest.java | 11 +- .../sdk/identity/IdemixIdentitiesTest.java | 12 +- .../fabric/sdk/security/TLSCertGenTest.java | 13 +- .../fabric/sdkintegration/End2endIT.java | 27 +- 83 files changed, 1455 insertions(+), 2028 deletions(-) create mode 100644 src/main/proto/ledger/queryresult/kv_query_result.proto create mode 100644 src/main/proto/orderer/cluster.proto create mode 100644 src/main/proto/orderer/configuration.proto create mode 100644 src/main/proto/orderer/etcdraft/configuration.proto create mode 100644 src/main/proto/orderer/etcdraft/metadata.proto create mode 100644 src/main/proto/orderer/kafka.proto mode change 100755 => 100644 src/main/proto/peer/chaincode_event.proto create mode 100644 src/main/proto/peer/chaincode_shim.proto create mode 100644 src/main/proto/peer/lifecycle/chaincode_definition.proto create mode 100644 src/main/proto/peer/lifecycle/db.proto create mode 100644 src/main/proto/peer/resources.proto create mode 100644 src/main/proto/peer/signed_cc_dep_spec.proto create mode 100644 src/main/proto/transientstore/transientstore.proto diff --git a/pom.xml b/pom.xml index 17bd1a96..8bd0c1b3 100644 --- a/pom.xml +++ b/pom.xml @@ -303,7 +303,7 @@ protobuf-java directly, you will be transitively depending on the protobuf-java version that grpc depends on. --> - com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier} + com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier} grpc-java io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier} @@ -321,7 +321,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + 3.8.1 1.8 1.8 @@ -331,6 +331,37 @@ -Xlint + + + default-compile + compile + + compile + + + + org/hyperledger/fabric/protos/**/*.java + + + + + compile-main + compile + + compile + + + + org/hyperledger/fabric/protos/**/*.java + + true + true + + -Xlint + + + + org.apache.maven.plugins diff --git a/src/main/java/org/hyperledger/fabric/sdk/BlockEvent.java b/src/main/java/org/hyperledger/fabric/sdk/BlockEvent.java index 0434da00..adb1dc73 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/BlockEvent.java +++ b/src/main/java/org/hyperledger/fabric/sdk/BlockEvent.java @@ -19,7 +19,7 @@ import com.google.protobuf.InvalidProtocolBufferException; import org.hyperledger.fabric.protos.common.Common.Block; -import org.hyperledger.fabric.protos.peer.PeerEvents; +import org.hyperledger.fabric.protos.peer.EventsPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; /** @@ -30,7 +30,7 @@ public class BlockEvent extends BlockInfo { private final Peer peer; - BlockEvent(Peer peer, PeerEvents.DeliverResponse resp) { + BlockEvent(Peer peer, EventsPackage.DeliverResponse resp) { super(resp); this.peer = peer; } @@ -44,7 +44,6 @@ public Peer getPeer() { return peer; } - TransactionEvent getTransactionEvent(int index) throws InvalidProtocolBufferException { TransactionEvent ret = null; @@ -65,7 +64,7 @@ public class TransactionEvent extends TransactionEnvelopeInfo { super(transactionEnvelopeInfo.getTransactionDeserializer()); } - TransactionEvent(PeerEvents.FilteredTransaction filteredTransaction) { + TransactionEvent(EventsPackage.FilteredTransaction filteredTransaction) { super(filteredTransaction); } @@ -74,11 +73,8 @@ public class TransactionEvent extends TransactionEnvelopeInfo { * * @return BlockEvent for this transaction. */ - public BlockEvent getBlockEvent() { - return BlockEvent.this; - } /** @@ -86,28 +82,22 @@ public BlockEvent getBlockEvent() { * * @return return peer producing the event. */ - public Peer getPeer() { - return BlockEvent.this.getPeer(); } } List getTransactionEventsList() { - ArrayList ret = new ArrayList(getTransactionCount()); for (TransactionEvent transactionEvent : getTransactionEvents()) { ret.add(transactionEvent); } return ret; - } public Iterable getTransactionEvents() { - return new TransactionEventIterable(); - } class TransactionEventIterator implements Iterator { @@ -122,22 +112,17 @@ class TransactionEventIterator implements Iterator { @Override public boolean hasNext() { return returned < max; - } @Override public TransactionEvent next() { - TransactionEvent ret = null; // Filter for only transactions but today it's not really needed. // Blocks with transactions only has transactions or a single pdate. try { do { - ret = getTransactionEvent(ci++); - } while (ret == null); - } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } @@ -147,7 +132,6 @@ public TransactionEvent next() { } class TransactionEventIterable implements Iterable { - @Override public Iterator iterator() { return new TransactionEventIterator(); diff --git a/src/main/java/org/hyperledger/fabric/sdk/BlockInfo.java b/src/main/java/org/hyperledger/fabric/sdk/BlockInfo.java index f8f17a27..f50265fc 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/BlockInfo.java +++ b/src/main/java/org/hyperledger/fabric/sdk/BlockInfo.java @@ -26,22 +26,20 @@ import org.hyperledger.fabric.protos.msp.Identities; import org.hyperledger.fabric.protos.peer.Chaincode; import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeInput; -import org.hyperledger.fabric.protos.peer.FabricTransaction; -import org.hyperledger.fabric.protos.peer.PeerEvents; -import org.hyperledger.fabric.protos.peer.PeerEvents.FilteredTransaction; +import org.hyperledger.fabric.protos.peer.EventsPackage; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; +import org.hyperledger.fabric.protos.peer.TransactionPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; import org.hyperledger.fabric.sdk.transaction.ProtoUtils; import static java.lang.String.format; -import static org.hyperledger.fabric.protos.peer.FabricProposalResponse.Endorsement; -import static org.hyperledger.fabric.sdk.BlockInfo.EnvelopeType.TRANSACTION_ENVELOPE; /** * BlockInfo contains the data from a {@link Block} */ public class BlockInfo { private final BlockDeserializer block; //can be only one or the other. - private final PeerEvents.FilteredBlock filteredBlock; + private final EventsPackage.FilteredBlock filteredBlock; BlockInfo(Block block) { @@ -49,18 +47,18 @@ public class BlockInfo { this.block = new BlockDeserializer(block); } - BlockInfo(PeerEvents.DeliverResponse resp) { + BlockInfo(EventsPackage.DeliverResponse resp) { - final PeerEvents.DeliverResponse.TypeCase type = resp.getTypeCase(); + final EventsPackage.DeliverResponse.TypeCase type = resp.getTypeCase(); - if (type == PeerEvents.DeliverResponse.TypeCase.BLOCK) { + if (type == EventsPackage.DeliverResponse.TypeCase.BLOCK) { final Block respBlock = resp.getBlock(); filteredBlock = null; if (respBlock == null) { throw new AssertionError("DeliverResponse type block but block is null"); } this.block = new BlockDeserializer(respBlock); - } else if (type == PeerEvents.DeliverResponse.TypeCase.FILTERED_BLOCK) { + } else if (type == EventsPackage.DeliverResponse.TypeCase.FILTERED_BLOCK) { filteredBlock = resp.getFilteredBlock(); block = null; if (filteredBlock == null) { @@ -84,7 +82,6 @@ public boolean isFiltered() { } public String getChannelId() throws InvalidProtocolBufferException { - return isFiltered() ? filteredBlock.getChannelId() : getEnvelopeInfo(0).getChannelId(); } @@ -96,9 +93,9 @@ public Block getBlock() { } /** - * @return the raw {@link org.hyperledger.fabric.protos.peer.PeerEvents.FilteredBlock} + * @return the raw {@link org.hyperledger.fabric.protos.peer.EventsPackage.FilteredBlock} */ - public PeerEvents.FilteredBlock getFilteredBlock() { + public EventsPackage.FilteredBlock getFilteredBlock() { return !isFiltered() ? null : filteredBlock; } @@ -113,7 +110,6 @@ public byte[] getPreviousHash() { * @return the {@link Block} data hash value and null if filtered block. */ public byte[] getDataHash() { - return isFiltered() ? null : block.getDataHash().toByteArray(); } @@ -121,7 +117,6 @@ public byte[] getDataHash() { * @return the {@link Block} transaction metadata value return null if filtered block. */ public byte[] getTransActionsMetaData() { - return isFiltered() ? null : block.getTransActionsMetaData(); } @@ -137,7 +132,6 @@ public long getBlockNumber() { * * @return the number of transactions in this block. */ - public int getEnvelopeCount() { return isFiltered() ? filteredBlock.getFilteredTransactionsCount() : block.getData().getDataCount(); } @@ -149,16 +143,14 @@ public int getEnvelopeCount() { * * @return Number of endorser transaction found in the block. */ - public int getTransactionCount() { if (isFiltered()) { - int ltransactionCount = transactionCount; if (ltransactionCount < 0) { ltransactionCount = 0; for (int i = filteredBlock.getFilteredTransactionsCount() - 1; i >= 0; --i) { - FilteredTransaction filteredTransactions = filteredBlock.getFilteredTransactions(i); + EventsPackage.FilteredTransaction filteredTransactions = filteredBlock.getFilteredTransactions(i); Common.HeaderType type = filteredTransactions.getType(); if (type == Common.HeaderType.ENDORSER_TRANSACTION) { ++ltransactionCount; @@ -171,12 +163,11 @@ public int getTransactionCount() { } int ltransactionCount = transactionCount; if (ltransactionCount < 0) { - ltransactionCount = 0; for (int i = getEnvelopeCount() - 1; i >= 0; --i) { try { EnvelopeInfo envelopeInfo = getEnvelopeInfo(i); - if (envelopeInfo.getType() == TRANSACTION_ENVELOPE) { + if (envelopeInfo.getType() == EnvelopeType.TRANSACTION_ENVELOPE) { ++ltransactionCount; } } catch (InvalidProtocolBufferException e) { @@ -191,11 +182,10 @@ public int getTransactionCount() { /** * Wrappers Envelope */ - public class EnvelopeInfo { private final EnvelopeDeserializer envelopeDeserializer; private final HeaderDeserializer headerDeserializer; - protected final FilteredTransaction filteredTx; + protected final EventsPackage.FilteredTransaction filteredTx; /** * This block is filtered @@ -204,7 +194,6 @@ public class EnvelopeInfo { */ boolean isFiltered() { return filteredTx != null; - } //private final EnvelopeDeserializer envelopeDeserializer; @@ -215,11 +204,10 @@ boolean isFiltered() { filteredTx = null; } - EnvelopeInfo(FilteredTransaction filteredTx) { + EnvelopeInfo(EventsPackage.FilteredTransaction filteredTx) { this.filteredTx = filteredTx; envelopeDeserializer = null; headerDeserializer = null; - } /** @@ -228,7 +216,6 @@ boolean isFiltered() { * @return The channel id also referred to as channel name. */ public String getChannelId() { - return BlockInfo.this.isFiltered() ? filteredBlock.getChannelId() : headerDeserializer.getChannelHeader().getChannelId(); } @@ -257,9 +244,7 @@ public String getMspid() { IdentitiesInfo(Identities.SerializedIdentity identity) { mspid = identity.getMspid(); id = identity.getIdBytes().toStringUtf8(); - } - } /** @@ -270,7 +255,6 @@ public String getMspid() { */ public IdentitiesInfo getCreator() { return isFiltered() ? null : new IdentitiesInfo(headerDeserializer.getCreator()); - } /** @@ -280,7 +264,6 @@ public IdentitiesInfo getCreator() { */ public byte[] getNonce() { return isFiltered() ? null : headerDeserializer.getNonce(); - } /** @@ -289,7 +272,6 @@ public byte[] getNonce() { * @return the transaction id. */ public String getTransactionID() { - return BlockInfo.this.isFiltered() ? filteredTx.getTxid() : headerDeserializer.getChannelHeader().getTxId(); } @@ -297,9 +279,7 @@ public String getTransactionID() { * @return epoch and -1 if filtered block. * @deprecated */ - public long getEpoch() { - return BlockInfo.this.isFiltered() ? -1 : headerDeserializer.getChannelHeader().getEpoch(); } @@ -308,9 +288,7 @@ public long getEpoch() { * * @return timestamp and null if filtered block. */ - public Date getTimestamp() { - return BlockInfo.this.isFiltered() ? null : ProtoUtils.getDateFromTimestamp(headerDeserializer.getChannelHeader().getTimestamp()); } @@ -319,7 +297,7 @@ public Date getTimestamp() { * @return whether this Transaction is marked as TxValidationCode.VALID */ public boolean isValid() { - return BlockInfo.this.isFiltered() ? filteredTx.getTxValidationCode().getNumber() == FabricTransaction.TxValidationCode.VALID_VALUE + return BlockInfo.this.isFiltered() ? filteredTx.getTxValidationCode().getNumber() == TransactionPackage.TxValidationCode.VALID_VALUE : envelopeDeserializer.isValid(); } @@ -328,36 +306,26 @@ public boolean isValid() { */ public byte getValidationCode() { if (BlockInfo.this.isFiltered()) { - return (byte) filteredTx.getTxValidationCode().getNumber(); - } return envelopeDeserializer.validationCode(); } public EnvelopeType getType() { - final int type; - if (BlockInfo.this.isFiltered()) { - type = filteredTx.getTypeValue(); - } else { type = headerDeserializer.getChannelHeader().getType(); - } switch (type) { case Common.HeaderType.ENDORSER_TRANSACTION_VALUE: return EnvelopeType.TRANSACTION_ENVELOPE; - default: return EnvelopeType.ENVELOPE; } - } - } /** @@ -367,15 +335,11 @@ public EnvelopeType getType() { * @return envelopeIndex the index * @throws InvalidProtocolBufferException */ - public EnvelopeInfo getEnvelopeInfo(int envelopeIndex) throws InvalidProtocolBufferException { - try { - EnvelopeInfo ret; if (isFiltered()) { - switch (filteredBlock.getFilteredTransactions(envelopeIndex).getType().getNumber()) { case Common.HeaderType.ENDORSER_TRANSACTION_VALUE: ret = new TransactionEnvelopeInfo(this.filteredBlock.getFilteredTransactions(envelopeIndex)); @@ -384,11 +348,8 @@ public EnvelopeInfo getEnvelopeInfo(int envelopeIndex) throws InvalidProtocolBuf ret = new EnvelopeInfo(this.filteredBlock.getFilteredTransactions(envelopeIndex)); break; } - } else { - EnvelopeDeserializer ed = EnvelopeDeserializer.newInstance(block.getBlock().getData().getData(envelopeIndex), block.getTransActionsMetaData()[envelopeIndex]); - switch (ed.getType()) { case Common.HeaderType.ENDORSER_TRANSACTION_VALUE: ret = new TransactionEnvelopeInfo((EndorserTransactionEnvDeserializer) ed); @@ -396,16 +357,12 @@ public EnvelopeInfo getEnvelopeInfo(int envelopeIndex) throws InvalidProtocolBuf default: //just assume base properties. ret = new EnvelopeInfo(ed); break; - } - } return ret; - } catch (InvalidProtocolBufferRuntimeException e) { throw e.getCause(); } - } /** @@ -413,15 +370,12 @@ public EnvelopeInfo getEnvelopeInfo(int envelopeIndex) throws InvalidProtocolBuf * * @return */ - public Iterable getEnvelopeInfos() { - return new EnvelopeInfoIterable(); } public class TransactionEnvelopeInfo extends EnvelopeInfo { - - TransactionEnvelopeInfo(FilteredTransaction filteredTx) { + TransactionEnvelopeInfo(EventsPackage.FilteredTransaction filteredTx) { super(filteredTx); this.transactionDeserializer = null; } @@ -432,13 +386,11 @@ public class TransactionEnvelopeInfo extends EnvelopeInfo { * @return byte array that as the signature. */ public byte[] getSignature() { - return transactionDeserializer.getSignature(); } TransactionEnvelopeInfo(EndorserTransactionEnvDeserializer transactionDeserializer) { super(transactionDeserializer); - this.transactionDeserializer = transactionDeserializer; } @@ -453,31 +405,26 @@ public int getTransactionActionInfoCount() { } public Iterable getTransactionActionInfos() { - return new TransactionActionIterable(); } public class TransactionActionInfo { - private final TransactionActionDeserializer transactionAction; - private final PeerEvents.FilteredChaincodeAction filteredAction; + private final EventsPackage.FilteredChaincodeAction filteredAction; List endorserInfos = null; private boolean isFiltered() { return filteredAction != null; - } TransactionActionInfo(TransactionActionDeserializer transactionAction) { - this.transactionAction = transactionAction; filteredAction = null; } - TransactionActionInfo(PeerEvents.FilteredChaincodeAction filteredAction) { + TransactionActionInfo(EventsPackage.FilteredChaincodeAction filteredAction) { this.filteredAction = filteredAction; transactionAction = null; - } public byte[] getResponseMessageBytes() { @@ -536,7 +483,7 @@ public EndorserInfo getEndorsementInfo(int index) { if (null == endorserInfos) { endorserInfos = new ArrayList<>(); - for (Endorsement endorsement : transactionAction.getPayload().getAction() + for (ProposalResponsePackage.Endorsement endorsement : transactionAction.getPayload().getAction() .getChaincodeEndorsedAction().getEndorsementsList()) { endorserInfos.add(new EndorserInfo(endorsement)); @@ -544,7 +491,6 @@ public EndorserInfo getEndorsementInfo(int index) { } } return endorserInfos.get(index); - } public byte[] getProposalResponseMessageBytes() { @@ -553,23 +499,16 @@ public byte[] getProposalResponseMessageBytes() { } return transactionAction.getPayload().getAction().getProposalResponsePayload().getExtension().getResponseMessageBytes(); - } public byte[] getProposalResponsePayload() { if (isFiltered()) { return null; } - byte[] ret = null; ByteString retByteString = transactionAction.getPayload().getAction().getProposalResponsePayload(). getExtension().getResponsePayload(); - if (null != retByteString) { - - ret = retByteString.toByteArray(); - } - return ret; - + return null != retByteString ? retByteString.toByteArray() : null; } public int getProposalResponseStatus() { @@ -579,7 +518,6 @@ public int getProposalResponseStatus() { return transactionAction.getPayload().getAction().getProposalResponsePayload(). getExtension().getResponseStatus(); - } /** @@ -591,17 +529,11 @@ public String getChaincodeIDName() { if (isFiltered()) { return null; } - String name = null; Chaincode.ChaincodeID ccid = transactionAction.getPayload().getAction().getProposalResponsePayload(). getExtension().getChaincodeID(); - if (ccid != null) { - name = ccid.getName(); - } - - return name; - + return ccid != null ? ccid.getName() : null; } /** @@ -613,17 +545,11 @@ public String getChaincodeIDPath() { if (isFiltered()) { return null; } - String path = null; Chaincode.ChaincodeID ccid = transactionAction.getPayload().getAction().getProposalResponsePayload(). getExtension().getChaincodeID(); - if (ccid != null) { - path = ccid.getPath(); - } - - return path; - + return ccid != null ? ccid.getPath() : null; } /** @@ -631,22 +557,15 @@ public String getChaincodeIDPath() { * * @return version of chaincode. Maybe null if no chaincode or if block is filtered. */ - public String getChaincodeIDVersion() { if (isFiltered()) { return null; } - String version = null; Chaincode.ChaincodeID ccid = transactionAction.getPayload().getAction().getProposalResponsePayload(). getExtension().getChaincodeID(); - if (ccid != null) { - version = ccid.getVersion(); - } - - return version; - + return ccid != null ? ccid.getVersion() : null; } /** @@ -655,23 +574,13 @@ public String getChaincodeIDVersion() { * * @return Read write set. */ - public TxReadWriteSetInfo getTxReadWriteSet() { - if (BlockInfo.this.isFiltered()) { return null; - - } else { - - TxReadWriteSet txReadWriteSet = transactionAction.getPayload().getAction().getProposalResponsePayload() - .getExtension().getResults(); - if (txReadWriteSet == null) { - return null; - } - - return new TxReadWriteSetInfo(txReadWriteSet); } - + TxReadWriteSet txReadWriteSet = transactionAction.getPayload().getAction().getProposalResponsePayload() + .getExtension().getResults(); + return txReadWriteSet != null ? new TxReadWriteSetInfo(txReadWriteSet) : null; } /** @@ -679,18 +588,15 @@ public TxReadWriteSetInfo getTxReadWriteSet() { * * @return A chaincode event if the chaincode set an event otherwise null. */ - public ChaincodeEvent getEvent() { if (isFiltered()) { - final PeerEvents.FilteredChaincodeAction chaincodeActions = filteredAction; + final EventsPackage.FilteredChaincodeAction chaincodeActions = filteredAction; return new ChaincodeEvent(chaincodeActions.getChaincodeEvent().toByteString()); } return transactionAction.getPayload().getAction().getProposalResponsePayload() .getExtension().getEvent(); - } - } public TransactionActionInfo getTransactionActionInfo(int index) { @@ -704,18 +610,15 @@ public class TransactionActionInfoIterator implements Iterator= max) { throw new ArrayIndexOutOfBoundsException(format("Current index: %d. Max index: %d", ci, max)); } @@ -727,7 +630,6 @@ public TransactionActionInfo next() { } public class TransactionActionIterable implements Iterable { - @Override public Iterator iterator() { return new TransactionActionInfoIterator(); @@ -741,18 +643,15 @@ class EnvelopeInfoIterator implements Iterator { EnvelopeInfoIterator() { max = isFiltered() ? filteredBlock.getFilteredTransactionsCount() : block.getData().getDataCount(); - } @Override public boolean hasNext() { return ci < max; - } @Override public EnvelopeInfo next() { - if (ci >= max) { throw new ArrayIndexOutOfBoundsException(format("Current index: %d. Max index: %d", ci, max)); } @@ -762,12 +661,10 @@ public EnvelopeInfo next() { } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - } } class EnvelopeInfoIterable implements Iterable { - @Override public Iterator iterator() { return new EnvelopeInfoIterator(); @@ -775,10 +672,9 @@ public Iterator iterator() { } public static class EndorserInfo { - private final Endorsement endorsement; - - EndorserInfo(Endorsement endorsement) { + private final ProposalResponsePackage.Endorsement endorsement; + EndorserInfo(ProposalResponsePackage.Endorsement endorsement) { this.endorsement = endorsement; } @@ -795,13 +691,11 @@ public byte[] getEndorser() { } public String getId() { - try { return Identities.SerializedIdentity.parseFrom(endorsement.getEndorser()).getIdBytes().toStringUtf8(); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - } public String getMspid() { @@ -811,16 +705,10 @@ public String getMspid() { throw new InvalidProtocolBufferRuntimeException(e); } } - } public enum EnvelopeType { - TRANSACTION_ENVELOPE, ENVELOPE - } - } - - diff --git a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeActionDeserializer.java b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeActionDeserializer.java index a84c753f..984af155 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeActionDeserializer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeActionDeserializer.java @@ -22,92 +22,69 @@ import com.google.protobuf.InvalidProtocolBufferException; import org.hyperledger.fabric.protos.ledger.rwset.Rwset.TxReadWriteSet; import org.hyperledger.fabric.protos.peer.Chaincode; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; -import static org.hyperledger.fabric.protos.peer.FabricProposal.ChaincodeAction; - class ChaincodeActionDeserializer { private final ByteString byteString; - private WeakReference chaincodeAction; + private WeakReference chaincodeAction; ChaincodeActionDeserializer(ByteString byteString) { this.byteString = byteString; } - ChaincodeAction getChaincodeAction() { - ChaincodeAction ret = null; - - if (chaincodeAction != null) { - ret = chaincodeAction.get(); - - } - if (ret == null) { + ProposalPackage.ChaincodeAction getChaincodeAction() { + ProposalPackage.ChaincodeAction ret = chaincodeAction != null ? chaincodeAction.get() : null; + if (null == ret) { try { - ret = ChaincodeAction.parseFrom(byteString); + ret = ProposalPackage.ChaincodeAction.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } chaincodeAction = new WeakReference<>(ret); - } return ret; - } Chaincode.ChaincodeID getChaincodeID() { - Chaincode.ChaincodeID ret = null; - - ChaincodeAction chaincodeAction = getChaincodeAction(); - if (chaincodeAction.hasChaincodeId()) { - ret = chaincodeAction.getChaincodeId(); - } - return ret; - + ProposalPackage.ChaincodeAction chaincodeAction = getChaincodeAction(); + return chaincodeAction.hasChaincodeId() ? chaincodeAction.getChaincodeId() : null; } ChaincodeEvent getEvent() { - - ChaincodeAction ca = getChaincodeAction(); + ProposalPackage.ChaincodeAction ca = getChaincodeAction(); ByteString eventsBytes = ca.getEvents(); if (eventsBytes == null || eventsBytes.isEmpty()) { return null; } return new ChaincodeEvent(eventsBytes); - } TxReadWriteSet getResults() { - try { return TxReadWriteSet.parseFrom(getChaincodeAction().getResults()); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - } String getResponseMessage() { return getChaincodeAction().getResponse().getMessage(); - } byte[] getResponseMessageBytes() { return getChaincodeAction().getResponse().getMessageBytes().toByteArray(); - } int getResponseStatus() { return getChaincodeAction().getResponse().getStatus(); - } ByteString getResponsePayload() { return getChaincodeAction().getResponse().getPayload(); - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeActionPayloadDeserializer.java b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeActionPayloadDeserializer.java index 8f8a3b9f..0473d3ec 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeActionPayloadDeserializer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeActionPayloadDeserializer.java @@ -20,12 +20,12 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import org.hyperledger.fabric.protos.peer.FabricTransaction.ChaincodeActionPayload; +import org.hyperledger.fabric.protos.peer.TransactionPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; class ChaincodeActionPayloadDeserializer { private final ByteString byteString; - private WeakReference chaincodeActionPayload; + private WeakReference chaincodeActionPayload; private WeakReference chaincodeEndorsedActionDeserializer; private WeakReference chaincodeProposalPayloadDeserializer; @@ -33,66 +33,40 @@ class ChaincodeActionPayloadDeserializer { this.byteString = byteString; } - ChaincodeActionPayload getChaincodeActionPayload() { - ChaincodeActionPayload ret = null; - - if (chaincodeActionPayload != null) { - ret = chaincodeActionPayload.get(); - - } - if (ret == null) { + TransactionPackage.ChaincodeActionPayload getChaincodeActionPayload() { + TransactionPackage.ChaincodeActionPayload ret = chaincodeActionPayload != null ? chaincodeActionPayload.get() : null; + if (null == ret) { try { - ret = ChaincodeActionPayload.parseFrom(byteString); + ret = TransactionPackage.ChaincodeActionPayload.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - chaincodeActionPayload = new WeakReference<>(ret); - } return ret; - } ChaincodeEndorsedActionDeserializer getAction() { - ChaincodeEndorsedActionDeserializer ret = null; - - if (chaincodeEndorsedActionDeserializer != null) { - ret = chaincodeEndorsedActionDeserializer.get(); - - } - if (ret == null) { + ChaincodeEndorsedActionDeserializer ret = chaincodeEndorsedActionDeserializer != null ? chaincodeEndorsedActionDeserializer.get() : null; + if (null == ret) { ret = new ChaincodeEndorsedActionDeserializer(getChaincodeActionPayload().getAction()); - chaincodeEndorsedActionDeserializer = new WeakReference<>(ret); - } return ret; - } ChaincodeProposalPayloadDeserializer getChaincodeProposalPayload() { + ChaincodeProposalPayloadDeserializer ret = chaincodeProposalPayloadDeserializer != null ? chaincodeProposalPayloadDeserializer.get() : null; - ChaincodeProposalPayloadDeserializer ret = null; - - if (chaincodeProposalPayloadDeserializer != null) { - ret = chaincodeProposalPayloadDeserializer.get(); - - } - if (ret == null) { - + if (null == ret) { ret = new ChaincodeProposalPayloadDeserializer(getChaincodeActionPayload().getChaincodeProposalPayload()); - chaincodeProposalPayloadDeserializer = new WeakReference<>(ret); - } return ret; - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeEndorsedActionDeserializer.java b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeEndorsedActionDeserializer.java index 77d98269..79df965c 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeEndorsedActionDeserializer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeEndorsedActionDeserializer.java @@ -21,77 +21,56 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; +import org.hyperledger.fabric.protos.peer.TransactionPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; -import static org.hyperledger.fabric.protos.peer.FabricTransaction.ChaincodeEndorsedAction; - class ChaincodeEndorsedActionDeserializer { private final ByteString byteString; - private WeakReference chaincodeEndorsedAction; + private WeakReference chaincodeEndorsedAction; private WeakReference proposalResponsePayload; - ChaincodeEndorsedActionDeserializer(ChaincodeEndorsedAction action) { + ChaincodeEndorsedActionDeserializer(TransactionPackage.ChaincodeEndorsedAction action) { byteString = action.toByteString(); chaincodeEndorsedAction = new WeakReference<>(action); } - ChaincodeEndorsedAction getChaincodeEndorsedAction() { - ChaincodeEndorsedAction ret = null; - - if (chaincodeEndorsedAction != null) { - ret = chaincodeEndorsedAction.get(); - - } - if (ret == null) { + TransactionPackage.ChaincodeEndorsedAction getChaincodeEndorsedAction() { + TransactionPackage.ChaincodeEndorsedAction ret = chaincodeEndorsedAction != null ? chaincodeEndorsedAction.get() : null; + if (null == ret) { try { - ret = ChaincodeEndorsedAction.parseFrom(byteString); + ret = TransactionPackage.ChaincodeEndorsedAction.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - chaincodeEndorsedAction = new WeakReference<>(ret); } return ret; - } int getEndorsementsCount() { - return getChaincodeEndorsedAction().getEndorsementsCount(); - } - List getEndorsements() { - + List getEndorsements() { return getChaincodeEndorsedAction().getEndorsementsList(); } byte[] getEndorsementSignature(int index) { - return getChaincodeEndorsedAction().getEndorsements(index).getSignature().toByteArray(); } ProposalResponsePayloadDeserializer getProposalResponsePayload() { + ProposalResponsePayloadDeserializer ret = proposalResponsePayload != null ? proposalResponsePayload.get() : null; - ProposalResponsePayloadDeserializer ret = null; - - if (proposalResponsePayload != null) { - ret = proposalResponsePayload.get(); - - } - if (ret == null) { - + if (null == ret) { ret = new ProposalResponsePayloadDeserializer(getChaincodeEndorsedAction().getProposalResponsePayload()); proposalResponsePayload = new WeakReference<>(ret); - } return ret; - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeEvent.java b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeEvent.java index c2374715..a7e5e164 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeEvent.java +++ b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeEvent.java @@ -20,7 +20,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import org.hyperledger.fabric.protos.peer.ChaincodeEventOuterClass; +import org.hyperledger.fabric.protos.peer.ChaincodeEventPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; /** @@ -28,34 +28,25 @@ */ public class ChaincodeEvent { private final ByteString byteString; - private WeakReference chaincodeEvent; + private WeakReference chaincodeEvent; ChaincodeEvent(ByteString byteString) { this.byteString = byteString; } - ChaincodeEventOuterClass.ChaincodeEvent getChaincodeEvent() { - ChaincodeEventOuterClass.ChaincodeEvent ret = null; - - if (chaincodeEvent != null) { - ret = chaincodeEvent.get(); - - } - if (ret == null) { + ChaincodeEventPackage.ChaincodeEvent getChaincodeEvent() { + ChaincodeEventPackage.ChaincodeEvent ret = chaincodeEvent != null ? chaincodeEvent.get() : null; + if (null == ret) { try { - ret = ChaincodeEventOuterClass.ChaincodeEvent.parseFrom(byteString); - + ret = ChaincodeEventPackage.ChaincodeEvent.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - chaincodeEvent = new WeakReference<>(ret); - } return ret; - } /** @@ -64,9 +55,7 @@ ChaincodeEventOuterClass.ChaincodeEvent getChaincodeEvent() { * @return Return name; */ public String getEventName() { - return getChaincodeEvent().getEventName(); - } /** @@ -75,9 +64,7 @@ public String getEventName() { * @return The identifier */ public String getChaincodeId() { - return getChaincodeEvent().getChaincodeId(); - } /** @@ -86,9 +73,7 @@ public String getChaincodeId() { * @return The transactions id. */ public String getTxId() { - return getChaincodeEvent().getTxId(); - } /** @@ -97,14 +82,11 @@ public String getTxId() { * @return binary data set by the chaincode for this event. This may return null. */ public byte[] getPayload() { - ByteString ret = getChaincodeEvent().getPayload(); if (null == ret) { return null; } return ret.toByteArray(); - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeProposalPayloadDeserializer.java b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeProposalPayloadDeserializer.java index 80d865b1..1ec60f79 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/ChaincodeProposalPayloadDeserializer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/ChaincodeProposalPayloadDeserializer.java @@ -20,59 +20,41 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; -import static org.hyperledger.fabric.protos.peer.FabricProposal.ChaincodeProposalPayload; - class ChaincodeProposalPayloadDeserializer { private final ByteString byteString; - private WeakReference chaincodeProposalPayload; + private WeakReference chaincodeProposalPayload; private WeakReference invocationSpecDeserializer; ChaincodeProposalPayloadDeserializer(ByteString byteString) { this.byteString = byteString; } - ChaincodeProposalPayload getChaincodeProposalPayload() { - ChaincodeProposalPayload ret = null; - - if (chaincodeProposalPayload != null) { - ret = chaincodeProposalPayload.get(); - - } - if (ret == null) { + ProposalPackage.ChaincodeProposalPayload getChaincodeProposalPayload() { + ProposalPackage.ChaincodeProposalPayload ret = chaincodeProposalPayload != null ? chaincodeProposalPayload.get() : null; + if (null == ret) { try { - ret = ChaincodeProposalPayload.parseFrom(byteString); + ret = ProposalPackage.ChaincodeProposalPayload.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - chaincodeProposalPayload = new WeakReference<>(ret); - } return ret; - } ChaincodeInvocationSpecDeserializer getChaincodeInvocationSpec() { - ChaincodeInvocationSpecDeserializer ret = null; - - if (invocationSpecDeserializer != null) { - ret = invocationSpecDeserializer.get(); - - } - if (ret == null) { + ChaincodeInvocationSpecDeserializer ret = invocationSpecDeserializer != null ? invocationSpecDeserializer.get() : null; + if (null == ret) { ret = new ChaincodeInvocationSpecDeserializer(getChaincodeProposalPayload().getInput()); - invocationSpecDeserializer = new WeakReference<>(ret); - } return ret; - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/Channel.java b/src/main/java/org/hyperledger/fabric/sdk/Channel.java index 9d3248b9..56e70576 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/Channel.java +++ b/src/main/java/org/hyperledger/fabric/sdk/Channel.java @@ -80,7 +80,7 @@ import org.hyperledger.fabric.protos.common.Configtx.ConfigValue; import org.hyperledger.fabric.protos.common.Ledger; import org.hyperledger.fabric.protos.discovery.Protocol; -import org.hyperledger.fabric.protos.msp.MspConfig; +import org.hyperledger.fabric.protos.msp.MspConfigPackage; import org.hyperledger.fabric.protos.orderer.Ab; import org.hyperledger.fabric.protos.orderer.Ab.BroadcastResponse; import org.hyperledger.fabric.protos.orderer.Ab.DeliverResponse; @@ -88,15 +88,10 @@ import org.hyperledger.fabric.protos.orderer.Ab.SeekPosition; import org.hyperledger.fabric.protos.orderer.Ab.SeekSpecified; import org.hyperledger.fabric.protos.peer.Configuration; -import org.hyperledger.fabric.protos.peer.FabricProposal; -import org.hyperledger.fabric.protos.peer.FabricProposal.SignedProposal; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse.Response; -import org.hyperledger.fabric.protos.peer.FabricTransaction.ProcessedTransaction; +import org.hyperledger.fabric.protos.peer.ProposalPackage; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.protos.peer.Query; -import org.hyperledger.fabric.protos.peer.Query.ChaincodeInfo; -import org.hyperledger.fabric.protos.peer.Query.ChaincodeQueryResponse; -import org.hyperledger.fabric.protos.peer.Query.ChannelQueryResponse; +import org.hyperledger.fabric.protos.peer.TransactionPackage; import org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent; import org.hyperledger.fabric.sdk.Peer.PeerRole; import org.hyperledger.fabric.sdk.ServiceDiscovery.SDChaindcode; @@ -869,13 +864,13 @@ public Channel joinPeer(Orderer orderer, Peer peer, PeerOptions peerOptions) thr TransactionContext transactionContext = systemChannel.getTransactionContext(); - FabricProposal.Proposal joinProposal = JoinPeerProposalBuilder.newBuilder() + ProposalPackage.Proposal joinProposal = JoinPeerProposalBuilder.newBuilder() .context(transactionContext) .genesisBlock(genesisBlock) .build(); logger.debug("Getting signed proposal."); - SignedProposal signedProposal = getSignedProposal(transactionContext, joinProposal); + ProposalPackage.SignedProposal signedProposal = getSignedProposal(transactionContext, joinProposal); logger.debug("Got signed proposal."); addPeer(peer, peerOptions); //need to add peer. @@ -923,12 +918,12 @@ private Block getConfigBlock(TransactionContext transactionContext, List p throw new ProposalException("No peers go get config block"); } - SignedProposal signedProposal = null; + ProposalPackage.SignedProposal signedProposal = null; try { transactionContext.verify(false); // can't verify till we get the config block. - FabricProposal.Proposal proposal = GetConfigBlockBuilder.newBuilder() + ProposalPackage.Proposal proposal = GetConfigBlockBuilder.newBuilder() .context(transactionContext) .channelId(name) .build(); @@ -1987,10 +1982,10 @@ private Map traverseConfigGroupsMSP(String name, ConfigGroup config if (null != mspv) { if (!msps.containsKey(name)) { - MspConfig.MSPConfig mspConfig = MspConfig.MSPConfig.parseFrom(mspv.getValue()); + MspConfigPackage.MSPConfig mspConfig = MspConfigPackage.MSPConfig.parseFrom(mspv.getValue()); Integer type = mspConfig.getType(); if (type == 0) { - MspConfig.FabricMSPConfig fabricMSPConfig = MspConfig.FabricMSPConfig.parseFrom(mspConfig.getConfig()); + MspConfigPackage.FabricMSPConfig fabricMSPConfig = MspConfigPackage.FabricMSPConfig.parseFrom(mspConfig.getConfig()); msps.put(name, new MSP(name, fabricMSPConfig)); } @@ -2792,8 +2787,8 @@ public Collection sendInstantiationProposal(InstantiateProposa instantiateProposalbuilder.chaincodeCollectionConfiguration(instantiateProposalRequest.getChaincodeCollectionConfiguration()); instantiateProposalbuilder.setTransientMap(instantiateProposalRequest.getTransientMap()); - FabricProposal.Proposal instantiateProposal = instantiateProposalbuilder.build(); - SignedProposal signedProposal = getSignedProposal(transactionContext, instantiateProposal); + ProposalPackage.Proposal instantiateProposal = instantiateProposalbuilder.build(); + ProposalPackage.SignedProposal signedProposal = getSignedProposal(transactionContext, instantiateProposal); return sendProposalToPeers(peers, signedProposal, transactionContext); } catch (Exception e) { @@ -2873,8 +2868,8 @@ Collection sendInstallProposal(InstallProposalRequest installP installProposalbuilder.setChaincodeInputStream(installProposalRequest.getChaincodeInputStream()); installProposalbuilder.setChaincodeMetaInfLocation(installProposalRequest.getChaincodeMetaInfLocation()); - FabricProposal.Proposal deploymentProposal = installProposalbuilder.build(); - SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); + ProposalPackage.Proposal deploymentProposal = installProposalbuilder.build(); + ProposalPackage.SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); return sendProposalToPeers(peers, signedProposal, transactionContext); } catch (Exception e) { @@ -2933,7 +2928,7 @@ public Collection sendUpgradeProposal(UpgradeProposalRequest u upgradeProposalBuilder.chaincodEndorsementPolicy(upgradeProposalRequest.getChaincodeEndorsementPolicy()); upgradeProposalBuilder.chaincodeCollectionConfiguration(upgradeProposalRequest.getChaincodeCollectionConfiguration()); - SignedProposal signedProposal = getSignedProposal(transactionContext, upgradeProposalBuilder.build()); + ProposalPackage.SignedProposal signedProposal = getSignedProposal(transactionContext, upgradeProposalBuilder.build()); return sendProposalToPeers(peers, signedProposal, transactionContext); } catch (Exception e) { @@ -2941,10 +2936,10 @@ public Collection sendUpgradeProposal(UpgradeProposalRequest u } } - private SignedProposal getSignedProposal(TransactionContext transactionContext, FabricProposal.Proposal proposal) throws CryptoException, InvalidArgumentException { + private ProposalPackage.SignedProposal getSignedProposal(TransactionContext transactionContext, ProposalPackage.Proposal proposal) throws CryptoException, InvalidArgumentException { - SignedProposal sp; - sp = SignedProposal.newBuilder() + ProposalPackage.SignedProposal sp; + sp = ProposalPackage.SignedProposal.newBuilder() .setProposalBytes(proposal.toByteString()) .setSignature(transactionContext.signByteString(proposal.toByteArray())) .build(); @@ -3572,7 +3567,7 @@ public TransactionInfo queryTransactionByID(Collection peers, String txID, ProposalResponse proposalResponse = sendProposalSerially(querySCCRequest, peers); - return new TransactionInfo(txID, ProcessedTransaction.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload())); + return new TransactionInfo(txID, TransactionPackage.ProcessedTransaction.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload())); } catch (Exception e) { logger.error(e); @@ -3596,9 +3591,9 @@ Set queryChannels(Peer peer) throws InvalidArgumentException, ProposalEx TransactionContext context = getTransactionContext(); - FabricProposal.Proposal q = QueryPeerChannelsBuilder.newBuilder().context(context).build(); + ProposalPackage.Proposal q = QueryPeerChannelsBuilder.newBuilder().context(context).build(); - SignedProposal qProposal = getSignedProposal(context, q); + ProposalPackage.SignedProposal qProposal = getSignedProposal(context, q); Collection proposalResponses = sendProposalToPeers(Collections.singletonList(peer), qProposal, context); if (null == proposalResponses) { @@ -3616,13 +3611,13 @@ Set queryChannels(Peer peer) throws InvalidArgumentException, ProposalEx } - FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); + ProposalResponsePackage.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); if (null == fabricResponse) { throw new ProposalException(format("Peer %s channel query return with empty fabric response", peer.getName())); } - final Response fabricResponseResponse = fabricResponse.getResponse(); + final ProposalResponsePackage.Response fabricResponseResponse = fabricResponse.getResponse(); if (null == fabricResponseResponse) { //not likely but check it. throw new ProposalException(format("Peer %s channel query return with empty fabricResponseResponse", peer.getName())); @@ -3634,7 +3629,7 @@ Set queryChannels(Peer peer) throws InvalidArgumentException, ProposalEx } - ChannelQueryResponse qr = ChannelQueryResponse.parseFrom(fabricResponseResponse.getPayload()); + Query.ChannelQueryResponse qr = Query.ChannelQueryResponse.parseFrom(fabricResponseResponse.getPayload()); Set ret = new HashSet<>(qr.getChannelsCount()); @@ -3653,7 +3648,7 @@ Set queryChannels(Peer peer) throws InvalidArgumentException, ProposalEx } - List queryInstalledChaincodes(Peer peer) throws InvalidArgumentException, ProposalException { + List queryInstalledChaincodes(Peer peer) throws InvalidArgumentException, ProposalException { checkPeer(peer); @@ -3665,9 +3660,9 @@ List queryInstalledChaincodes(Peer peer) throws InvalidArgumentEx TransactionContext context = getTransactionContext(); - FabricProposal.Proposal q = QueryInstalledChaincodesBuilder.newBuilder().context(context).build(); + ProposalPackage.Proposal q = QueryInstalledChaincodesBuilder.newBuilder().context(context).build(); - SignedProposal qProposal = getSignedProposal(context, q); + ProposalPackage.SignedProposal qProposal = getSignedProposal(context, q); Collection proposalResponses = sendProposalToPeers(Collections.singletonList(peer), qProposal, context); if (null == proposalResponses) { @@ -3681,13 +3676,13 @@ List queryInstalledChaincodes(Peer peer) throws InvalidArgumentEx ProposalResponse proposalResponse = proposalResponses.iterator().next(); - FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); + ProposalResponsePackage.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); if (null == fabricResponse) { throw new ProposalException(format("Peer %s channel query return with empty fabric response", peer.getName())); } - final Response fabricResponseResponse = fabricResponse.getResponse(); + final ProposalResponsePackage.Response fabricResponseResponse = fabricResponse.getResponse(); if (null == fabricResponseResponse) { //not likely but check it. throw new ProposalException(format("Peer %s channel query return with empty fabricResponseResponse", peer.getName())); @@ -3699,7 +3694,7 @@ List queryInstalledChaincodes(Peer peer) throws InvalidArgumentEx } - ChaincodeQueryResponse chaincodeQueryResponse = ChaincodeQueryResponse.parseFrom(fabricResponseResponse.getPayload()); + Query.ChaincodeQueryResponse chaincodeQueryResponse = Query.ChaincodeQueryResponse.parseFrom(fabricResponseResponse.getPayload()); return chaincodeQueryResponse.getChaincodesList(); @@ -3740,8 +3735,8 @@ Collection sendLifecycleInstallPropos LifecycleInstallProposalBuilder installProposalbuilder = LifecycleInstallProposalBuilder.newBuilder(); installProposalbuilder.setChaincodeBytes(chaincodeBytes); installProposalbuilder.context(transactionContext); - FabricProposal.Proposal deploymentProposal = installProposalbuilder.build(); - SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); + ProposalPackage.Proposal deploymentProposal = installProposalbuilder.build(); + ProposalPackage.SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); return sendProposalToPeers(peers, signedProposal, transactionContext, LifecycleInstallChaincodeProposalResponse.class); } catch (Exception e) { @@ -3852,8 +3847,8 @@ public Collection s approveChaincodeDefinitionForMyOrgProposalBuilder.chaincodeCollectionConfiguration(chaincodeCollectionConfiguration.getCollectionConfigPackage()); } - FabricProposal.Proposal deploymentProposal = approveChaincodeDefinitionForMyOrgProposalBuilder.build(); - SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); + ProposalPackage.Proposal deploymentProposal = approveChaincodeDefinitionForMyOrgProposalBuilder.build(); + ProposalPackage.SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); return sendProposalToPeers(peers, signedProposal, transactionContext, LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse.class); } catch (Exception e) { @@ -3942,8 +3937,8 @@ public Collection sendLifecy commitChaincodeDefinitionProposalBuilder.chaincodeCollectionConfiguration(chaincodeCollectionConfiguration.getCollectionConfigPackage()); } - FabricProposal.Proposal deploymentProposal = commitChaincodeDefinitionProposalBuilder.build(); - SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); + ProposalPackage.Proposal deploymentProposal = commitChaincodeDefinitionProposalBuilder.build(); + ProposalPackage.SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); return sendProposalToPeers(peers, signedProposal, transactionContext, LifecycleCommitChaincodeDefinitionProposalResponse.class); } catch (Exception e) { @@ -3969,9 +3964,9 @@ Collection lifecycleQueryInst TransactionContext context = getTransactionContext(lifecycleQueryInstalledChaincodesRequest); - FabricProposal.Proposal proposalBuilder = LifecycleQueryInstalledChaincodesBuilder.newBuilder().context(context).build(); + ProposalPackage.Proposal proposalBuilder = LifecycleQueryInstalledChaincodesBuilder.newBuilder().context(context).build(); - SignedProposal qProposal = getSignedProposal(context, proposalBuilder); + ProposalPackage.SignedProposal qProposal = getSignedProposal(context, proposalBuilder); return sendProposalToPeers(peers, qProposal, context, LifecycleQueryInstalledChaincodesProposalResponse.class); @@ -4008,7 +4003,7 @@ Collection lifecycleQueryInsta lifecycleQueryInstalledChaincodeBuilder.setPackageId(lifecycleQueryInstalledChaincodeRequest.getPackageId()); lifecycleQueryInstalledChaincodeBuilder.context(context); - SignedProposal qProposal = getSignedProposal(context, lifecycleQueryInstalledChaincodeBuilder.build()); + ProposalPackage.SignedProposal qProposal = getSignedProposal(context, lifecycleQueryInstalledChaincodeBuilder.build()); return sendProposalToPeers(peers, qProposal, context, LifecycleQueryInstalledChaincodeProposalResponse.class); } catch (ProposalException e) { @@ -4043,7 +4038,7 @@ public Collection lifecycleQ TransactionContext context = getTransactionContext(proposalRequest); LifecycleQueryChaincodeDefinitionsBuilder proposalBuilder = LifecycleQueryChaincodeDefinitionsBuilder.newBuilder(); proposalBuilder.context(context); - SignedProposal proposal = getSignedProposal(context, proposalBuilder.build()); + ProposalPackage.SignedProposal proposal = getSignedProposal(context, proposalBuilder.build()); return sendProposalToPeers(peers, proposal, context, LifecycleQueryChaincodeDefinitionsProposalResponse.class); } catch (Exception e) { @@ -4133,7 +4128,7 @@ public Collection sendLifecycleCh lifecycleCheckCommitReadinessBuilder.context(context); - SignedProposal qProposal = getSignedProposal(context, lifecycleCheckCommitReadinessBuilder.build()); + ProposalPackage.SignedProposal qProposal = getSignedProposal(context, lifecycleCheckCommitReadinessBuilder.build()); return sendProposalToPeers(peers, qProposal, context, LifecycleCheckCommitReadinessProposalResponse.class); } catch (Exception e) { @@ -4169,7 +4164,7 @@ public Collection lifecycleQu LifecycleQueryChaincodeDefinitionBuilder lifecycleQueryChaincodeDefinitionBuilder = LifecycleQueryChaincodeDefinitionBuilder.newBuilder(); lifecycleQueryChaincodeDefinitionBuilder.context(context).setChaincodeName(queryLifecycleQueryChaincodeDefinitionRequest.getChaincodeName()); - SignedProposal qProposal = getSignedProposal(context, lifecycleQueryChaincodeDefinitionBuilder.build()); + ProposalPackage.SignedProposal qProposal = getSignedProposal(context, lifecycleQueryChaincodeDefinitionBuilder.build()); return sendProposalToPeers(peers, qProposal, context, LifecycleQueryChaincodeDefinitionProposalResponse.class); } catch (ProposalException e) { @@ -4187,12 +4182,12 @@ public Collection lifecycleQu * This method may not be thread safe if client context is changed! * * @param peer The peer to query. - * @return A list of ChaincodeInfo @see {@link ChaincodeInfo} + * @return A list of ChaincodeInfo @see {@link Query.ChaincodeInfo} * @throws InvalidArgumentException * @throws ProposalException */ - public List queryInstantiatedChaincodes(Peer peer) throws InvalidArgumentException, ProposalException { + public List queryInstantiatedChaincodes(Peer peer) throws InvalidArgumentException, ProposalException { return queryInstantiatedChaincodes(peer, client.getUserContext()); } @@ -4202,12 +4197,12 @@ public List queryInstantiatedChaincodes(Peer peer) throws Invalid * * @param peer The peer to query. * @param userContext the user context. - * @return A list of ChaincodeInfo @see {@link ChaincodeInfo} + * @return A list of ChaincodeInfo @see {@link Query.ChaincodeInfo} * @throws InvalidArgumentException * @throws ProposalException */ - public List queryInstantiatedChaincodes(Peer peer, User userContext) throws InvalidArgumentException, ProposalException { + public List queryInstantiatedChaincodes(Peer peer, User userContext) throws InvalidArgumentException, ProposalException { checkChannelState(); checkPeer(peer); @@ -4217,9 +4212,9 @@ public List queryInstantiatedChaincodes(Peer peer, User userConte TransactionContext context = getTransactionContext(userContext); - FabricProposal.Proposal q = QueryInstantiatedChaincodesBuilder.newBuilder().context(context).build(); + ProposalPackage.Proposal q = QueryInstantiatedChaincodesBuilder.newBuilder().context(context).build(); - SignedProposal qProposal = getSignedProposal(context, q); + ProposalPackage.SignedProposal qProposal = getSignedProposal(context, q); Collection proposalResponses = sendProposalToPeers(Collections.singletonList(peer), qProposal, context); if (null == proposalResponses) { @@ -4233,13 +4228,13 @@ public List queryInstantiatedChaincodes(Peer peer, User userConte ProposalResponse proposalResponse = proposalResponses.iterator().next(); - FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); + ProposalResponsePackage.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); if (null == fabricResponse) { throw new ProposalException(format("Peer %s channel query return with empty fabric response", peer.getName())); } - final Response fabricResponseResponse = fabricResponse.getResponse(); + final ProposalResponsePackage.Response fabricResponseResponse = fabricResponse.getResponse(); if (null == fabricResponseResponse) { //not likely but check it. throw new ProposalException(format("Peer %s channel query return with empty fabricResponseResponse", peer.getName())); @@ -4251,7 +4246,7 @@ public List queryInstantiatedChaincodes(Peer peer, User userConte } - ChaincodeQueryResponse chaincodeQueryResponse = ChaincodeQueryResponse.parseFrom(fabricResponseResponse.getPayload()); + Query.ChaincodeQueryResponse chaincodeQueryResponse = Query.ChaincodeQueryResponse.parseFrom(fabricResponseResponse.getPayload()); return chaincodeQueryResponse.getChaincodesList(); @@ -4291,9 +4286,9 @@ public CollectionConfigPackage queryCollectionsConfig(String chaincodeName, Peer QueryCollectionsConfigBuilder queryCollectionsConfigBuilder = QueryCollectionsConfigBuilder.newBuilder() .context(context).chaincodeName(chaincodeName); - FabricProposal.Proposal q = queryCollectionsConfigBuilder.build(); + ProposalPackage.Proposal q = queryCollectionsConfigBuilder.build(); - SignedProposal qProposal = getSignedProposal(context, q); + ProposalPackage.SignedProposal qProposal = getSignedProposal(context, q); Collection proposalResponses = sendProposalToPeers(Collections.singletonList(peer), qProposal, context); if (null == proposalResponses) { @@ -4307,13 +4302,13 @@ public CollectionConfigPackage queryCollectionsConfig(String chaincodeName, Peer ProposalResponse proposalResponse = proposalResponses.iterator().next(); - FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); + ProposalResponsePackage.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); if (null == fabricResponse) { throw new ProposalException(format("Peer %s channel query return with empty fabric response", peer.getName())); } - final Response fabricResponseResponse = fabricResponse.getResponse(); + final ProposalResponsePackage.Response fabricResponseResponse = fabricResponse.getResponse(); if (null == fabricResponseResponse) { //not likely but check it. throw new ProposalException(format("Peer %s channel query return with empty fabricResponseResponse", peer.getName())); @@ -4403,7 +4398,7 @@ public Collection sendTransactionProposalToEndorsers(Transacti proposalBuilder.context(transactionContext); proposalBuilder.request(transactionProposalRequest); - SignedProposal invokeProposal = null; + ProposalPackage.SignedProposal invokeProposal = null; try { invokeProposal = getSignedProposal(transactionContext, proposalBuilder.build()); } catch (CryptoException e) { @@ -4792,7 +4787,7 @@ private Collection sendProposal(TransactionRequest proposalReq proposalBuilder.context(transactionContext); proposalBuilder.request(proposalRequest); - SignedProposal invokeProposal = getSignedProposal(transactionContext, proposalBuilder.build()); + ProposalPackage.SignedProposal invokeProposal = getSignedProposal(transactionContext, proposalBuilder.build()); return sendProposalToPeers(peers, invokeProposal, transactionContext); } catch (ProposalException e) { throw e; @@ -4814,7 +4809,7 @@ public ServiceDiscovery.EndorsementSelector setSDEndorserSelector(ServiceDiscove } private Collection sendProposalToPeers(Collection peers, - SignedProposal signedProposal, + ProposalPackage.SignedProposal signedProposal, TransactionContext transactionContext) throws InvalidArgumentException, ProposalException { return sendProposalToPeers(peers, @@ -4824,7 +4819,7 @@ private Collection sendProposalToPeers(Collection peers, } private Collection sendProposalToPeers(Collection peers, - SignedProposal signedProposal, + ProposalPackage.SignedProposal signedProposal, TransactionContext transactionContext, Class clazz) throws InvalidArgumentException, ProposalException { checkPeers(peers); @@ -4848,9 +4843,9 @@ private Collection sendProposalToPeers(Collectio class Pair { private final Peer peer; - private final Future future; + private final Future future; - private Pair(Peer peer, Future future) { + private Pair(Peer peer, Future future) { this.peer = peer; this.future = future; } @@ -4863,25 +4858,21 @@ private Pair(Peer peer, Future future) if (null != diagnosticFileDumper) { logger.trace(format("Sending to channel %s, peer: %s, proposal: %s, txID: %s", name, peer, txID, diagnosticFileDumper.createDiagnosticProtobufFile(signedProposal.toByteArray()))); - } - Future proposalResponseListenableFuture; + Future proposalResponseListenableFuture; try { proposalResponseListenableFuture = peer.sendProposalAsync(signedProposal); } catch (Exception e) { proposalResponseListenableFuture = new CompletableFuture<>(); ((CompletableFuture) proposalResponseListenableFuture).completeExceptionally(e); - } peerFuturePairs.add(new Pair(peer, proposalResponseListenableFuture)); - } Collection proposalResponses = new ArrayList<>(); for (Pair peerFuturePair : peerFuturePairs) { - - FabricProposalResponse.ProposalResponse fabricResponse = null; + ProposalResponsePackage.ProposalResponse fabricResponse = null; String message; int status = 500; final String peerName = peerFuturePair.peer.toString(); @@ -4952,9 +4943,7 @@ private Pair(Peer peer, Future future) * @return a future allowing access to the result of the transaction invocation once complete. */ public CompletableFuture sendTransaction(Collection proposalResponses, User userContext) { - return sendTransaction(proposalResponses, getOrderers(), userContext); - } /** @@ -4964,9 +4953,7 @@ public CompletableFuture sendTransaction(Collection sendTransaction(Collection proposalResponses) { - return sendTransaction(proposalResponses, getOrderers()); - } /** @@ -4978,7 +4965,6 @@ public CompletableFuture sendTransaction(Collection sendTransaction(Collection proposalResponses, Collection orderers) { - return sendTransaction(proposalResponses, orderers, client.getUserContext()); } @@ -4995,14 +4981,10 @@ public CompletableFuture sendTransaction(Collection * NofEvents may also contain other NofEvent grouping. They can be nested. */ - public static class NOfEvents { - public NOfEvents setN(int n) { if (n < 1) { - throw new IllegalArgumentException(format("N was %d but needs to be greater than 0. ", n)); - } this.n = n; return this; @@ -5022,7 +5004,6 @@ public NOfEvents setN(int n) { * @param peers The peers that need to see the transaction event to complete. * @return This NofEvents. */ - public NOfEvents addPeers(Peer... peers) { if (peers == null || peers.length == 0) { throw new IllegalArgumentException("Peers added must be not null or empty."); @@ -5030,7 +5011,6 @@ public NOfEvents addPeers(Peer... peers) { this.peers.addAll(Arrays.asList(peers)); return this; - } /** @@ -5087,14 +5067,12 @@ private boolean inHayStack(NOfEvents needle) { * @param nofs The nested event group that need to set the transacton event to complete. * @return This NofEvents. */ - public NOfEvents addNOfs(Collection nofs) { addNOfs(nofs.toArray(new NOfEvents[nofs.size()])); return this; } synchronized Collection unSeenPeers() { - Set unseen = new HashSet<>(16); unseen.addAll(peers); for (NOfEvents nOfEvents : nOfEvents) { @@ -5109,14 +5087,12 @@ synchronized boolean seen(Peer peer) { n = Long.min(peers.size() + nOfEvents.size(), n); } if (!ready) { - if (peers.remove(peer)) { if (--n == 0) { ready = true; } } if (!ready) { - for (Iterator ni = nOfEvents.iterator(); ni.hasNext(); ) { // for check style NOfEvents e = ni.next(); @@ -5132,7 +5108,6 @@ synchronized boolean seen(Peer peer) { } } if (ready) { - peers.clear(); nOfEvents.clear(); } @@ -5154,9 +5129,7 @@ synchronized boolean seen(Peer peer) { } } - private NOfEvents() { - - } + private NOfEvents() { } public static NOfEvents createNofEvents() { return new NOfEvents(); @@ -5166,7 +5139,6 @@ public static NOfEvents createNofEvents() { * Special NofEvents indicating that no transaction events are needed to complete the Future. * This will result in the Future being completed as soon has the Orderer has seen the transaction. */ - public static NOfEvents nofNoEvents = new NOfEvents() { @Override public NOfEvents addNOfs(NOfEvents... nOfEvents) { @@ -5195,9 +5167,7 @@ public NOfEvents addPeers(Collection peers) { public static NOfEvents createNoEvents() { return nofNoEvents; - } - } /** @@ -5209,7 +5179,6 @@ public static NOfEvents createNoEvents() { * @param orderers * @return Future allowing access to the result of the transaction invocation. */ - public CompletableFuture sendTransaction(Collection proposalResponses, Collection orderers, User userContext) { return sendTransaction(proposalResponses, createTransactionOptions().orderers(orderers).userContext(userContext)); } @@ -5217,7 +5186,6 @@ public CompletableFuture sendTransaction(Collection orderers; boolean shuffleOrders = true; @@ -5309,7 +5277,6 @@ public TransactionOptions orderers(Collection orderers) { * Additional metadata used by service discovery to find the endorsements needed. * Specify which chaincode is invoked and what collections are used. */ - public static class ServiceDiscoveryChaincodeCalls { String name; List collections; @@ -5324,7 +5291,6 @@ public static class ServiceDiscoveryChaincodeCalls { * @param collectionName name of collection. * @return */ - public ServiceDiscoveryChaincodeCalls addCollections(String... collectionName) { if (collections == null) { collections = new LinkedList<>(); @@ -5334,7 +5300,6 @@ public ServiceDiscoveryChaincodeCalls addCollections(String... collectionName) { } String write(List dep) { - StringBuilder cns = new StringBuilder(1000); cns.append("ServiceDiscoveryChaincodeCalls(name: ").append(name); @@ -5360,12 +5325,10 @@ String write(List dep) { } cns.append("]"); - } cns.append(")"); return cns.toString(); - } /** @@ -5375,7 +5338,6 @@ String write(List dep) { * @return * @throws InvalidArgumentException */ - public static ServiceDiscoveryChaincodeCalls createServiceDiscoveryChaincodeCalls(String name) throws InvalidArgumentException { if (isNullOrEmpty(name)) { throw new InvalidArgumentException("The name parameter must be non null nor an empty string."); @@ -5386,9 +5348,7 @@ public static ServiceDiscoveryChaincodeCalls createServiceDiscoveryChaincodeCall private Protocol.ChaincodeCall ret = null; Protocol.ChaincodeCall build() { - if (ret == null) { - final Protocol.ChaincodeCall.Builder builder = Protocol.ChaincodeCall.newBuilder().setName(name); if (collections != null && !collections.isEmpty()) { builder.addAllCollectionNames(collections); @@ -5397,7 +5357,6 @@ Protocol.ChaincodeCall build() { } return ret; - } String getName() { @@ -5469,7 +5428,6 @@ public DiscoveryOptions setEndorsementSelector(ServiceDiscovery.EndorsementSelec * @param serviceDiscoveryChaincodeInterests * @return DiscoveryOptions */ - public DiscoveryOptions setServiceDiscoveryChaincodeInterests(ServiceDiscoveryChaincodeCalls... serviceDiscoveryChaincodeInterests) { if (this.serviceDiscoveryChaincodeInterests == null) { @@ -5485,7 +5443,6 @@ public DiscoveryOptions setServiceDiscoveryChaincodeInterests(ServiceDiscoveryCh * @param forceDiscovery * @return */ - public DiscoveryOptions setForceDiscovery(boolean forceDiscovery) { this.forceDiscovery = forceDiscovery; return this; @@ -5506,9 +5463,7 @@ public DiscoveryOptions ignoreEndpoints(String... endpoints) throws InvalidArgum Collection getIgnoreList() { return ignoreList; - } - } /** @@ -5520,11 +5475,9 @@ Collection getIgnoreList() { * @param transactionOptions * @return Future allowing access to the result of the transaction invocation. */ - public CompletableFuture sendTransaction(Collection proposalResponses, TransactionOptions transactionOptions) { try { - if (null == transactionOptions) { throw new InvalidArgumentException("Parameter transactionOptions can't be null"); } @@ -5554,13 +5507,11 @@ public CompletableFuture sendTransaction(Collection ed = new LinkedList<>(); - FabricProposal.Proposal proposal = null; + List ed = new LinkedList<>(); + ProposalPackage.Proposal proposal = null; ByteString proposalResponsePayload = null; String proposalTransactionID = null; TransactionContext transactionContext = null; @@ -5615,7 +5566,6 @@ public CompletableFuture sendTransaction(Collection eventingPeers = getEventingPeers(); @@ -5626,7 +5576,6 @@ public CompletableFuture sendTransaction(Collection sendTransaction(Collection sendTransaction(Collection sendTransaction(Collection sendTransaction(Collection future = new CompletableFuture<>(); future.completeExceptionally(e); return future; - } - } /** @@ -5726,7 +5668,6 @@ public CompletableFuture sendTransaction(Collection blockEventQueue) throws InvalidArgumentException { - if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } @@ -5846,11 +5765,8 @@ public String registerBlockListener(BlockingQueue blockEventQu } String handle = new BL(blockEventQueue, -1L, null).getHandle(); - logger.trace(format("Register QueuedBlockEvent listener %s", handle)); - return handle; - } /** @@ -5862,9 +5778,7 @@ public String registerBlockListener(BlockingQueue blockEventQu * @return return a handle to ungregister the handler. * @throws InvalidArgumentException */ - public String registerBlockListener(BlockingQueue blockEventQueue, long timeout, TimeUnit timeUnit) throws InvalidArgumentException { - if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } @@ -5882,11 +5796,8 @@ public String registerBlockListener(BlockingQueue blockEventQu } String handle = new BL(blockEventQueue, timeout, timeUnit).getHandle(); - logger.trace(format("Register QueuedBlockEvent listener %s", handle)); - return handle; - } /** @@ -5897,7 +5808,6 @@ public String registerBlockListener(BlockingQueue blockEventQu * @throws InvalidArgumentException if the channel is shutdown or invalid arguments. */ public boolean unregisterBlockListener(String handle) throws InvalidArgumentException { - if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } @@ -5911,14 +5821,11 @@ public boolean unregisterBlockListener(String handle) throws InvalidArgumentExce } synchronized (lblockListeners) { - return null != lblockListeners.remove(handle); - } } public Collection getBlockListenerHandles() throws InvalidArgumentException { - if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } @@ -5929,7 +5836,6 @@ public Collection getBlockListenerHandles() throws InvalidArgumentExcept } synchronized (lblockListeners) { - Set ret = new HashSet<>(lblockListeners.keySet()); // remove the SDKs own transaction block listener. final String ltransactionListenerProcessorHandle = transactionListenerProcessorHandle; @@ -5943,7 +5849,6 @@ public Collection getBlockListenerHandles() throws InvalidArgumentExcept ////////// Transaction monitoring ///////////////////////////// private void startEventQue() { - if (eventQueueThread != null) { return; } @@ -5968,7 +5873,6 @@ private void startEventQue() { if (!shutdown) { logger.error(e); } - continue; } if (blockEvent == null) { @@ -5977,7 +5881,6 @@ private void startEventQue() { } try { - final String blockchainID = blockEvent.getChannelId(); final String from = format("Channel %s eventqueue got block event with block number: %d for channel: %s, from %s", @@ -6002,19 +5905,14 @@ private void startEventQue() { if (l.listener != null) { client.getExecutorService().execute(() -> l.listener.received(blockEvent)); } else if (l.blockingQueue != null) { - if (l.timeout < 0 || l.timeUnit == null) { - l.blockingQueue.put(new QueuedBlockEvent(l.handle, blockEvent)); - } else { - if (!l.blockingQueue.offer(new QueuedBlockEvent(l.handle, blockEvent), l.timeout, l.timeUnit)) { logger.warn(format("Error calling block listener %s on channel: %s event: %s could not be added in time %d %s ", l.handle, name, from, l.timeout, l.timeUnit)); } } - } } catch (Throwable e) { //Don't let one register stop rest. logger.error(format("Error calling block listener %s on channel: %s event: %s ", l.handle, name, from), e); @@ -6029,7 +5927,6 @@ private void startEventQue() { logger.info(format("Channel %s eventThread shutting down. shutdown: %b thread: %s ", name, shutdown, Thread.currentThread().getName())); }); - } /** @@ -6037,7 +5934,6 @@ private void startEventQue() { * * @return */ - private String registerTransactionListenerProcessor() throws InvalidArgumentException { logger.debug(format("Channel %s registerTransactionListenerProcessor starting", name)); @@ -6057,30 +5953,23 @@ private String registerTransactionListenerProcessor() throws InvalidArgumentExce final Iterable transactionEvents = blockEvent.getTransactionEvents(); if (transactionEvents == null || !transactionEvents.iterator().hasNext()) { - // no transactions today we can assume it was a config or update block. - if (isLaterBlock(blockEvent.getBlockNumber())) { ServiceDiscovery lserviceDiscovery = serviceDiscovery; if (null != lserviceDiscovery) { client.getExecutorService().execute(() -> lserviceDiscovery.fullNetworkDiscovery(true)); } - } else { - lclient.getExecutorService().execute(() -> { try { if (!shutdown) { loadCACertificates(true); } - } catch (Exception e) { logger.warn(format("Channel %s failed to load certificates for an update", name), e); } - }); - } return; @@ -6091,7 +5980,6 @@ private String registerTransactionListenerProcessor() throws InvalidArgumentExce } for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) { - logger.debug(format("Channel %s got event from %s for transaction %s in block number: %d", name, source, transactionEvent.getTransactionID(), blockEvent.getBlockNumber())); @@ -6113,7 +6001,6 @@ private String registerTransactionListenerProcessor() throws InvalidArgumentExce if (l.eventReceived(transactionEvent)) { l.fire(transactionEvent); } - } catch (Throwable e) { logger.error(e); // Don't let one register stop rest. } @@ -6133,13 +6020,11 @@ private synchronized boolean isLaterBlock(final long blockno) { } void runSweeper() { - if (shutdown || DELTA_SWEEP < 1) { return; } if (sweeper == null) { - sweeperExecutorService = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); @@ -6147,16 +6032,10 @@ void runSweeper() { }); sweeper = sweeperExecutorService.scheduleAtFixedRate(() -> { try { - if (txListeners != null) { - synchronized (txListeners) { - - for (Iterator>> it = txListeners.entrySet().iterator(); it.hasNext(); - ) { - + for (Iterator>> it = txListeners.entrySet().iterator(); it.hasNext();) { Map.Entry> es = it.next(); - LinkedList tlLinkedList = es.getValue(); tlLinkedList.removeIf(TL::sweepMe); if (tlLinkedList.isEmpty()) { @@ -6168,10 +6047,8 @@ void runSweeper() { } catch (Exception e) { logger.warn("Sweeper got error:" + e.getMessage(), e); } - }, 0, DELTA_SWEEP, TimeUnit.MILLISECONDS); } - } /** @@ -6181,15 +6058,10 @@ void runSweeper() { * @param nOfEvents * @return */ - private CompletableFuture registerTxListener(String txid, NOfEvents nOfEvents, boolean failFast) { - CompletableFuture future = new CompletableFuture<>(); - new TL(txid, future, nOfEvents, failFast); - return future; - } /** @@ -6198,12 +6070,9 @@ private CompletableFuture registerTxListener(String txid, NOfE * @param txid */ private void unregisterTxListener(String txid) { - synchronized (txListeners) { - txListeners.remove(txid); } - } /** @@ -6216,9 +6085,7 @@ private void unregisterTxListener(String txid) { * @return Handle to be used to unregister the event listener {@link #unregisterChaincodeEventListener(String)} * @throws InvalidArgumentException */ - public String registerChaincodeEventListener(Pattern chaincodeId, Pattern eventName, ChaincodeEventListener chaincodeEventListener) throws InvalidArgumentException { - if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } @@ -6242,7 +6109,6 @@ public String registerChaincodeEventListener(Pattern chaincodeId, Pattern eventN } } return chaincodeEventListenerEntry.handle; - } /** @@ -6252,7 +6118,6 @@ public String registerChaincodeEventListener(Pattern chaincodeId, Pattern eventN * @return True if the chaincode handler was found and removed. * @throws InvalidArgumentException */ - public boolean unregisterChaincodeEventListener(String handle) throws InvalidArgumentException { boolean ret; @@ -6264,19 +6129,16 @@ public boolean unregisterChaincodeEventListener(String handle) throws InvalidArg synchronized (chainCodeListeners) { ret = null != chainCodeListeners.remove(handle); - } synchronized (this) { if (null != blh && chainCodeListeners.isEmpty()) { - unregisterBlockListener(blh); blh = null; } } return ret; - } //////////////////////////////////////////////////////////////////////// @@ -6288,7 +6150,6 @@ private String registerChaincodeListenerProcessor() throws InvalidArgumentExcept // Chaincode event listener is internal Block listener for chaincode events. return registerBlockListener(blockEvent -> { - if (chainCodeListeners.isEmpty()) { return; } @@ -6296,24 +6157,18 @@ private String registerChaincodeListenerProcessor() throws InvalidArgumentExcept LinkedList chaincodeEvents = new LinkedList<>(); //Find the chaincode events in the transactions. - for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) { - logger.debug(format("Channel %s got event for transaction %s ", name, transactionEvent.getTransactionID())); for (BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo info : transactionEvent.getTransactionActionInfos()) { - ChaincodeEvent event = info.getEvent(); if (null != event) { chaincodeEvents.add(event); } - } - } if (!chaincodeEvents.isEmpty()) { - class MatchPair { final ChaincodeEventListenerEntry eventListener; final ChaincodeEvent event; @@ -6327,32 +6182,22 @@ class MatchPair { List matches = new LinkedList<>(); //Find matches. synchronized (chainCodeListeners) { - for (ChaincodeEventListenerEntry chaincodeEventListenerEntry : chainCodeListeners.values()) { - for (ChaincodeEvent chaincodeEvent : chaincodeEvents) { - if (chaincodeEventListenerEntry.isMatch(chaincodeEvent)) { - matches.add(new MatchPair(chaincodeEventListenerEntry, chaincodeEvent)); } - } - } } //fire events for (MatchPair match : matches) { - ChaincodeEventListenerEntry chaincodeEventListenerEntry = match.eventListener; ChaincodeEvent ce = match.event; chaincodeEventListenerEntry.fire(blockEvent, ce); - } - } - }); } @@ -6361,9 +6206,7 @@ class MatchPair { * * @param force force immediate shutdown. */ - public synchronized void shutdown(boolean force) { - if (shutdown) { return; } @@ -6371,7 +6214,6 @@ public synchronized void shutdown(boolean force) { String ltransactionListenerProcessorHandle = transactionListenerProcessorHandle; transactionListenerProcessorHandle = null; if (null != ltransactionListenerProcessorHandle) { - try { unregisterBlockListener(ltransactionListenerProcessorHandle); } catch (Exception e) { @@ -6382,7 +6224,6 @@ public synchronized void shutdown(boolean force) { String lchaincodeEventUpgradeListenerHandle = chaincodeEventUpgradeListenerHandle; chaincodeEventUpgradeListenerHandle = null; if (null != lchaincodeEventUpgradeListenerHandle) { - try { unregisterChaincodeEventListener(lchaincodeEventUpgradeListenerHandle); } catch (Exception e) { @@ -6401,7 +6242,6 @@ public synchronized void shutdown(boolean force) { if (chainCodeListeners != null) { chainCodeListeners.clear(); - } if (blockListeners != null) { @@ -6415,7 +6255,6 @@ public synchronized void shutdown(boolean force) { client = null; for (Peer peer : new ArrayList<>(getPeers())) { - try { removePeerInternal(peer); peer.shutdown(force); @@ -6468,16 +6307,13 @@ public synchronized void shutdown(boolean force) { * @throws IOException * @throws InvalidArgumentException */ - public void serializeChannel(File file) throws IOException, InvalidArgumentException { - if (null == file) { throw new InvalidArgumentException("File parameter may not be null"); } Files.write(Paths.get(file.getAbsolutePath()), serializeChannel(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); - } /** @@ -6488,7 +6324,6 @@ public void serializeChannel(File file) throws IOException, InvalidArgumentExcep * @throws IOException */ public byte[] serializeChannel() throws IOException, InvalidArgumentException { - if (isShutdown()) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", getName())); } @@ -6510,14 +6345,12 @@ public byte[] serializeChannel() throws IOException, InvalidArgumentException { } } } - } @Override protected void finalize() throws Throwable { shutdown(true); super.finalize(); - } /** @@ -6539,11 +6372,9 @@ public String toString() { sb.append("PeerOptions( " + format("newest: %s, startEvents: %s, stopEvents: %s, registerEventsForFilteredBlocks: %s", "" + newest, "" + startEvents, "" + stopEvents, registerEventsForFilteredBlocks)); if (peerRoles != null && !peerRoles.isEmpty()) { - sb.append(", PeerRoles:["); String sep = ""; - for (PeerRole peerRole : peerRoles) { sb.append(sep).append(peerRole.getPropertyName()); sep = " ,"; @@ -6568,7 +6399,6 @@ public boolean isRegisterEventsForFilteredBlocks() { * * @return the PeerOptions instance. */ - public PeerOptions registerEventsForFilteredBlocks() { registerEventsForFilteredBlocks = true; return this; @@ -6579,7 +6409,6 @@ public PeerOptions registerEventsForFilteredBlocks() { * * @return the PeerOptions instance. */ - public PeerOptions registerEventsForBlocks() { registerEventsForFilteredBlocks = false; return this; @@ -6599,7 +6428,6 @@ public Boolean getNewest() { * * @return the start number */ - public Long getStartEvents() { return startEvents; } @@ -6609,21 +6437,17 @@ public Long getStartEvents() { * * @return the stop block number. */ - public Long getStopEvents() { return stopEvents; } - protected PeerOptions() { - - } + protected PeerOptions() { } /** * Create an instance of PeerOptions. * * @return the PeerOptions instance. */ - public static PeerOptions createPeerOptions() { return new PeerOptions(); } @@ -6633,7 +6457,6 @@ public static PeerOptions createPeerOptions() { * * @return the roles {@link PeerRole} */ - public EnumSet getPeerRoles() { if (peerRoles == null) { peerRoles = EnumSet.complementOf(EnumSet.of(PeerRole.SERVICE_DISCOVERY)); @@ -6647,7 +6470,6 @@ public EnumSet getPeerRoles() { * @param peerRoles {@link PeerRole} * @return This PeerOptions. */ - public PeerOptions setPeerRoles(EnumSet peerRoles) { this.peerRoles = peerRoles; return this; @@ -6659,9 +6481,7 @@ public PeerOptions setPeerRoles(EnumSet peerRoles) { * @param peerRole see {@link PeerRole} * @return This PeerOptions. */ - public PeerOptions addPeerRole(PeerRole peerRole) { - if (peerRoles == null) { peerRoles = EnumSet.noneOf(PeerRole.class); @@ -6689,7 +6509,6 @@ public PeerOptions startEvents(long start) { * * @return This PeerOptions. */ - public PeerOptions startEventsNewest() { startEvents = null; newest = true; @@ -6713,30 +6532,26 @@ public PeerOptions stopEvents(long stop) { * * @return return a duplicate of this instance. */ - public PeerOptions clone() { try { return (PeerOptions) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } - } - } /** * MSPs */ - class MSP { final String orgName; - final MspConfig.FabricMSPConfig fabricMSPConfig; + final MspConfigPackage.FabricMSPConfig fabricMSPConfig; byte[][] adminCerts; byte[][] rootCerts; byte[][] intermediateCerts; - MSP(String orgName, MspConfig.FabricMSPConfig fabricMSPConfig) { + MSP(String orgName, MspConfigPackage.FabricMSPConfig fabricMSPConfig) { this.orgName = orgName; this.fabricMSPConfig = fabricMSPConfig; } @@ -6746,10 +6561,8 @@ class MSP { * * @return */ - String getID() { return fabricMSPConfig.getName(); - } /** @@ -6758,7 +6571,6 @@ String getID() { * @return array of admin certs in PEM bytes format. */ byte[][] getAdminCerts() { - if (null == adminCerts) { adminCerts = new byte[fabricMSPConfig.getAdminsList().size()][]; int i = 0; @@ -6775,7 +6587,6 @@ byte[][] getAdminCerts() { * @return array of admin certs in PEM bytes format. */ byte[][] getRootCerts() { - if (null == rootCerts) { rootCerts = new byte[fabricMSPConfig.getRootCertsList().size()][]; int i = 0; @@ -6793,7 +6604,6 @@ byte[][] getRootCerts() { * @return array of intermediate certs in PEM bytes format. */ byte[][] getIntermediateCerts() { - if (null == intermediateCerts) { intermediateCerts = new byte[fabricMSPConfig.getIntermediateCertsList().size()][]; int i = 0; @@ -6803,11 +6613,9 @@ byte[][] getIntermediateCerts() { } return intermediateCerts; } - } class ChannelEventQue { - private final BlockingQueue events = new LinkedBlockingQueue<>(); //Thread safe private Throwable eventException; @@ -6823,13 +6631,11 @@ boolean addBEvent(BlockEvent event) { events.add(event); return true; - } BlockEvent getNextEvent() throws EventingException { if (shutdown) { throw new EventingException(format("Channel %s has been shutdown", name)); - } BlockEvent ret = null; if (eventException != null) { @@ -6840,11 +6646,9 @@ BlockEvent getNextEvent() throws EventingException { } catch (InterruptedException e) { if (shutdown) { throw new EventingException(format("channel %s is shutdown", name), e); - } else { logger.warn(e); if (eventException != null) { - EventingException eve = new EventingException(e); logger.error(eve.getMessage(), eve); throw eve; @@ -6857,18 +6661,14 @@ BlockEvent getNextEvent() throws EventingException { } if (shutdown) { - throw new EventingException(format("Channel %s has been shutdown.", name)); - } return ret; } - } class BL { - final BlockListener listener; final String handle; private final BlockingQueue blockingQueue; @@ -6880,19 +6680,15 @@ class BL { logger.debug(format("Channel %s blockListener %s starting", name, handle)); synchronized (blockListeners) { - blockListeners.put(handle, this); - } } BL(BlockListener listener) { - this.listener = listener; blockingQueue = null; timeout = Long.MAX_VALUE; timeUnit = null; - } BL(BlockingQueue blockingQueue, long timeout, TimeUnit timeUnit) { @@ -6900,7 +6696,6 @@ class BL { this.timeout = timeout; this.timeUnit = timeUnit; listener = null; - } public String getHandle() { @@ -6969,11 +6764,9 @@ private void addListener() { } boolean sweepMe() { // Sweeps DO NOT fire future. user needs to put timeout on their futures for timeouts. - final boolean ret = sweepTime < System.currentTimeMillis() || fired.get() || future.isDone(); if (IS_WARN_LEVEL && ret) { - StringBuilder sb = new StringBuilder(10000); String sep = "Non reporting peers: "; @@ -6990,11 +6783,9 @@ boolean sweepMe() { // Sweeps DO NOT fire future. user needs to put timeout on t } return ret; - } void fire(BlockEvent.TransactionEvent transactionEvent) { - if (fired.getAndSet(true)) { return; } @@ -7027,11 +6818,9 @@ void fire(BlockEvent.TransactionEvent transactionEvent) { transactionEvent))); } } - } private class ChaincodeEventListenerEntry { - private final Pattern chaincodeIdPattern; private final Pattern eventNamePattern; private final ChaincodeEventListener chaincodeEventListener; @@ -7044,23 +6833,16 @@ private class ChaincodeEventListenerEntry { this.handle = CHAINCODE_EVENTS_TAG + Utils.generateUUID() + CHAINCODE_EVENTS_TAG; synchronized (chainCodeListeners) { - chainCodeListeners.put(handle, this); - } } boolean isMatch(ChaincodeEvent chaincodeEvent) { - return chaincodeIdPattern.matcher(chaincodeEvent.getChaincodeId()).matches() && eventNamePattern.matcher(chaincodeEvent.getEventName()).matches(); - } void fire(BlockEvent blockEvent, ChaincodeEvent ce) { - client.getExecutorService().execute(() -> chaincodeEventListener.received(handle, blockEvent, ce)); - } } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/EndorserClient.java b/src/main/java/org/hyperledger/fabric/sdk/EndorserClient.java index 1919d3c8..2c3b72f7 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/EndorserClient.java +++ b/src/main/java/org/hyperledger/fabric/sdk/EndorserClient.java @@ -26,8 +26,8 @@ import org.hyperledger.fabric.protos.discovery.DiscoveryGrpc; import org.hyperledger.fabric.protos.discovery.Protocol; import org.hyperledger.fabric.protos.peer.EndorserGrpc; -import org.hyperledger.fabric.protos.peer.FabricProposal; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalPackage; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.sdk.exception.PeerException; import org.hyperledger.fabric.sdk.helper.Config; @@ -112,14 +112,14 @@ synchronized void shutdown(boolean force) { } } - public CompletableFuture sendProposalAsync(FabricProposal.SignedProposal proposal) { + public CompletableFuture sendProposalAsync(ProposalPackage.SignedProposal proposal) { if (shutdown) { - CompletableFuture ret = new CompletableFuture<>(); + CompletableFuture ret = new CompletableFuture<>(); ret.completeExceptionally(new PeerException("Shutdown " + toString())); return ret; } - CompletableFuture future = CompletableFuturesExtra.toCompletableFuture(futureStub.processProposal(proposal)); + CompletableFuture future = CompletableFuturesExtra.toCompletableFuture(futureStub.processProposal(proposal)); return future.exceptionally(throwable -> { throw new CompletionException(format("%s %s", toString, throwable.getMessage()), throwable); diff --git a/src/main/java/org/hyperledger/fabric/sdk/EnvelopeDeserializer.java b/src/main/java/org/hyperledger/fabric/sdk/EnvelopeDeserializer.java index 6f2d9088..7f314a8a 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/EnvelopeDeserializer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/EnvelopeDeserializer.java @@ -23,7 +23,7 @@ import org.hyperledger.fabric.protos.common.Common.ChannelHeader; import org.hyperledger.fabric.protos.common.Common.Envelope; import org.hyperledger.fabric.protos.common.Common.Payload; -import org.hyperledger.fabric.protos.peer.FabricTransaction; +import org.hyperledger.fabric.protos.peer.TransactionPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; class EnvelopeDeserializer { @@ -34,52 +34,37 @@ class EnvelopeDeserializer { EnvelopeDeserializer(ByteString byteString, byte validcode) { this.byteString = byteString; - this.validcode = validcode; } Envelope getEnvelope() { - Envelope ret = null; - - if (envelope != null) { - ret = envelope.get(); + Envelope ret = envelope != null ? envelope.get() : null; - } if (ret == null) { - try { ret = Envelope.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - envelope = new WeakReference<>(ret); - } return ret; - } byte[] getSignature() { - return getEnvelope().getSignature().toByteArray(); - } PayloadDeserializer getPayload() { - PayloadDeserializer ret = null; if (payload != null) { ret = payload.get(); - } if (ret == null) { - ret = new PayloadDeserializer(getEnvelope().getPayload()); payload = new WeakReference<>(ret); - } return ret; @@ -89,9 +74,7 @@ PayloadDeserializer getPayload() { int getType() { if (type == null) { - type = getPayload().getHeader().getChannelHeader().getType(); - } return type; } @@ -100,27 +83,21 @@ int getType() { * @return whether this Transaction is marked as TxValidationCode.VALID */ public boolean isValid() { - - return validcode == FabricTransaction.TxValidationCode.VALID_VALUE; + return validcode == TransactionPackage.TxValidationCode.VALID_VALUE; } /** * @return the validation code of this Transaction (enumeration TxValidationCode in Transaction.proto) */ public byte validationCode() { - return validcode; } static EnvelopeDeserializer newInstance(ByteString byteString, byte b) throws InvalidProtocolBufferException { - EnvelopeDeserializer ret; - final int type = ChannelHeader.parseFrom(Payload.parseFrom(Envelope.parseFrom(byteString).getPayload()) .getHeader().getChannelHeader()).getType(); - /* - MESSAGE = 0; // Used for messages which are signed but opaque CONFIG = 1; // Used for messages which express the channel config CONFIG_UPDATE = 2; // Used for transactions which update the channel config @@ -128,7 +105,6 @@ static EnvelopeDeserializer newInstance(ByteString byteString, byte b) throws In ORDERER_TRANSACTION = 4; // Used internally by the orderer for management DELIVER_SEEK_INFO = 5; // Used as the type for Envelope messages submitted to instruct the Deliver API to seek CHAINCODE_PACKAGE = 6; // Used for packaging chaincode artifacts for install - */ switch (type) { @@ -140,7 +116,5 @@ static EnvelopeDeserializer newInstance(ByteString byteString, byte b) throws In break; } return ret; - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/LifecycleCheckCommitReadinessProposalResponse.java b/src/main/java/org/hyperledger/fabric/sdk/LifecycleCheckCommitReadinessProposalResponse.java index ae147f4a..c205d703 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/LifecycleCheckCommitReadinessProposalResponse.java +++ b/src/main/java/org/hyperledger/fabric/sdk/LifecycleCheckCommitReadinessProposalResponse.java @@ -9,13 +9,12 @@ package org.hyperledger.fabric.sdk; import java.util.Collections; -import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import com.google.protobuf.ByteString; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.ProposalException; import org.hyperledger.fabric.sdk.transaction.TransactionContext; @@ -38,7 +37,7 @@ public Lifecycle.CheckCommitReadinessResult getApprovalStatusResults() throws Pr throw new ProposalException(format("Fabric response failed on peer %s %s", getPeer(), getMessage())); } - FabricProposalResponse.ProposalResponse fabricResponse = getProposalResponse(); + ProposalResponsePackage.ProposalResponse fabricResponse = getProposalResponse(); if (null == fabricResponse) { throw new ProposalException(format("Proposal has no Fabric response. %s", getPeer())); } diff --git a/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryChaincodeDefinitionProposalResponse.java b/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryChaincodeDefinitionProposalResponse.java index 9a2d28ac..90088a78 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryChaincodeDefinitionProposalResponse.java +++ b/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryChaincodeDefinitionProposalResponse.java @@ -10,7 +10,7 @@ import com.google.protobuf.ByteString; import org.hyperledger.fabric.protos.common.Collection; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -30,23 +30,17 @@ public class LifecycleQueryChaincodeDefinitionProposalResponse extends ProposalR } private Lifecycle.QueryChaincodeDefinitionResult parsePayload() throws ProposalException { - if (null == queryChaincodeDefinitionResult) { - if (getStatus() != Status.SUCCESS) { throw new ProposalException(format("Fabric response failed on peer %s %s", getPeer(), getMessage())); } - FabricProposalResponse.ProposalResponse fabricResponse = getProposalResponse(); - - // getChaincodeActionResponsePayload() - + ProposalResponsePackage.ProposalResponse fabricResponse = getProposalResponse(); if (null == fabricResponse) { throw new ProposalException("Proposal has no Fabric response."); } ByteString payload = fabricResponse.getPayload(); - if (payload == null) { throw new ProposalException("Fabric response has no payload"); } @@ -60,7 +54,6 @@ private Lifecycle.QueryChaincodeDefinitionResult parsePayload() throws ProposalE } catch (Exception e) { throw new ProposalException(format("Failure on peer %s %s", getPeer(), e.getMessage()), e); } - } return queryChaincodeDefinitionResult; @@ -73,7 +66,6 @@ private Lifecycle.QueryChaincodeDefinitionResult parsePayload() throws ProposalE * @throws ProposalException */ public byte[] getValidationParameter() throws ProposalException { - ByteString payloadBytes = parsePayload().getValidationParameter(); if (null == payloadBytes) { return null; diff --git a/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryChaincodeDefinitionsProposalResponse.java b/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryChaincodeDefinitionsProposalResponse.java index 6dc75aaf..5afb090d 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryChaincodeDefinitionsProposalResponse.java +++ b/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryChaincodeDefinitionsProposalResponse.java @@ -11,11 +11,10 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Set; import java.util.stream.Collectors; import com.google.protobuf.ByteString; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.ProposalException; import org.hyperledger.fabric.sdk.transaction.TransactionContext; @@ -35,7 +34,7 @@ private Lifecycle.QueryChaincodeDefinitionsResult getPayload() throws ProposalEx throw new ProposalException(format("Fabric response failed on peer %s %s", getPeer(), getMessage())); } - FabricProposalResponse.ProposalResponse fabricResponse = getProposalResponse(); + ProposalResponsePackage.ProposalResponse fabricResponse = getProposalResponse(); if (null == fabricResponse) { throw new ProposalException(format("Proposal has no Fabric response. %s", getPeer())); } diff --git a/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryInstalledChaincodeProposalResponse.java b/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryInstalledChaincodeProposalResponse.java index b1879d94..cbf7498c 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryInstalledChaincodeProposalResponse.java +++ b/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryInstalledChaincodeProposalResponse.java @@ -11,7 +11,7 @@ import java.nio.file.Path; import com.google.protobuf.ByteString; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.ProposalException; import org.hyperledger.fabric.sdk.transaction.TransactionContext; @@ -29,16 +29,12 @@ public class LifecycleQueryInstalledChaincodeProposalResponse extends ProposalRe Lifecycle.QueryInstalledChaincodeResult queryChaincodeDefinitionResult; private Lifecycle.QueryInstalledChaincodeResult parsePayload() throws ProposalException { - if (null == queryChaincodeDefinitionResult) { - if (getStatus() != Status.SUCCESS) { throw new ProposalException(format("Fabric response failed on peer %s %s", getPeer(), getMessage())); } - FabricProposalResponse.ProposalResponse fabricResponse = getProposalResponse(); - - // getChaincodeActionResponsePayload() + ProposalResponsePackage.ProposalResponse fabricResponse = getProposalResponse(); if (null == fabricResponse) { throw new ProposalException(format("Proposal has no Fabric response. %s", getPeer())); @@ -66,16 +62,13 @@ private Lifecycle.QueryInstalledChaincodeResult parsePayload() throws ProposalEx * @return the packageId * @throws ProposalException */ - public String getPackageId() throws ProposalException { - Lifecycle.QueryInstalledChaincodeResult queryInstalledChaincodeResult = parsePayload(); if (queryInstalledChaincodeResult == null) { return null; } return queryInstalledChaincodeResult.getPackageId(); - } /** @@ -84,14 +77,11 @@ public String getPackageId() throws ProposalException { * @throws ProposalException */ public String getLabel() throws ProposalException { - Lifecycle.QueryInstalledChaincodeResult queryInstalledChaincodeResult = parsePayload(); if (queryInstalledChaincodeResult == null) { return null; } return queryInstalledChaincodeResult.getLabel(); - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryInstalledChaincodesProposalResponse.java b/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryInstalledChaincodesProposalResponse.java index 3c974373..9143ceec 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryInstalledChaincodesProposalResponse.java +++ b/src/main/java/org/hyperledger/fabric/sdk/LifecycleQueryInstalledChaincodesProposalResponse.java @@ -13,7 +13,7 @@ import java.util.Collection; import com.google.protobuf.ByteString; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.ProposalException; import org.hyperledger.fabric.sdk.transaction.TransactionContext; @@ -31,16 +31,12 @@ public class LifecycleQueryInstalledChaincodesProposalResponse extends ProposalR Lifecycle.QueryInstalledChaincodesResult queryChaincodeDefinitionResult; private Lifecycle.QueryInstalledChaincodesResult parsePayload() throws ProposalException { - if (null == queryChaincodeDefinitionResult) { - if (getStatus() != Status.SUCCESS) { throw new ProposalException(format("Fabric response failed on peer %s %s", getPeer(), getMessage())); } - FabricProposalResponse.ProposalResponse fabricResponse = getProposalResponse(); - - // getChaincodeActionResponsePayload() + ProposalResponsePackage.ProposalResponse fabricResponse = getProposalResponse(); if (null == fabricResponse) { throw new ProposalException(format("Proposal has no Fabric response. %s", getPeer())); @@ -63,7 +59,6 @@ private Lifecycle.QueryInstalledChaincodesResult parsePayload() throws ProposalE } public Collection getLifecycleQueryInstalledChaincodesResult() throws ProposalException { - Lifecycle.QueryInstalledChaincodesResult queryInstalledChaincodesResult = parsePayload(); Collection ret = new ArrayList<>(queryInstalledChaincodesResult.getInstalledChaincodesCount()); @@ -72,13 +67,10 @@ public Collection getLifecycleQueryInst ret.add(new LifecycleQueryInstalledChaincodesResult(qr)); } return ret; - } public class LifecycleQueryInstalledChaincodesResult { - LifecycleQueryInstalledChaincodesResult(Lifecycle.QueryInstalledChaincodesResult.InstalledChaincode installedChaincode) { - this.installedChaincode = installedChaincode; } @@ -101,6 +93,5 @@ public String getPackageId() { } private final Lifecycle.QueryInstalledChaincodesResult.InstalledChaincode installedChaincode; - } } diff --git a/src/main/java/org/hyperledger/fabric/sdk/Peer.java b/src/main/java/org/hyperledger/fabric/sdk/Peer.java index c3ac306a..2779f60a 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/Peer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/Peer.java @@ -29,8 +29,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.protos.discovery.Protocol; -import org.hyperledger.fabric.protos.peer.FabricProposal; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalPackage; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.sdk.Channel.PeerOptions; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.PeerEventingServiceException; @@ -49,7 +49,6 @@ * The Peer class represents a peer to which SDK sends deploy, or query proposals requests. */ public class Peer implements Serializable { - public static final String PEER_ORGANIZATION_MSPID_PROPERTY = "org.hyperledger.fabric.sdk.peer.organization_mspid"; private static final Config config = Config.getConfig(); @@ -103,11 +102,9 @@ boolean hasConnected() { this.properties = properties == null ? new Properties() : (Properties) properties.clone(); //keep our own copy. logger.debug("Created " + toString()); - } static Peer createNewInstance(String name, String grpcURL, Properties properties) throws InvalidArgumentException { - return new Peer(name, grpcURL, properties); } @@ -116,14 +113,11 @@ static Peer createNewInstance(String name, String grpcURL, Properties properties * * @return return the peer's name. */ - public String getName() { - return name; } public Properties getProperties() { - return properties == null ? null : (Properties) properties.clone(); } @@ -141,17 +135,12 @@ ExecutorService getExecutorService() { } 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); - } - } /** @@ -159,11 +148,8 @@ void initiateEventing(TransactionContext transactionContext, PeerOptions peersOp * * @return */ - Channel getChannel() { - return channel; - } boolean isShutdown() { @@ -175,9 +161,7 @@ boolean isShutdown() { * * @param channel */ - void setChannel(Channel channel) throws InvalidArgumentException { - if (null != this.channel) { throw new InvalidArgumentException(format("Can not add peer %s to channel %s because it already belongs to channel %s.", name, channel.getName(), this.channel.getName())); @@ -187,7 +171,6 @@ void setChannel(Channel channel) throws InvalidArgumentException { this.channel = channel; this.channelName = channel.getName(); toString = null; //recalculated - } /** @@ -196,7 +179,6 @@ void setChannel(Channel channel) throws InvalidArgumentException { * @return {string} Get the URL associated with the peer. */ public String getUrl() { - return url; } @@ -226,11 +208,11 @@ public int hashCode() { return Objects.hash(name, url); } - CompletableFuture sendProposalAsync(FabricProposal.SignedProposal proposal) { + CompletableFuture sendProposalAsync(ProposalPackage.SignedProposal proposal) { try { checkSendProposal(proposal); } catch (Exception e) { - CompletableFuture future = new CompletableFuture<>(); + CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } @@ -248,7 +230,6 @@ CompletableFuture sendProposalAsync(Fab } throw new CompletionException(throwable); }); - } private synchronized EndorserClient getEndorserClient() { @@ -302,7 +283,6 @@ CompletableFuture sendDiscoveryRequestAsync(Protocol.SignedRe } synchronized byte[] getClientTLSCertificateDigest() { - byte[] lclientTLSCertificateDigest = clientTLSCertificateDigest; if (lclientTLSCertificateDigest == null) { if (!foundClientTLSCertificateDigest) { @@ -313,12 +293,10 @@ synchronized byte[] getClientTLSCertificateDigest() { } return lclientTLSCertificateDigest; - } - private void checkSendProposal(FabricProposal.SignedProposal proposal) throws + private void checkSendProposal(ProposalPackage.SignedProposal proposal) throws PeerException, InvalidArgumentException { - if (shutdown) { throw new PeerException(format("%s was shutdown.", toString())); } @@ -441,12 +419,9 @@ public void reconnect(Long startBLockNumber) throws TransactionException { lpeerEventingClient.connect(fltransactionContext); peerEventingClient = lpeerEventingClient; } - } })); - } - } void setLastConnectTime(long lastConnectTime) { @@ -486,24 +461,20 @@ void setProperties(Properties properties) { } public interface PeerEventingServiceDisconnected { - /** * Called when a disconnect is detected in peer eventing service. * * @param event */ void disconnected(PeerEventingServiceDisconnectEvent event); - } public interface PeerEventingServiceDisconnectEvent { - /** * The latest BlockEvent received by peer eventing service. * * @return The latest BlockEvent. */ - BlockEvent getLatestBLockReceived(); /** @@ -518,7 +489,6 @@ public interface PeerEventingServiceDisconnectEvent { * * @return reconnect attempts. */ - long getReconnectCount(); /** @@ -526,11 +496,9 @@ public interface PeerEventingServiceDisconnectEvent { * * @return */ - Throwable getExceptionThrown(); void reconnect(Long startEvent) throws TransactionException; - } private transient PeerEventingServiceDisconnected disconnectedHandler = getDefaultDisconnectHandler(); @@ -539,7 +507,6 @@ private static PeerEventingServiceDisconnected getDefaultDisconnectHandler() { return new PeerEventingServiceDisconnected() { //default. @Override public synchronized void disconnected(final PeerEventingServiceDisconnectEvent event) { - BlockEvent lastBlockEvent = event.getLatestBLockReceived(); Throwable thrown = event.getExceptionThrown(); @@ -570,9 +537,7 @@ public synchronized void disconnected(final PeerEventingServiceDisconnectEvent e } catch (TransactionException e) { logger.warn(toString() + " " + e.getMessage()); } - } - }; } @@ -581,7 +546,6 @@ public synchronized void disconnected(final PeerEventingServiceDisconnectEvent e * * @return The current disconnect handler service. */ - public PeerEventingServiceDisconnected getPeerEventingServiceDisconnected() { return disconnectedHandler; } @@ -592,7 +556,6 @@ public PeerEventingServiceDisconnected getPeerEventingServiceDisconnected() { * @param newPeerEventingServiceDisconnectedHandler New handler to replace. If set to null no retry will take place. * @return the old handler. */ - public PeerEventingServiceDisconnected setPeerEventingServiceDisconnected(PeerEventingServiceDisconnected newPeerEventingServiceDisconnectedHandler) { PeerEventingServiceDisconnected ret = disconnectedHandler; disconnectedHandler = newPeerEventingServiceDisconnectedHandler; @@ -655,7 +618,6 @@ public enum PeerRole { public String getPropertyName() { return propertyName; } - } String getEndpoint() { diff --git a/src/main/java/org/hyperledger/fabric/sdk/PeerEventServiceClient.java b/src/main/java/org/hyperledger/fabric/sdk/PeerEventServiceClient.java index 830b8df8..b4d2720c 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/PeerEventServiceClient.java +++ b/src/main/java/org/hyperledger/fabric/sdk/PeerEventServiceClient.java @@ -33,18 +33,15 @@ import org.hyperledger.fabric.protos.orderer.Ab; import org.hyperledger.fabric.protos.orderer.Ab.SeekInfo; import org.hyperledger.fabric.protos.peer.DeliverGrpc; -import org.hyperledger.fabric.protos.peer.PeerEvents.DeliverResponse; +import org.hyperledger.fabric.protos.peer.EventsPackage; import org.hyperledger.fabric.sdk.Channel.PeerOptions; import org.hyperledger.fabric.sdk.exception.PeerEventingServiceException; import org.hyperledger.fabric.sdk.exception.TransactionException; import org.hyperledger.fabric.sdk.helper.Config; +import org.hyperledger.fabric.sdk.transaction.ProtoUtils; import org.hyperledger.fabric.sdk.transaction.TransactionContext; import static java.lang.String.format; -import static org.hyperledger.fabric.protos.peer.PeerEvents.DeliverResponse.TypeCase.BLOCK; -import static org.hyperledger.fabric.protos.peer.PeerEvents.DeliverResponse.TypeCase.FILTERED_BLOCK; -import static org.hyperledger.fabric.protos.peer.PeerEvents.DeliverResponse.TypeCase.STATUS; -import static org.hyperledger.fabric.sdk.transaction.ProtoUtils.createSeekInfoEnvelope; /** * Sample client code that makes gRPC calls to the server. @@ -64,7 +61,7 @@ class PeerEventServiceClient { private final boolean filterBlock; private byte[] clientTLSCertificateDigest; StreamObserver nso = null; - StreamObserver so = null; + StreamObserver so = null; private Channel.ChannelEventQue channelEventQue; private volatile boolean shutdown = false; private ManagedChannel managedChannel = null; @@ -75,7 +72,6 @@ class PeerEventServiceClient { * Construct client for accessing Peer eventing service using the existing managedChannel. */ PeerEventServiceClient(Peer peer, Endpoint endpoint, Properties properties, PeerOptions peerOptions) { - this.channelBuilder = endpoint.getChannelBuilder(); this.filterBlock = peerOptions.isRegisterEventsForFilteredBlocks(); this.peer = peer; @@ -105,13 +101,9 @@ class PeerEventServiceClient { this.channelEventQue = channel.getChannelEventQue(); if (null == properties) { - peerEventRegistrationWaitTimeMilliSecs = PEER_EVENT_REGISTRATION_WAIT_TIME; - } else { - String peerEventRegistrationWaitTime = properties.getProperty("peerEventRegistrationWaitTime", Long.toString(PEER_EVENT_REGISTRATION_WAIT_TIME)); - long tempPeerWaitTimeMilliSecs = PEER_EVENT_REGISTRATION_WAIT_TIME; try { @@ -122,7 +114,6 @@ class PeerEventServiceClient { peerEventRegistrationWaitTimeMilliSecs = tempPeerWaitTimeMilliSecs; } - } PeerOptions getPeerOptions() { @@ -135,14 +126,13 @@ public String toString() { } synchronized void shutdown(boolean force) { - if (shutdown) { return; } final String me = toString(); logger.debug(me + " is shutting down."); shutdown = true; - StreamObserver lsno = so; + StreamObserver lsno = so; nso = null; so = null; if (null != lsno) { @@ -156,7 +146,6 @@ synchronized void shutdown(boolean force) { ManagedChannel lchannel = managedChannel; managedChannel = null; if (lchannel != null) { - if (force) { lchannel.shutdownNow(); } else { @@ -175,7 +164,6 @@ synchronized void shutdown(boolean force) { channelEventQue = null; logger.debug(me + " is down."); - } @Override @@ -188,9 +176,7 @@ public void finalize() { * * @return The last block received by this peer. May return null if no block has been received since first reactivated. */ - void connectEnvelope(Envelope envelope) throws TransactionException { - if (shutdown) { logger.warn(format("%s not connecting is shutdown.", toString())); return; @@ -201,14 +187,11 @@ void connectEnvelope(Envelope envelope) throws TransactionException { ManagedChannel lmanagedChannel = managedChannel; if (lmanagedChannel == null || lmanagedChannel.isTerminated() || lmanagedChannel.isShutdown()) { - lmanagedChannel = channelBuilder.build(); managedChannel = lmanagedChannel; - } try { - DeliverGrpc.DeliverStub broadcast = DeliverGrpc.newStub(lmanagedChannel); // final DeliverResponse[] ret = new DeliverResponse[1]; @@ -216,19 +199,16 @@ void connectEnvelope(Envelope envelope) throws TransactionException { final List throwableList = new ArrayList<>(); final CountDownLatch finishLatch = new CountDownLatch(1); - so = new StreamObserver() { - + so = new StreamObserver() { @Override - public void onNext(DeliverResponse resp) { - + public void onNext(EventsPackage.DeliverResponse resp) { // logger.info("Got Broadcast response: " + resp); logger.trace(format("DeliverResponse %s resp status value:%d status %s, typecase %s ", PeerEventServiceClient.this.toString(), resp.getStatusValue(), resp.getStatus(), resp.getTypeCase())); - final DeliverResponse.TypeCase typeCase = resp.getTypeCase(); - - if (typeCase == STATUS) { + final EventsPackage.DeliverResponse.TypeCase typeCase = resp.getTypeCase(); + if (typeCase == EventsPackage.DeliverResponse.TypeCase.STATUS) { logger.debug(format("DeliverResponse %s setting done.", PeerEventServiceClient.this.toString())); @@ -236,7 +216,6 @@ public void onNext(DeliverResponse resp) { peer.setLastConnectTime(System.currentTimeMillis()); peer.resetReconnectCount(); } else { - final long rec = peer.getReconnectCount(); PeerEventingServiceException peerEventingServiceException = new PeerEventingServiceException(format("%s attempts %s Status returned failure code %d (%s) during peer service event registration", @@ -248,9 +227,9 @@ public void onNext(DeliverResponse resp) { throwableList.add(peerEventingServiceException); } - - } else if (typeCase == FILTERED_BLOCK || typeCase == BLOCK) { - if (typeCase == BLOCK) { + } else if (typeCase == EventsPackage.DeliverResponse.TypeCase.FILTERED_BLOCK || + typeCase == EventsPackage.DeliverResponse.TypeCase.BLOCK) { + if (typeCase == EventsPackage.DeliverResponse.TypeCase.BLOCK) { logger.trace(format("%s got event block hex hashcode: %016x, block number: %d", PeerEventServiceClient.this.toString(), resp.getBlock().hashCode(), resp.getBlock().getHeader().getNumber())); } else { @@ -279,10 +258,8 @@ public void onNext(DeliverResponse resp) { peerEventingServiceException.setResponse(resp); throwableList.add(peerEventingServiceException); - } finishLatch.countDown(); - } @Override @@ -302,17 +279,14 @@ public void onError(Throwable t) { if (PEER_EVENT_RECONNECTION_WARNING_RATE > 1 && reconnectCount % PEER_EVENT_RECONNECTION_WARNING_RATE == 1) { logger.warn(format("Received error on %s, attempts %d. %s", PeerEventServiceClient.this.toString(), reconnectCount, t.getMessage())); - } else { logger.trace(format("Received error on %s, attempts %d. %s", PeerEventServiceClient.this.toString(), reconnectCount, t.getMessage())); - } if (retry.getAndSet(false)) { peer.reconnectPeerEventServiceClient(PeerEventServiceClient.this, t); } - } finishLatch.countDown(); } @@ -338,7 +312,6 @@ public void onCompleted() { ex.setTimedOut(peerEventRegistrationWaitTimeMilliSecs); logger.warn(toString() + " " + ex.getMessage()); throwableList.add(0, ex); - } logger.trace(toString() + " done waiting for reply!"); @@ -352,9 +325,7 @@ public void onCompleted() { if (retry.getAndSet(false)) { peer.reconnectPeerEventServiceClient(this, throwable); } - } - } catch (InterruptedException e) { ManagedChannel llmanagedChannel = managedChannel; if (llmanagedChannel != null) { @@ -366,17 +337,14 @@ public void onCompleted() { if (retry.getAndSet(false)) { peer.reconnectPeerEventServiceClient(this, e); } - } finally { if (null != nso) { - try { nso.onCompleted(); } catch (Exception e) { //Best effort only report on debug logger.debug(format("Exception completing connect with %s %s", toString(), e.getMessage()), e); } - } } } @@ -404,7 +372,6 @@ private void peerVent(TransactionContext transactionContext) throws TransactionE final Envelope envelope; try { - Ab.SeekPosition.Builder start = Ab.SeekPosition.newBuilder(); if (null != peerOptions.getNewest()) { start.setNewest(Ab.SeekNewest.getDefaultInstance()); @@ -414,7 +381,7 @@ private void peerVent(TransactionContext transactionContext) throws TransactionE start.setNewest(Ab.SeekNewest.getDefaultInstance()); } - envelope = createSeekInfoEnvelope(transactionContext, + envelope = ProtoUtils.createSeekInfoEnvelope(transactionContext, start.build(), Ab.SeekPosition.newBuilder() .setSpecified(Ab.SeekSpecified.newBuilder().setNumber(peerOptions.getStopEvents()).build()) @@ -426,11 +393,9 @@ private void peerVent(TransactionContext transactionContext) throws TransactionE } catch (Exception e) { throw new TransactionException(toString() + " error message: " + e.getMessage(), e); } - } String getStatus() { - ManagedChannel lmanagedChannel = managedChannel; if (lmanagedChannel == null) { return "No grpc managed channel active. peer eventing client service is shutdown: " + shutdown; @@ -443,6 +408,5 @@ String getStatus() { .append(", grpc state: ").append("" + lmanagedChannel.getState(false)); return sb.toString(); } - } } diff --git a/src/main/java/org/hyperledger/fabric/sdk/ProposalResponse.java b/src/main/java/org/hyperledger/fabric/sdk/ProposalResponse.java index f770be31..bb4a2e41 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/ProposalResponse.java +++ b/src/main/java/org/hyperledger/fabric/sdk/ProposalResponse.java @@ -15,11 +15,10 @@ import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.protos.common.Common; import org.hyperledger.fabric.protos.common.Common.Header; -import org.hyperledger.fabric.protos.ledger.rwset.Rwset.TxReadWriteSet; +import org.hyperledger.fabric.protos.ledger.rwset.Rwset; import org.hyperledger.fabric.protos.msp.Identities; -import org.hyperledger.fabric.protos.peer.FabricProposal; -import org.hyperledger.fabric.protos.peer.FabricProposal.ChaincodeHeaderExtension; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalPackage; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.sdk.exception.CryptoException; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -44,8 +43,8 @@ public class ProposalResponse extends ChaincodeResponse { private boolean hasBeenVerified = false; private WeakReference proposalResponsePayload; - private FabricProposal.Proposal proposal; - private FabricProposalResponse.ProposalResponse proposalResponse; + private ProposalPackage.Proposal proposal; + private ProposalResponsePackage.ProposalResponse proposalResponse; private Peer peer = null; private ChaincodeID chaincodeID = null; private final TransactionContext transactionContext; @@ -71,23 +70,19 @@ ProposalResponsePayloadDeserializer getProposalResponsePayloadDeserializer() thr } if (ret == null) { - try { ret = new ProposalResponsePayloadDeserializer(proposalResponse.getPayload()); } catch (Exception e) { throw new InvalidArgumentException(e); } - proposalResponsePayload = new WeakReference<>(ret); } return ret; - } ByteString getPayloadBytes() { return proposalResponse.getPayload(); - } public boolean isVerified() { @@ -120,7 +115,7 @@ boolean verify(CryptoSuite crypto) { return false; } - FabricProposalResponse.Endorsement endorsement = this.proposalResponse.getEndorsement(); + ProposalResponsePackage.Endorsement endorsement = this.proposalResponse.getEndorsement(); ByteString sig = endorsement.getSignature(); byte[] endorserCertifcate = null; byte[] signature = null; @@ -132,7 +127,6 @@ boolean verify(CryptoSuite crypto) { ByteString plainText = proposalResponse.getPayload().concat(endorsement.getEndorser()); if (config.extraLogLevel(10)) { - if (null != diagnosticFileDumper) { StringBuilder sb = new StringBuilder(10000); sb.append("payload TransactionBuilderbytes in hex: " + DatatypeConverter.printHexBinary(proposalResponse.getPayload().toByteArray())); @@ -145,14 +139,12 @@ boolean verify(CryptoSuite crypto) { logger.trace("payload TransactionBuilderbytes: " + diagnosticFileDumper.createDiagnosticFile(sb.toString())); } - } if (sig == null || sig.isEmpty()) { // we shouldn't get here ... logger.warn(format("%s %s returned signature is empty verify set to false.", peer, getTransactionID())); this.isVerified = false; } else { - endorserCertifcate = endorser.getIdBytes().toByteArray(); signature = sig.toByteArray(); data = plainText.toByteArray(); @@ -187,17 +179,15 @@ peer, getTransactionID(), toHexString(endorserCertifcate), toHexString(signature } } // verify - public FabricProposal.Proposal getProposal() { + public ProposalPackage.Proposal getProposal() { return proposal; } - public void setProposal(FabricProposal.SignedProposal signedProposal) throws ProposalException { - + public void setProposal(ProposalPackage.SignedProposal signedProposal) throws ProposalException { try { - this.proposal = FabricProposal.Proposal.parseFrom(signedProposal.getProposalBytes()); + this.proposal = ProposalPackage.Proposal.parseFrom(signedProposal.getProposalBytes()); } catch (InvalidProtocolBufferException e) { throw new ProposalException(format("%s transaction: %s Proposal exception", peer, getTransactionID()), e); - } } @@ -206,12 +196,11 @@ public void setProposal(FabricProposal.SignedProposal signedProposal) throws Pro * * @return peer response. */ - - public FabricProposalResponse.ProposalResponse getProposalResponse() { + public ProposalResponsePackage.ProposalResponse getProposalResponse() { return proposalResponse; } - public void setProposalResponse(FabricProposalResponse.ProposalResponse proposalResponse) { + public void setProposalResponse(ProposalResponsePackage.ProposalResponse proposalResponse) { this.proposalResponse = proposalResponse; } @@ -220,7 +209,6 @@ public void setProposalResponse(FabricProposalResponse.ProposalResponse proposal * * @return See {@link Peer} */ - public Peer getPeer() { return this.peer; } @@ -239,24 +227,18 @@ void setPeer(Peer peer) { * @return See {@link ChaincodeID} * @throws InvalidArgumentException */ - public ChaincodeID getChaincodeID() throws InvalidArgumentException { - try { - if (chaincodeID == null) { - Header header = Header.parseFrom(proposal.getHeader()); Common.ChannelHeader channelHeader = Common.ChannelHeader.parseFrom(header.getChannelHeader()); - ChaincodeHeaderExtension chaincodeHeaderExtension = ChaincodeHeaderExtension.parseFrom(channelHeader.getExtension()); + ProposalPackage.ChaincodeHeaderExtension chaincodeHeaderExtension = ProposalPackage.ChaincodeHeaderExtension.parseFrom(channelHeader.getExtension()); chaincodeID = new ChaincodeID(chaincodeHeaderExtension.getChaincodeId()); } return chaincodeID; - } catch (Exception e) { throw new InvalidArgumentException(e); } - } /** @@ -265,21 +247,15 @@ public ChaincodeID getChaincodeID() throws InvalidArgumentException { * @return the result of the executing chaincode. * @throws InvalidArgumentException */ - public byte[] getChaincodeActionResponsePayload() throws InvalidArgumentException { - if (isInvalid()) { throw new InvalidArgumentException("Proposal response is invalid."); } try { - final ProposalResponsePayloadDeserializer proposalResponsePayloadDeserializer = getProposalResponsePayloadDeserializer(); ByteString ret = proposalResponsePayloadDeserializer.getExtension().getChaincodeAction().getResponse().getPayload(); - if (null == ret) { - return null; - } - return ret.toByteArray(); + return ret != null ? ret.toByteArray() : null; } catch (InvalidArgumentException e) { throw e; } catch (Exception e) { @@ -293,25 +269,20 @@ public byte[] getChaincodeActionResponsePayload() throws InvalidArgumentExceptio * @return status code. * @throws InvalidArgumentException */ - public int getChaincodeActionResponseStatus() throws InvalidArgumentException { - if (statusReturnCode != -1) { return statusReturnCode; } try { - final ProposalResponsePayloadDeserializer proposalResponsePayloadDeserializer = getProposalResponsePayloadDeserializer(); statusReturnCode = proposalResponsePayloadDeserializer.getExtension().getResponseStatus(); return statusReturnCode; - } catch (InvalidArgumentException e) { throw e; } catch (Exception e) { throw new InvalidArgumentException(e); } - } /** @@ -320,29 +291,17 @@ public int getChaincodeActionResponseStatus() throws InvalidArgumentException { * @return The read write set. See {@link TxReadWriteSetInfo} * @throws InvalidArgumentException */ - public TxReadWriteSetInfo getChaincodeActionResponseReadWriteSetInfo() throws InvalidArgumentException { - if (isInvalid()) { throw new InvalidArgumentException("Proposal response is invalid."); } try { - final ProposalResponsePayloadDeserializer proposalResponsePayloadDeserializer = getProposalResponsePayloadDeserializer(); - - TxReadWriteSet txReadWriteSet = proposalResponsePayloadDeserializer.getExtension().getResults(); - - if (txReadWriteSet == null) { - return null; - } - - return new TxReadWriteSetInfo(txReadWriteSet); - + Rwset.TxReadWriteSet txReadWriteSet = proposalResponsePayloadDeserializer.getExtension().getResults(); + return txReadWriteSet != null ? new TxReadWriteSetInfo(txReadWriteSet) : null; } catch (Exception e) { throw new InvalidArgumentException(e); } - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/ProposalResponsePayloadDeserializer.java b/src/main/java/org/hyperledger/fabric/sdk/ProposalResponsePayloadDeserializer.java index c604d5dd..0342b547 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/ProposalResponsePayloadDeserializer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/ProposalResponsePayloadDeserializer.java @@ -20,60 +20,42 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; -import static org.hyperledger.fabric.protos.peer.FabricProposalResponse.ProposalResponsePayload; - class ProposalResponsePayloadDeserializer { private final ByteString byteString; - private WeakReference proposalResponsePayload; + private WeakReference proposalResponsePayload; private WeakReference chaincodeAction; ProposalResponsePayloadDeserializer(ByteString byteString) { this.byteString = byteString; } - ProposalResponsePayload getProposalResponsePayload() { - ProposalResponsePayload ret = null; - - if (proposalResponsePayload != null) { - ret = proposalResponsePayload.get(); - - } - if (ret == null) { + ProposalResponsePackage.ProposalResponsePayload getProposalResponsePayload() { + ProposalResponsePackage.ProposalResponsePayload ret = proposalResponsePayload != null ? proposalResponsePayload.get() : null; + if (null == ret) { try { - ret = ProposalResponsePayload.parseFrom(byteString); + ret = ProposalResponsePackage.ProposalResponsePayload.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } proposalResponsePayload = new WeakReference<>(ret); - } return ret; - } ChaincodeActionDeserializer getExtension() { + ChaincodeActionDeserializer ret = chaincodeAction != null ? chaincodeAction.get() : null; - ChaincodeActionDeserializer ret = null; - - if (chaincodeAction != null) { - ret = chaincodeAction.get(); - - } - if (ret == null) { - + if (null == ret) { ret = new ChaincodeActionDeserializer(getProposalResponsePayload().getExtension()); - chaincodeAction = new WeakReference<>(ret); - } return ret; - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/ServiceDiscovery.java b/src/main/java/org/hyperledger/fabric/sdk/ServiceDiscovery.java index d9035dd2..604d5c9b 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/ServiceDiscovery.java +++ b/src/main/java/org/hyperledger/fabric/sdk/ServiceDiscovery.java @@ -40,7 +40,7 @@ import org.hyperledger.fabric.protos.discovery.Protocol; import org.hyperledger.fabric.protos.gossip.Message; import org.hyperledger.fabric.protos.msp.Identities; -import org.hyperledger.fabric.protos.msp.MspConfig; +import org.hyperledger.fabric.protos.msp.MspConfigPackage; import org.hyperledger.fabric.sdk.Channel.ServiceDiscoveryChaincodeCalls; import org.hyperledger.fabric.sdk.ServiceDiscovery.SDLayout.SDGroup; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; @@ -98,15 +98,12 @@ SDChaindcode discoverEndorserEndpoint(TransactionContext transactionContext, fin } Collection getDiscoveredChaincodeNames() { - final SDNetwork lsdNetwork = fullNetworkDiscovery(false); if (null == lsdNetwork) { return Collections.emptyList(); - } return new ArrayList<>(lsdNetwork.getChaincodesNames()); - } class SDNetwork { @@ -119,7 +116,6 @@ void addTlsCert(String mspid, byte[] cert) { logger.trace(format("Channel %s service discovery MSPID %s adding TLSCert %s", channelName, mspid, toHexString(cert))); } tlsCerts.computeIfAbsent(mspid, k -> new LinkedList<>()).add(cert); - } void addTlsIntermCert(String mspid, byte[] cert) { @@ -127,7 +123,6 @@ void addTlsIntermCert(String mspid, byte[] cert) { logger.trace(format("Channel %s service discovery MSPID %s adding intermediate TLSCert %s", channelName, mspid, toHexString(cert))); } tlsIntermCerts.computeIfAbsent(mspid, k -> new LinkedList<>()).add(cert); - } SDEndorser getEndorserByEndpoint(String endpoint) { @@ -147,13 +142,10 @@ Set getOrdererEndpoints() { } Collection getSDOrderers() { - return ordererEndpoints.values(); - } Set getPeerEndpoints() { - return Collections.unmodifiableSet(endorsers.keySet()); } @@ -161,7 +153,6 @@ Set getPeerEndpoints() { Set getChaincodesNames() { if (null == chaincodeNames) { - if (null == endorsers) { chaincodeNames = Collections.emptySet(); return chaincodeNames; @@ -177,7 +168,6 @@ Set getChaincodesNames() { } return chaincodeNames; - } Collection getTlsCerts(final String mspid) { @@ -215,7 +205,6 @@ Collection getTlsIntermediateCerts(String mspid) { private final ConcurrentSet certs = new ConcurrentSet<>(); SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force) { - logger.trace(format("Network discovery force: %b", force)); ArrayList speers = new ArrayList<>(serviceDiscoveryPeers); @@ -223,17 +212,13 @@ SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force SDNetwork ret = sdNetwork; if (!force && null != ret && ret.discoveryTime + SERVICE_DISCOVER_FREQ_SECONDS * 1000 > System.currentTimeMillis()) { - return ret; } ret = null; for (final Peer serviceDiscoveryPeer : speers) { - try { - SDNetwork lsdNetwork = new SDNetwork(); - final byte[] clientTLSCertificateDigest = serviceDiscoveryPeer.getClientTLSCertificateDigest(); logger.info(format("Channel %s doing discovery with peer: %s", channelName, serviceDiscoveryPeer.toString())); @@ -247,9 +232,7 @@ SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force Protocol.AuthInfo authentication = Protocol.AuthInfo.newBuilder().setClientIdentity(clientIdent).setClientTlsCertHash(tlshash).build(); List fq = new ArrayList<>(2); - fq.add(Protocol.Query.newBuilder().setChannel(channelName).setConfigQuery(Protocol.ConfigQuery.newBuilder().build()).build()); - fq.add(Protocol.Query.newBuilder().setChannel(channelName).setPeerQuery(Protocol.PeerMembershipQuery.newBuilder().build()).build()); Protocol.Request request = Protocol.Request.newBuilder().addAllQueries(fq).setAuthentication(authentication).build(); @@ -287,11 +270,11 @@ SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force } Protocol.ConfigResult configResult = queryResult.getConfigResult(); - Map msps = configResult.getMspsMap(); + Map msps = configResult.getMspsMap(); Set cbbs = new HashSet<>(msps.size() * 4); - for (Map.Entry i : msps.entrySet()) { - final MspConfig.FabricMSPConfig value = i.getValue(); + for (Map.Entry i : msps.entrySet()) { + final MspConfigPackage.FabricMSPConfig value = i.getValue(); final String mspid = value.getName(); cbbs.addAll(value.getRootCertsList()); cbbs.addAll(value.getIntermediateCertsList()); @@ -304,13 +287,11 @@ SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force List toaddCerts = new LinkedList<>(); synchronized (certs) { - cbbs.forEach(bytes -> { if (certs.add(bytes)) { toaddCerts.add(bytes.toByteArray()); } }); - } if (!toaddCerts.isEmpty()) { // add them to crypto store. channel.client.getCryptoSuite().loadCACertificatesAsBytes(toaddCerts); @@ -352,7 +333,6 @@ SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force final Protocol.Peers peer = peers.getValue(); for (Protocol.Peer pp : peer.getPeersList()) { - SDEndorser ppp = new SDEndorser(pp, lsdNetwork.getTlsCerts(mspId), lsdNetwork.getTlsIntermediateCerts(mspId)); SDEndorser discoveredAlready = lsdNetwork.endorsers.get(ppp.getEndpoint()); @@ -368,7 +348,6 @@ SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force logger.trace(format("Channel %s peer: %s discovered peer mspid group: %s, endpoint: %s, mspid: %s", channelName, serviceDiscoveryPeer, mspId, ppp.getEndpoint(), ppp.getMspid())); lsdNetwork.endorsers.put(ppp.getEndpoint(), ppp); - } } lsdNetwork.discoveryTime = System.currentTimeMillis(); @@ -376,7 +355,6 @@ SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force sdNetwork = lsdNetwork; ret = lsdNetwork; break; - } catch (Exception e) { logger.warn(format("Channel %s peer %s service discovery error %s", channelName, serviceDiscoveryPeer, e.getMessage())); } @@ -385,11 +363,9 @@ SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force logger.debug(format("Channel %s service discovery completed: %b", channelName, ret != null)); return ret; - } public static class SDOrderer { - private final String mspid; private final Collection tlsCerts; private final Collection tlsIntermediateCerts; @@ -420,7 +396,6 @@ public Collection getTlsCerts() { } Map discoverEndorserEndpoints(TransactionContext transactionContext, List> chaincodeNames) throws ServiceDiscoveryException { - if (null == chaincodeNames) { logger.warn("Discover of chaincode names was null."); return Collections.emptyMap(); @@ -455,7 +430,6 @@ Map discoverEndorserEndpoints(TransactionContext transacti logger.debug(format("Channel %s doing discovery for chaincodes on peer: %s", channelName, serviceDiscoveryPeer.toString())); TransactionContext ltransactionContext = transactionContext.retryTransactionSameContext(); - final byte[] clientTLSCertificateDigest = serviceDiscoveryPeer.getClientTLSCertificateDigest(); if (null == clientTLSCertificateDigest) { @@ -470,7 +444,6 @@ Map discoverEndorserEndpoints(TransactionContext transacti List fq = new ArrayList<>(chaincodeNames.size()); for (List chaincodeName : chaincodeNames) { - if (ret.containsKey(chaincodeName.get(0).getName())) { continue; } @@ -488,7 +461,6 @@ Map discoverEndorserEndpoints(TransactionContext transacti if (fq.size() == 0) { //this would be odd but lets take care of it. break; - } Protocol.Request request = Protocol.Request.newBuilder().addAllQueries(fq).setAuthentication(authentication).build(); @@ -511,9 +483,7 @@ Map discoverEndorserEndpoints(TransactionContext transacti serviceDiscoveryPeer.hasConnected(); for (Protocol.QueryResult queryResult : response.getResultsList()) { - if (queryResult.getResultCase().getNumber() == Protocol.QueryResult.ERROR_FIELD_NUMBER) { - ServiceDiscoveryException discoveryException = new ServiceDiscoveryException(format("Error %s", queryResult.getError().getContent())); logger.error(discoveryException.getMessage()); continue; @@ -523,7 +493,6 @@ Map discoverEndorserEndpoints(TransactionContext transacti ServiceDiscoveryException discoveryException = new ServiceDiscoveryException(format("Error expected chaincode endorsement query but got %s : ", queryResult.getResultCase().toString())); logger.error(discoveryException.getMessage()); continue; - } Protocol.ChaincodeQueryResult ccQueryRes = queryResult.getCcQueryRes(); @@ -551,26 +520,20 @@ Map discoverEndorserEndpoints(TransactionContext transacti List sdEndorsers = new LinkedList<>(); for (Protocol.Peer pp : peers.getPeersList()) { - SDEndorser ppp = new SDEndorser(pp, null, null); final String endPoint = ppp.getEndpoint(); SDEndorser nppp = sdNetwork.getEndorserByEndpoint(endPoint); if (null == nppp) { - sdNetwork = networkDiscovery(transactionContext, true); if (null == sdNetwork) { throw new ServiceDiscoveryException("Failed to discover network resources."); } nppp = sdNetwork.getEndorserByEndpoint(ppp.getEndpoint()); if (null == nppp) { - throw new ServiceDiscoveryException(format("Failed to discover peer endpoint information %s for chaincode %s ", endPoint, chaincode)); - } - } sdEndorsers.add(nppp); - } if (sdLayout == null) { sdLayout = new SDLayout(); @@ -582,18 +545,15 @@ Map discoverEndorserEndpoints(TransactionContext transacti if (layouts.isEmpty()) { logger.warn(format("Channel %s chaincode %s discovered no layouts!", channelName, chaincode)); } else { - if (DEBUG) { StringBuilder sb = new StringBuilder(1000); sb.append("Channel ").append(channelName) .append(" found ").append(layouts.size()).append(" layouts for chaincode: ").append(es.getChaincode()); - sb.append(", layouts: ["); String sep = ""; for (SDLayout layout : layouts) { sb.append(sep).append(layout); - sep = ", "; } sb.append("]"); @@ -603,13 +563,11 @@ Map discoverEndorserEndpoints(TransactionContext transacti ret.put(es.getChaincode(), new SDChaindcode(es.getChaincode(), layouts)); } } - } if (ret.size() == chaincodeNames.size()) { break; // found them all. } - } catch (ServiceDiscoveryException e) { logger.warn(format("Service discovery error on peer %s. Error: %s", serviceDiscoveryPeer.toString(), e.getMessage())); serviceDiscoveryException = e; @@ -627,13 +585,11 @@ Map discoverEndorserEndpoints(TransactionContext transacti } return ret; - } /** * Endorsement selection by layout group that has least required and block height is the highest (most up to date). */ - static final EndorsementSelector ENDORSEMENT_SELECTION_LEAST_REQUIRED_BLOCKHEIGHT = sdChaindcode -> { List layouts = sdChaindcode.getLayouts(); @@ -655,7 +611,6 @@ boolean endorsed(Set endorsed) { } } return stillRequred > 0; - } } @@ -666,7 +621,6 @@ boolean endorsed(Set endorsed) { // if (layouts.size() > 1) { // pick layout by least number of endorsers .. least number of peers hit and smaller block! for (SDLayout sdLayout : layouts) { - Set remainingGroups = new HashSet<>(); for (SDGroup sdGroup : sdLayout.getSDLGroups()) { remainingGroups.add(new LGroup(sdGroup)); @@ -699,7 +653,6 @@ boolean endorsed(Set endorsed) { //Now go through groups finding which endorsers can satisfy the most groups. do { - Map matchCount = new HashMap<>(); for (LGroup group : remainingGroups) { @@ -748,11 +701,9 @@ boolean endorsed(Set endorsed) { Set sdEndorsers = layoutEndorsers.computeIfAbsent(sdLayout, k -> new HashSet<>()); sdEndorsers.addAll(theVeryMost); remainingGroups.removeAll(remove2); - } while (!remainingGroups.isEmpty()); // Now pick the layout with least endorsers - } //Pick layout which needs least endorsements. int min = Integer.MAX_VALUE; @@ -772,7 +723,6 @@ boolean endorsed(Set endorsed) { if (theLeast.size() == 1) { pickedLayout = theLeast.iterator().next(); - } else { long max = 0L; // Tie breaker: Pick one with greatest ledger height. @@ -793,7 +743,6 @@ boolean endorsed(Set endorsed) { sdEndorserState.setPickedLayout(pickedLayout); return sdEndorserState; - }; public static final EndorsementSelector DEFAULT_ENDORSEMENT_SELECTION = ENDORSEMENT_SELECTION_LEAST_REQUIRED_BLOCKHEIGHT; @@ -834,7 +783,6 @@ public static class SDChaindcode { final List layouts; SDChaindcode(SDChaindcode sdChaindcode) { - name = sdChaindcode.name; layouts = new LinkedList<>(); sdChaindcode.layouts.forEach(sdLayout -> layouts.add(new SDLayout(sdLayout))); @@ -877,7 +825,6 @@ boolean endorsedList(Collection sdEndorsers) { // return the set needed or null if the policy was not meet. Collection meetsEndorsmentPolicy(Set endpoints) { - Collection ret = null; // not meet. for (SDLayout sdLayout : layouts) { @@ -906,16 +853,12 @@ public String toString() { sb.append(")"); return sb.toString(); } - } public static class SDLayout { - final List groups = new LinkedList<>(); - SDLayout() { - - } + SDLayout() { } //Copy constructor SDLayout(SDLayout sdLayout) { @@ -944,7 +887,6 @@ public String toString() { sb.append("}"); return sb.toString(); - } //return true if the groups still exist to get endorsement. @@ -974,7 +916,6 @@ boolean ignoreListSDEndorser(Collection names) { // endorsement has been meet. boolean endorsedList(Collection sdEndorsers) { - int endorsementMeet = 0; for (SDGroup group : groups) { if (group.endorsedList(sdEndorsers)) { @@ -1001,7 +942,6 @@ Collection meetsEndorsmentPolicy(Set endpoints) { public Collection getSDLGroups() { return new ArrayList<>(groups); - } public class SDGroup { @@ -1018,7 +958,6 @@ public class SDGroup { this.name = name; this.required = required; this.endorsers.addAll(endorsers); - } SDGroup(SDGroup group) { //copy constructor @@ -1105,7 +1044,6 @@ public String toString() { // Returns Collection meetsEndorsmentPolicy(Set allEndorsed, Collection requiredYet) { - Set ret = new HashSet<>(this.endorsers.size()); for (SDEndorser hasBeenEndorsed : allEndorsed) { for (SDEndorser sdEndorser : endorsers) { @@ -1118,7 +1056,6 @@ Collection meetsEndorsmentPolicy(Set allEndorsed, Collec } } if (null != requiredYet) { - for (SDEndorser sdEndorser : endorsers) { if (!allEndorsed.contains(sdEndorser)) { requiredYet.add(sdEndorser); @@ -1127,23 +1064,19 @@ Collection meetsEndorsmentPolicy(Set allEndorsed, Collec } return null; // group has not meet endorsement. } - } void addGroup(String key, int required, List endorsers) { new SDGroup(key, required, endorsers); - } } public static class SDEndorserState { - private Collection sdEndorsers = new ArrayList<>(); private SDLayout pickedLayout; public void setPickedEndorsers(Collection sdEndorsers) { this.sdEndorsers = sdEndorsers; - } Collection getSdEndorsers() { @@ -1160,7 +1093,6 @@ public SDLayout getPickedLayout() { } public static class SDEndorser { - private List chaincodesList; // private final Protocol.Peer proto; private String endPoint = null; @@ -1203,14 +1135,12 @@ private void parseIdentity(Protocol.Peer peerRet) { try { Identities.SerializedIdentity serializedIdentity = Identities.SerializedIdentity.parseFrom(peerRet.getIdentity()); mspid = serializedIdentity.getMspid(); - } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } } private String parseEndpoint(Protocol.Peer peerRet) throws InvalidProtocolBufferRuntimeException { - if (null == endPoint) { try { Message.Envelope membershipInfo = peerRet.getMembershipInfo(); @@ -1228,14 +1158,11 @@ private String parseEndpoint(Protocol.Peer peerRet) throws InvalidProtocolBuffer } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - } return endPoint; - } private long parseLedgerHeight(Protocol.Peer peerRet) throws InvalidProtocolBufferRuntimeException { - if (-1L == ledgerHeight) { try { Message.Envelope stateInfo = peerRet.getStateInfo(); @@ -1248,7 +1175,6 @@ private long parseLedgerHeight(Protocol.Peer peerRet) throws InvalidProtocolBuff ledgerHeight = stateInfo1.getProperties().getLedgerHeight(); this.chaincodesList = stateInfo1.getProperties().getChaincodesList(); - } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } @@ -1272,7 +1198,6 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return Objects.hash(mspid, endPoint); } @@ -1295,7 +1220,6 @@ public String getMspid() { public String toString() { return "SDEndorser-" + mspid + "-" + endPoint; } - } private static List topNbyHeight(int required, List endorsers) { @@ -1309,25 +1233,21 @@ private static List topNbyHeight(int required, List endo private static final int SERVICE_DISCOVER_FREQ_SECONDS = config.getServiceDiscoveryFreqSeconds(); void run() { - if (channel.isShutdown() || SERVICE_DISCOVER_FREQ_SECONDS < 1) { return; } if (seviceDiscovery == null) { - seviceDiscovery = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; }).scheduleAtFixedRate(() -> { - logger.debug(format("Channel %s starting service rediscovery after %d seconds.", channelName, SERVICE_DISCOVER_FREQ_SECONDS)); fullNetworkDiscovery(true); }, SERVICE_DISCOVER_FREQ_SECONDS, SERVICE_DISCOVER_FREQ_SECONDS, TimeUnit.SECONDS); } - } SDNetwork fullNetworkDiscovery(boolean force) { @@ -1359,7 +1279,6 @@ SDNetwork fullNetworkDiscovery(boolean force) { } return lsdNetwork; - } catch (Exception e) { logger.warn("Service discovery got error:" + e.getMessage(), e); } finally { diff --git a/src/main/java/org/hyperledger/fabric/sdk/TransactionActionDeserializer.java b/src/main/java/org/hyperledger/fabric/sdk/TransactionActionDeserializer.java index a380a438..1e7a4e89 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/TransactionActionDeserializer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/TransactionActionDeserializer.java @@ -20,62 +20,47 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import org.hyperledger.fabric.protos.peer.FabricTransaction.TransactionAction; +import org.hyperledger.fabric.protos.peer.TransactionPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; class TransactionActionDeserializer { private final ByteString byteString; - private WeakReference transactionAction; + private WeakReference transactionAction; private WeakReference chaincodeActionPayloadDeserializer; TransactionActionDeserializer(ByteString byteString) { this.byteString = byteString; } - TransactionActionDeserializer(TransactionAction transactionAction) { + TransactionActionDeserializer(TransactionPackage.TransactionAction transactionAction) { byteString = transactionAction.toByteString(); - this.transactionAction = new WeakReference(transactionAction); + this.transactionAction = new WeakReference(transactionAction); } - TransactionAction getTransactionAction() { - TransactionAction ret = null; - - if (transactionAction != null) { - ret = transactionAction.get(); - - } - if (ret == null) { + TransactionPackage.TransactionAction getTransactionAction() { + TransactionPackage.TransactionAction ret = transactionAction != null ? transactionAction.get() : null; + if (null == ret) { try { - ret = TransactionAction.parseFrom(byteString); + ret = TransactionPackage.TransactionAction.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } - transactionAction = new WeakReference(ret); + transactionAction = new WeakReference<>(ret); } return ret; - } ChaincodeActionPayloadDeserializer getPayload() { + ChaincodeActionPayloadDeserializer ret = chaincodeActionPayloadDeserializer != null ? chaincodeActionPayloadDeserializer.get() : null; - ChaincodeActionPayloadDeserializer ret = null; - - if (chaincodeActionPayloadDeserializer != null) { - ret = chaincodeActionPayloadDeserializer.get(); - - } - if (ret == null) { - + if (null == ret) { ret = new ChaincodeActionPayloadDeserializer(getTransactionAction().getPayload()); - - chaincodeActionPayloadDeserializer = new WeakReference(ret); - + chaincodeActionPayloadDeserializer = new WeakReference<>(ret); } return ret; - } } diff --git a/src/main/java/org/hyperledger/fabric/sdk/TransactionDeserializer.java b/src/main/java/org/hyperledger/fabric/sdk/TransactionDeserializer.java index a84dae61..2822748e 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/TransactionDeserializer.java +++ b/src/main/java/org/hyperledger/fabric/sdk/TransactionDeserializer.java @@ -24,13 +24,12 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; +import org.hyperledger.fabric.protos.peer.TransactionPackage; import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; -import static org.hyperledger.fabric.protos.peer.FabricTransaction.Transaction; - class TransactionDeserializer { private final ByteString byteString; - private WeakReference transaction; + private WeakReference transaction; private final Map> transactionActions = Collections.synchronizedMap(new WeakHashMap>()); @@ -38,37 +37,28 @@ class TransactionDeserializer { this.byteString = byteString; } - Transaction getTransaction() { - Transaction ret = null; - - if (transaction != null) { - ret = transaction.get(); - - } - if (ret == null) { + TransactionPackage.Transaction getTransaction() { + TransactionPackage.Transaction ret = transaction != null ? transaction.get() : null; + if (null == ret) { try { - ret = Transaction.parseFrom(byteString); + ret = TransactionPackage.Transaction.parseFrom(byteString); } catch (InvalidProtocolBufferException e) { throw new InvalidProtocolBufferRuntimeException(e); } transaction = new WeakReference<>(ret); - } return ret; - } int getActionsCount() { - return getTransaction().getActionsCount(); } TransactionActionDeserializer getTransactionAction(int index) { - - final Transaction transaction = getTransaction(); + final TransactionPackage.Transaction transaction = getTransaction(); if (index >= getActionsCount()) { return null; @@ -83,17 +73,13 @@ TransactionActionDeserializer getTransactionAction(int index) { } TransactionActionDeserializer transactionActionDeserialize = new TransactionActionDeserializer(transaction.getActions(index)); - transactionActions.put(index, new WeakReference<>(transactionActionDeserialize)); return transactionActionDeserialize; - } Iterable getTransactionActions() { - return new TransactionActionIterable(); - } class TransactionActionIterator implements Iterator { @@ -102,7 +88,6 @@ class TransactionActionIterator implements Iterator iterator() { return new TransactionActionIterator(); } } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/TransactionInfo.java b/src/main/java/org/hyperledger/fabric/sdk/TransactionInfo.java index ba0da97d..700f16de 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/TransactionInfo.java +++ b/src/main/java/org/hyperledger/fabric/sdk/TransactionInfo.java @@ -14,47 +14,46 @@ package org.hyperledger.fabric.sdk; import org.hyperledger.fabric.protos.common.Common.Envelope; -import org.hyperledger.fabric.protos.peer.FabricTransaction.ProcessedTransaction; -import org.hyperledger.fabric.protos.peer.FabricTransaction.TxValidationCode; +import org.hyperledger.fabric.protos.peer.TransactionPackage; /** - * TransactionInfo contains the data from a {@link ProcessedTransaction} message + * TransactionInfo contains the data from a {@link TransactionPackage.ProcessedTransaction} message */ public class TransactionInfo { private final String txID; - private final ProcessedTransaction processedTransaction; + private final TransactionPackage.ProcessedTransaction processedTransaction; - TransactionInfo(String txID, ProcessedTransaction processedTransaction) { + TransactionInfo(String txID, TransactionPackage.ProcessedTransaction processedTransaction) { this.txID = txID; this.processedTransaction = processedTransaction; } /** - * @return the transaction ID of this {@link ProcessedTransaction} + * @return the transaction ID of this {@link TransactionPackage.ProcessedTransaction} */ public String getTransactionID() { return txID; } /** - * @return the {@link Envelope} of this {@link ProcessedTransaction} + * @return the {@link Envelope} of this {@link TransactionPackage.ProcessedTransaction} */ public Envelope getEnvelope() { return processedTransaction.getTransactionEnvelope(); } /** - * @return the raw {@link ProcessedTransaction} + * @return the raw {@link TransactionPackage.ProcessedTransaction} */ - public ProcessedTransaction getProcessedTransaction() { + public TransactionPackage.ProcessedTransaction getProcessedTransaction() { return processedTransaction; } /** - * @return the {@link TxValidationCode} of this {@link ProcessedTransaction} + * @return the {@link TransactionPackage.TxValidationCode} of this {@link TransactionPackage.ProcessedTransaction} */ - public TxValidationCode getValidationCode() { - return TxValidationCode.forNumber(processedTransaction.getValidationCode()); + public TransactionPackage.TxValidationCode getValidationCode() { + return TransactionPackage.TxValidationCode.forNumber(processedTransaction.getValidationCode()); } } diff --git a/src/main/java/org/hyperledger/fabric/sdk/TransactionRequest.java b/src/main/java/org/hyperledger/fabric/sdk/TransactionRequest.java index a4baf1d6..cee75e2d 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/TransactionRequest.java +++ b/src/main/java/org/hyperledger/fabric/sdk/TransactionRequest.java @@ -20,7 +20,6 @@ import java.util.Map; import org.hyperledger.fabric.protos.peer.Chaincode; -import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.helper.Config; /** @@ -144,18 +143,13 @@ public ChaincodeID getChaincodeID() { } public void setChaincodeID(ChaincodeID chaincodeID) { - if (chaincodeName != null) { - throw new IllegalArgumentException("Chaincode name has already been set."); } if (chaincodeVersion != null) { - throw new IllegalArgumentException("Chaincode version has already been set."); } - if (chaincodePath != null) { - throw new IllegalArgumentException("Chaincode path has already been set."); } diff --git a/src/main/java/org/hyperledger/fabric/sdk/exception/PeerEventingServiceException.java b/src/main/java/org/hyperledger/fabric/sdk/exception/PeerEventingServiceException.java index 906d32d0..78a1bac6 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/exception/PeerEventingServiceException.java +++ b/src/main/java/org/hyperledger/fabric/sdk/exception/PeerEventingServiceException.java @@ -16,7 +16,7 @@ package org.hyperledger.fabric.sdk.exception; -import org.hyperledger.fabric.protos.peer.PeerEvents; +import org.hyperledger.fabric.protos.peer.EventsPackage; public class PeerEventingServiceException extends TransactionException { @@ -36,11 +36,11 @@ public long getTimedOut() { * * @return Response error from peer if received otherwise null. */ - public PeerEvents.DeliverResponse getResp() { + public EventsPackage.DeliverResponse getResp() { return resp; } - private PeerEvents.DeliverResponse resp; + private EventsPackage.DeliverResponse resp; public PeerEventingServiceException(String message, Throwable parent) { super(message, parent); @@ -54,7 +54,7 @@ public PeerEventingServiceException(Throwable t) { super(t); } - public void setResponse(PeerEvents.DeliverResponse resp) { + public void setResponse(EventsPackage.DeliverResponse resp) { this.resp = resp; } diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/CSCCProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/CSCCProposalBuilder.java index 777bf302..299bdb84 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/CSCCProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/CSCCProposalBuilder.java @@ -15,12 +15,10 @@ package org.hyperledger.fabric.sdk.transaction; import org.hyperledger.fabric.protos.peer.Chaincode; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; -import static org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeSpec.Type.GOLANG; - public class CSCCProposalBuilder extends ProposalBuilder { private static final String CSCC_CHAIN_NAME = "cscc"; private static final Chaincode.ChaincodeID CHAINCODE_ID_CSCC = @@ -33,12 +31,9 @@ public CSCCProposalBuilder context(TransactionContext context) { } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { - - ccType(GOLANG); + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { + ccType(Chaincode.ChaincodeSpec.Type.GOLANG); chaincodeID(CHAINCODE_ID_CSCC); - return super.build(); - } } diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/InstallProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/InstallProposalBuilder.java index e00fa237..89ed8cfe 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/InstallProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/InstallProposalBuilder.java @@ -26,9 +26,8 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeDeploymentSpec; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeSpec.Type; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.Chaincode; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.sdk.TransactionRequest; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -96,7 +95,7 @@ public InstallProposalBuilder setChaincodeMetaInfLocation(File chaincodeMetaInfL } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { constructInstallProposal(); return super.build(); @@ -125,7 +124,7 @@ private void createNetModeTransaction() throws IOException { throw new IllegalArgumentException("Both chaincodeSource and chaincodeInputStream in InstallRequest were set. Specify one or the other"); } - final Type ccType; + final Chaincode.ChaincodeSpec.Type ccType; File projectSourceDir = null; String targetPathPrefix = null; String dplang; @@ -176,7 +175,7 @@ private void createNetModeTransaction() throws IOException { } dplang = "Go"; - ccType = Type.GOLANG; + ccType = Chaincode.ChaincodeSpec.Type.GOLANG; if (null != chaincodeSource) { projectSourceDir = Paths.get(chaincodeSource.toString(), "src", chaincodePath).toFile(); @@ -195,7 +194,7 @@ private void createNetModeTransaction() throws IOException { } dplang = "Java"; - ccType = Type.JAVA; + ccType = Chaincode.ChaincodeSpec.Type.JAVA; if (null != chaincodeSource) { targetPathPrefix = "src"; projectSourceDir = Paths.get(chaincodeSource.toString()).toFile(); @@ -213,7 +212,7 @@ private void createNetModeTransaction() throws IOException { } dplang = "Node"; - ccType = Type.NODE; + ccType = Chaincode.ChaincodeSpec.Type.NODE; if (null != chaincodeSource) { projectSourceDir = Paths.get(chaincodeSource.toString()).toFile(); @@ -266,7 +265,7 @@ private void createNetModeTransaction() throws IOException { } - final ChaincodeDeploymentSpec depspec = createDeploymentSpec( + final Chaincode.ChaincodeDeploymentSpec depspec = createDeploymentSpec( ccType, this.chaincodeName, this.chaincodePath, this.chaincodeVersion, null, data); // set args diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/InstantiateProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/InstantiateProposalBuilder.java index 24baefc1..37d1d939 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/InstantiateProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/InstantiateProposalBuilder.java @@ -23,8 +23,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.protos.peer.Chaincode; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeDeploymentSpec; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.sdk.ChaincodeCollectionConfiguration; import org.hyperledger.fabric.sdk.ChaincodeEndorsementPolicy; import org.hyperledger.fabric.sdk.TransactionRequest; @@ -104,7 +103,7 @@ public InstantiateProposalBuilder argss(List argList) { } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { constructInstantiateProposal(); return super.build(); @@ -149,7 +148,7 @@ private void createNetModeTransaction() throws InvalidArgumentException { throw new InvalidArgumentException("Requested chaincode type is not supported: " + chaincodeType); } - ChaincodeDeploymentSpec depspec = createDeploymentSpec(ccType, + Chaincode.ChaincodeDeploymentSpec depspec = createDeploymentSpec(ccType, chaincodeName, chaincodePath, chaincodeVersion, modlist, null); List argList = new ArrayList<>(); diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LSCCProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LSCCProposalBuilder.java index d9395d19..07ad7bae 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LSCCProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LSCCProposalBuilder.java @@ -14,7 +14,7 @@ package org.hyperledger.fabric.sdk.transaction; import org.hyperledger.fabric.protos.peer.Chaincode; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage.Proposal; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -30,7 +30,7 @@ public LSCCProposalBuilder context(TransactionContext context) { } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public Proposal build() throws ProposalException, InvalidArgumentException { chaincodeID(CHAINCODE_ID_LSCC); diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder.java index 70d8a707..10a25b11 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder.java @@ -15,7 +15,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.protos.common.Collection.CollectionConfigPackage; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -68,7 +68,7 @@ public static LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder newBuil } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { constructProposal(); return super.build(); diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleCheckCommitReadinessBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleCheckCommitReadinessBuilder.java index ecb3648c..3a963549 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleCheckCommitReadinessBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleCheckCommitReadinessBuilder.java @@ -13,7 +13,7 @@ import com.google.protobuf.ByteString; import org.hyperledger.fabric.protos.common.Collection; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -88,7 +88,7 @@ public void setInitRequired(boolean initRequired) { } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { List argList = new ArrayList<>(); argList.add(ByteString.copyFromUtf8("CheckCommitReadiness")); argList.add(builder.build().toByteString()); diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleCommitChaincodeDefinitionProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleCommitChaincodeDefinitionProposalBuilder.java index 3a3feee0..13bc15dd 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleCommitChaincodeDefinitionProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleCommitChaincodeDefinitionProposalBuilder.java @@ -14,8 +14,8 @@ import com.google.protobuf.ByteString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.hyperledger.fabric.protos.common.Collection.CollectionConfigPackage; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.common.Collection; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -42,35 +42,29 @@ public class LifecycleCommitChaincodeDefinitionProposalBuilder extends Lifecycle protected LifecycleCommitChaincodeDefinitionProposalBuilder() { super(); if (!Utils.isNullOrEmpty(config.getDefaultChaincodeEndorsementPlugin())) { - builder.setEndorsementPlugin(config.getDefaultChaincodeEndorsementPlugin()); } if (!Utils.isNullOrEmpty(config.getDefaultChaincodeValidationPlugin())) { - builder.setValidationPlugin(config.getDefaultChaincodeValidationPlugin()); } if (lifecycleInitRequiredDefault != null) { - builder.setInitRequired(lifecycleInitRequiredDefault); } } public static LifecycleCommitChaincodeDefinitionProposalBuilder newBuilder() { return new LifecycleCommitChaincodeDefinitionProposalBuilder(); - } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { - + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { constructProposal(); return super.build(); } public void chaincodeName(String name) { - builder.setName(name); } @@ -79,7 +73,6 @@ public void initRequired(boolean initRequired) { } public void version(String version) { - builder.setVersion(version); } @@ -92,9 +85,8 @@ public void setValidationParamter(ByteString validationParamter) { } //Optional - public void collectionsConfig(CollectionConfigPackage collectionsConfig) { + public void collectionsConfig(Collection.CollectionConfigPackage collectionsConfig) { builder.setCollections(collectionsConfig); - } void endorsementPolicy(byte[] endorsmentPolicyBytes) { @@ -102,17 +94,14 @@ void endorsementPolicy(byte[] endorsmentPolicyBytes) { } private void constructProposal() { - // set args final List argList = new ArrayList<>(); argList.add(ByteString.copyFromUtf8("CommitChaincodeDefinition")); argList.add(builder.build().toByteString()); args(argList); - } - public void chaincodeCollectionConfiguration(CollectionConfigPackage collectionConfigPackage) { - + public void chaincodeCollectionConfiguration(Collection.CollectionConfigPackage collectionConfigPackage) { builder.setCollections(collectionConfigPackage); } diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleInstallProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleInstallProposalBuilder.java index faa10877..2251fc52 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleInstallProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleInstallProposalBuilder.java @@ -24,7 +24,7 @@ import com.google.protobuf.ByteString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.TransactionRequest; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; @@ -87,7 +87,7 @@ public LifecycleInstallProposalBuilder setChaincodeMetaInfLocation(File chaincod } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { constructInstallProposal(); return super.build(); diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleProposalBuilder.java index 1db2c700..2b1f63df 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleProposalBuilder.java @@ -16,7 +16,7 @@ package org.hyperledger.fabric.sdk.transaction; import org.hyperledger.fabric.protos.peer.Chaincode; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -32,11 +32,8 @@ public LifecycleProposalBuilder context(TransactionContext context) { } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { - + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { chaincodeID(CHAINCODE_ID_LIFECYCLE); - return super.build(); - } } diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryChaincodeDefinitionBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryChaincodeDefinitionBuilder.java index 36ecb390..5b5abfaa 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryChaincodeDefinitionBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryChaincodeDefinitionBuilder.java @@ -12,7 +12,7 @@ import java.util.List; import com.google.protobuf.ByteString; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -39,7 +39,7 @@ public void setChaincodeName(String chaincodeName) { } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { List argList = new ArrayList<>(); argList.add(ByteString.copyFromUtf8("QueryChaincodeDefinition")); diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryChaincodeDefinitionsBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryChaincodeDefinitionsBuilder.java index 947e8b13..21aa7cf0 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryChaincodeDefinitionsBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryChaincodeDefinitionsBuilder.java @@ -12,7 +12,7 @@ import java.util.List; import com.google.protobuf.ByteString; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -33,7 +33,7 @@ public static LifecycleQueryChaincodeDefinitionsBuilder newBuilder() { } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { List argList = new ArrayList<>(); argList.add(ByteString.copyFromUtf8("QueryChaincodeDefinitions")); argList.add(Lifecycle.QueryChaincodeDefinitionsArgs.getDefaultInstance().toByteString()); diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryInstalledChaincodeBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryInstalledChaincodeBuilder.java index d1f3ad37..64422de2 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryInstalledChaincodeBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/LifecycleQueryInstalledChaincodeBuilder.java @@ -12,7 +12,7 @@ import java.util.List; import com.google.protobuf.ByteString; -import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.protos.peer.lifecycle.Lifecycle; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -45,10 +45,8 @@ public LifecycleQueryInstalledChaincodeBuilder setPackageId(String packageId) { } @Override - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { argList.add(Lifecycle.QueryInstalledChaincodeArgs.newBuilder().setPackageId(packageId).build().toByteString()); return super.build(); - } - } diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/ProposalBuilder.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/ProposalBuilder.java index c043c4d7..47529919 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/ProposalBuilder.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/ProposalBuilder.java @@ -19,20 +19,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import com.google.protobuf.ByteString; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.protos.common.Common; -import org.hyperledger.fabric.protos.common.Common.HeaderType; import org.hyperledger.fabric.protos.peer.Chaincode; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeInput; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeInvocationSpec; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeSpec; -import org.hyperledger.fabric.protos.peer.FabricProposal; -import org.hyperledger.fabric.protos.peer.FabricProposal.ChaincodeHeaderExtension; -import org.hyperledger.fabric.protos.peer.FabricProposal.ChaincodeProposalPayload; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.sdk.TransactionRequest; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.ProposalException; @@ -44,7 +37,6 @@ import static org.hyperledger.fabric.sdk.transaction.ProtoUtils.getSignatureHeaderAsByteString; public class ProposalBuilder { - private static final Log logger = LogFactory.getLog(ProposalBuilder.class); private static final boolean IS_DEBUG_LEVEL = logger.isDebugEnabled(); @@ -52,7 +44,7 @@ public class ProposalBuilder { protected List argList; protected TransactionContext context; protected TransactionRequest request; - protected ChaincodeSpec.Type ccType = ChaincodeSpec.Type.GOLANG; + protected Chaincode.ChaincodeSpec.Type ccType = Chaincode.ChaincodeSpec.Type.GOLANG; protected Map transientMap = null; // The channel that is being targeted . note blank string means no specific channel @@ -113,31 +105,30 @@ public ProposalBuilder request(TransactionRequest request) throws InvalidArgumen return this; } - public FabricProposal.Proposal build() throws ProposalException, InvalidArgumentException { + public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException { if (request != null && request.noChannelID()) { channelID = ""; } return createFabricProposal(channelID, chaincodeID, isInit); } - private FabricProposal.Proposal createFabricProposal(String channelID, Chaincode.ChaincodeID chaincodeID, boolean isInit) { + private ProposalPackage.Proposal createFabricProposal(String channelID, Chaincode.ChaincodeID chaincodeID, boolean isInit) { if (null == transientMap) { transientMap = Collections.emptyMap(); } if (IS_DEBUG_LEVEL) { - for (Entry tme : transientMap.entrySet()) { + for (Map.Entry tme : transientMap.entrySet()) { logger.debug(format("transientMap('%s', '%s'))", logString(tme.getKey()), logString(new String(tme.getValue(), UTF_8)))); } } - ChaincodeHeaderExtension chaincodeHeaderExtension = ChaincodeHeaderExtension.newBuilder() - .setChaincodeId(chaincodeID).build(); - Common.ChannelHeader chainHeader = createChannelHeader(HeaderType.ENDORSER_TRANSACTION, + ProposalPackage.ChaincodeHeaderExtension chaincodeHeaderExtension = ProposalPackage.ChaincodeHeaderExtension.newBuilder() + .setChaincodeId(chaincodeID).build(); + Common.ChannelHeader chainHeader = createChannelHeader(Common.HeaderType.ENDORSER_TRANSACTION, context.getTxID(), channelID, context.getEpoch(), context.getFabricTimestamp(), chaincodeHeaderExtension, null); - - ChaincodeInvocationSpec chaincodeInvocationSpec = createChaincodeInvocationSpec( + Chaincode.ChaincodeInvocationSpec chaincodeInvocationSpec = createChaincodeInvocationSpec( chaincodeID, ccType, isInit); @@ -145,16 +136,14 @@ private FabricProposal.Proposal createFabricProposal(String channelID, Chaincode //Convert to bytestring map. Map bsm = Collections.EMPTY_MAP; if (transientMap != null) { - bsm = new HashMap<>(transientMap.size()); - for (Entry tme : transientMap.entrySet()) { + for (Map.Entry tme : transientMap.entrySet()) { bsm.put(tme.getKey(), ByteString.copyFrom(tme.getValue())); - } } - ChaincodeProposalPayload payload = ChaincodeProposalPayload.newBuilder() + ProposalPackage.ChaincodeProposalPayload payload = ProposalPackage.ChaincodeProposalPayload.newBuilder() .setInput(chaincodeInvocationSpec.toByteString()) .putAllTransientMap(bsm) .build(); @@ -164,15 +153,13 @@ private FabricProposal.Proposal createFabricProposal(String channelID, Chaincode .setChannelHeader(chainHeader.toByteString()) .build(); - return FabricProposal.Proposal.newBuilder() + return ProposalPackage.Proposal.newBuilder() .setHeader(header.toByteString()) .setPayload(payload.toByteString()) .build(); - } - private ChaincodeInvocationSpec createChaincodeInvocationSpec(Chaincode.ChaincodeID chaincodeID, ChaincodeSpec.Type langType, boolean isInit) { - + private Chaincode.ChaincodeInvocationSpec createChaincodeInvocationSpec(Chaincode.ChaincodeID chaincodeID, Chaincode.ChaincodeSpec.Type langType, boolean isInit) { List allArgs = new ArrayList<>(); if (argList != null && argList.size() > 0) { @@ -198,10 +185,9 @@ private ChaincodeInvocationSpec createChaincodeInvocationSpec(Chaincode.Chaincod allArgs.add(ByteString.copyFrom(arg)); } } - } - if (IS_DEBUG_LEVEL) { + if (IS_DEBUG_LEVEL) { StringBuilder logout = new StringBuilder(1000); logout.append(format("ChaincodeInvocationSpec type: %s, chaincode name: %s, chaincode path: %s, chaincode version: %s, isInit: %b", @@ -216,27 +202,21 @@ private ChaincodeInvocationSpec createChaincodeInvocationSpec(Chaincode.Chaincod } logout.append(")"); - logger.debug(logout.toString()); - } - ChaincodeInput chaincodeInput = ChaincodeInput.newBuilder().addAllArgs(allArgs).setIsInit(isInit).build(); - - ChaincodeSpec chaincodeSpec = ChaincodeSpec.newBuilder() + Chaincode.ChaincodeInput chaincodeInput = Chaincode.ChaincodeInput.newBuilder().addAllArgs(allArgs).setIsInit(isInit).build(); + Chaincode.ChaincodeSpec chaincodeSpec = Chaincode.ChaincodeSpec.newBuilder() .setType(langType) .setChaincodeId(chaincodeID) .setInput(chaincodeInput) .build(); - - return ChaincodeInvocationSpec.newBuilder() + return Chaincode.ChaincodeInvocationSpec.newBuilder() .setChaincodeSpec(chaincodeSpec).build(); - } - public ProposalBuilder ccType(ChaincodeSpec.Type ccType) { + public ProposalBuilder ccType(Chaincode.ChaincodeSpec.Type ccType) { this.ccType = ccType; return this; } - } \ No newline at end of file diff --git a/src/main/java/org/hyperledger/fabric/sdk/transaction/ProtoUtils.java b/src/main/java/org/hyperledger/fabric/sdk/transaction/ProtoUtils.java index d8bf6035..86e31f77 100644 --- a/src/main/java/org/hyperledger/fabric/sdk/transaction/ProtoUtils.java +++ b/src/main/java/org/hyperledger/fabric/sdk/transaction/ProtoUtils.java @@ -28,22 +28,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperledger.fabric.protos.common.Common; -import org.hyperledger.fabric.protos.common.Common.ChannelHeader; -import org.hyperledger.fabric.protos.common.Common.Envelope; -import org.hyperledger.fabric.protos.common.Common.HeaderType; -import org.hyperledger.fabric.protos.common.Common.Payload; -import org.hyperledger.fabric.protos.common.Common.SignatureHeader; import org.hyperledger.fabric.protos.common.Configtx; import org.hyperledger.fabric.protos.msp.Identities; -import org.hyperledger.fabric.protos.orderer.Ab.SeekInfo; -import org.hyperledger.fabric.protos.orderer.Ab.SeekInfo.SeekBehavior; -import org.hyperledger.fabric.protos.orderer.Ab.SeekPosition; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeDeploymentSpec; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeID; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeInput; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeSpec; -import org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeSpec.Type; -import org.hyperledger.fabric.protos.peer.FabricProposal.ChaincodeHeaderExtension; +import org.hyperledger.fabric.protos.orderer.Ab; +import org.hyperledger.fabric.protos.peer.Chaincode; +import org.hyperledger.fabric.protos.peer.ProposalPackage; import org.hyperledger.fabric.sdk.Enrollment; import org.hyperledger.fabric.sdk.User; import org.hyperledger.fabric.sdk.exception.CryptoException; @@ -86,10 +75,9 @@ private ProtoUtils() { * @param tlsCertHash * @return a new chain header. */ - public static ChannelHeader createChannelHeader(HeaderType type, String txID, String channelID, long epoch, - Timestamp timeStamp, ChaincodeHeaderExtension chaincodeHeaderExtension, + public static Common.ChannelHeader createChannelHeader(Common.HeaderType type, String txID, String channelID, long epoch, + Timestamp timeStamp, ProposalPackage.ChaincodeHeaderExtension chaincodeHeaderExtension, byte[] tlsCertHash) { - if (isDebugLevel) { String tlschs = ""; if (tlsCertHash != null) { @@ -98,10 +86,9 @@ public static ChannelHeader createChannelHeader(HeaderType type, String txID, St } logger.debug(format("ChannelHeader: type: %s, version: 1, Txid: %s, channelId: %s, epoch %d, clientTLSCertificate digest: %s", type.name(), txID, channelID, epoch, tlschs)); - } - ChannelHeader.Builder ret = ChannelHeader.newBuilder() + Common.ChannelHeader.Builder ret = Common.ChannelHeader.newBuilder() .setType(type.getNumber()) .setVersion(1) .setTxId(txID) @@ -117,34 +104,32 @@ public static ChannelHeader createChannelHeader(HeaderType type, String txID, St } return ret.build(); - } - public static ChaincodeDeploymentSpec createDeploymentSpec(Type ccType, String name, String chaincodePath, + public static Chaincode.ChaincodeDeploymentSpec createDeploymentSpec(Chaincode.ChaincodeSpec.Type ccType, String name, String chaincodePath, String chaincodeVersion, List args, byte[] codePackage) { - - ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(name).setVersion(chaincodeVersion); + Chaincode.ChaincodeID.Builder chaincodeIDBuilder = Chaincode.ChaincodeID.newBuilder().setName(name).setVersion(chaincodeVersion); if (chaincodePath != null) { chaincodeIDBuilder = chaincodeIDBuilder.setPath(chaincodePath); } - ChaincodeID chaincodeID = chaincodeIDBuilder.build(); + Chaincode.ChaincodeID chaincodeID = chaincodeIDBuilder.build(); // build chaincodeInput List argList = new ArrayList<>(args == null ? 0 : args.size()); if (args != null && args.size() != 0) { - for (String arg : args) { argList.add(ByteString.copyFrom(arg.getBytes(UTF_8))); } - } - ChaincodeInput chaincodeInput = ChaincodeInput.newBuilder().addAllArgs(argList).setIsInit(false).build(); + Chaincode.ChaincodeInput chaincodeInput = Chaincode.ChaincodeInput.newBuilder().addAllArgs(argList).setIsInit(false).build(); // Construct the ChaincodeSpec - ChaincodeSpec chaincodeSpec = ChaincodeSpec.newBuilder().setType(ccType).setChaincodeId(chaincodeID) + Chaincode.ChaincodeSpec chaincodeSpec = Chaincode.ChaincodeSpec.newBuilder() + .setType(ccType) + .setChaincodeId(chaincodeID) .setInput(chaincodeInput) .build(); @@ -168,59 +153,47 @@ public static ChaincodeDeploymentSpec createDeploymentSpec(Type ccType, String n } sb.append(")"); - logger.debug(sb.toString()); - } - ChaincodeDeploymentSpec.Builder chaincodeDeploymentSpecBuilder = ChaincodeDeploymentSpec - .newBuilder().setChaincodeSpec(chaincodeSpec) //.setEffectiveDate(context.getFabricTimestamp()) - .setExecEnv(ChaincodeDeploymentSpec.ExecutionEnvironment.DOCKER); + Chaincode.ChaincodeDeploymentSpec.Builder chaincodeDeploymentSpecBuilder = Chaincode.ChaincodeDeploymentSpec.newBuilder() +// .setEffectiveDate(context.getFabricTimestamp()) +// .setExecEnv(ChaincodeDeploymentSpec.ExecutionEnvironment.DOCKER) + .setChaincodeSpec(chaincodeSpec); if (codePackage != null) { chaincodeDeploymentSpecBuilder.setCodePackage(ByteString.copyFrom(codePackage)); - } return chaincodeDeploymentSpecBuilder.build(); - } public static ByteString getSignatureHeaderAsByteString(TransactionContext transactionContext) { - return getSignatureHeaderAsByteString(transactionContext.getUser(), transactionContext); } public static ByteString getSignatureHeaderAsByteString(User user, TransactionContext transactionContext) { - final Identities.SerializedIdentity identity = transactionContext.getSerializedIdentity(); if (isDebugLevel) { - Enrollment enrollment = user.getEnrollment(); String cert = enrollment.getCert(); logger.debug(format(" User: %s Certificate: %s", user.getName(), cert == null ? "null" : toHexString(cert.getBytes(UTF_8)))); if (enrollment instanceof X509Enrollment) { if (null == suite) { - try { suite = CryptoSuite.Factory.getCryptoSuite(); } catch (Exception e) { //best try. } - } if (null != suite && suite instanceof CryptoPrimitives) { - CryptoPrimitives cp = (CryptoPrimitives) suite; byte[] der = cp.certificateToDER(cert); if (null != der && der.length > 0) { - cert = toHexString(suite.hash(der)); - } - } } @@ -232,16 +205,15 @@ public static ByteString getSignatureHeaderAsByteString(User user, TransactionCo toHexString(cert) )); } - } - return SignatureHeader.newBuilder() + + return Common.SignatureHeader.newBuilder() .setCreator(identity.toByteString()) .setNonce(transactionContext.getNonce()) .build().toByteString(); } public static Identities.SerializedIdentity createSerializedIdentity(User user) { - return Identities.SerializedIdentity.newBuilder() .setIdBytes(ByteString.copyFromUtf8(user.getEnrollment().getCert())) .setMspid(user.getMspId()).build(); @@ -258,19 +230,17 @@ public static Date getDateFromTimestamp(Timestamp timestamp) { } static Timestamp getTimestampFromDate(Date date) { - long millis = date.getTime(); return Timestamp.newBuilder().setSeconds(millis / 1000) .setNanos((int) ((millis % 1000) * 1000000)).build(); } - public static Envelope createSeekInfoEnvelope(TransactionContext transactionContext, SeekInfo seekInfo, byte[] tlsCertHash) throws CryptoException, InvalidArgumentException { - - ChannelHeader seekInfoHeader = createChannelHeader(Common.HeaderType.DELIVER_SEEK_INFO, + public static Common.Envelope createSeekInfoEnvelope(TransactionContext transactionContext, Ab.SeekInfo seekInfo, byte[] tlsCertHash) throws CryptoException, InvalidArgumentException { + Common.ChannelHeader seekInfoHeader = createChannelHeader(Common.HeaderType.DELIVER_SEEK_INFO, transactionContext.getTxID(), transactionContext.getChannelID(), transactionContext.getEpoch(), transactionContext.getFabricTimestamp(), null, tlsCertHash); - SignatureHeader signatureHeader = SignatureHeader.newBuilder() + Common.SignatureHeader signatureHeader = Common.SignatureHeader.newBuilder() .setCreator(transactionContext.getIdentity().toByteString()) .setNonce(transactionContext.getNonce()) .build(); @@ -280,33 +250,29 @@ public static Envelope createSeekInfoEnvelope(TransactionContext transactionCont .setChannelHeader(seekInfoHeader.toByteString()) .build(); - Payload seekPayload = Payload.newBuilder() + Common.Payload seekPayload = Common.Payload.newBuilder() .setHeader(seekHeader) .setData(seekInfo.toByteString()) .build(); - return Envelope.newBuilder().setSignature(transactionContext.signByteString(seekPayload.toByteArray())) + return Common.Envelope.newBuilder().setSignature(transactionContext.signByteString(seekPayload.toByteArray())) .setPayload(seekPayload.toByteString()) .build(); - } - public static Envelope createSeekInfoEnvelope(TransactionContext transactionContext, SeekPosition startPosition, - SeekPosition stopPosition, - SeekBehavior seekBehavior, byte[] tlsCertHash) throws CryptoException, InvalidArgumentException { - - return createSeekInfoEnvelope(transactionContext, SeekInfo.newBuilder() + public static Common.Envelope createSeekInfoEnvelope(TransactionContext transactionContext, Ab.SeekPosition startPosition, + Ab.SeekPosition stopPosition, + Ab.SeekInfo.SeekBehavior seekBehavior, byte[] tlsCertHash) throws CryptoException, InvalidArgumentException { + return createSeekInfoEnvelope(transactionContext, Ab.SeekInfo.newBuilder() .setStart(startPosition) .setStop(stopPosition) .setBehavior(seekBehavior) .build(), tlsCertHash); - } // not an api public static boolean computeUpdate(String channelId, Configtx.Config original, Configtx.Config update, Configtx.ConfigUpdate.Builder configUpdateBuilder) { - Configtx.ConfigGroup.Builder readSetBuilder = Configtx.ConfigGroup.newBuilder(); Configtx.ConfigGroup.Builder writeSetBuilder = Configtx.ConfigGroup.newBuilder(); @@ -314,17 +280,14 @@ public static boolean computeUpdate(String channelId, Configtx.Config original, configUpdateBuilder.setReadSet(readSetBuilder.build()) .setWriteSet(writeSetBuilder.build()) .setChannelId(channelId); - return true; } return false; - } private static boolean computeGroupUpdate(Configtx.ConfigGroup original, Configtx.ConfigGroup updated, Configtx.ConfigGroup.Builder readSetBuilder, Configtx.ConfigGroup.Builder writeSetBuilder) { - Map readSetPolicies = new HashMap<>(); Map writeSetPolicies = new HashMap<>(); Map sameSetPolicies = new HashMap<>(); @@ -350,13 +313,10 @@ private static boolean computeGroupUpdate(Configtx.ConfigGroup original, Configt // nothing changed. if (writeSetValues.isEmpty() && writeSetPolicies.isEmpty() && writeSetGroups.isEmpty() && readSetGroups.isEmpty()) { - readSetBuilder.setVersion(original.getVersion()); writeSetBuilder.setVersion(original.getVersion()); - return false; } else { - readSetBuilder.setVersion(original.getVersion()) .putAllGroups(readSetGroups); writeSetBuilder.setVersion(original.getVersion()) @@ -364,9 +324,7 @@ private static boolean computeGroupUpdate(Configtx.ConfigGroup original, Configt .putAllValues(writeSetValues) .putAllGroups(writeSetGroups); return true; - } - } for (Map.Entry i : sameSetPolicies.entrySet()) { @@ -374,7 +332,6 @@ private static boolean computeGroupUpdate(Configtx.ConfigGroup original, Configt final Configtx.ConfigPolicy value = i.getValue(); readSetPolicies.put(name, value); writeSetPolicies.put(name, value); - } for (Map.Entry i : sameSetValues.entrySet()) { @@ -382,7 +339,6 @@ private static boolean computeGroupUpdate(Configtx.ConfigGroup original, Configt final Configtx.ConfigValue value = i.getValue(); readSetValues.put(name, value); writeSetValues.put(name, value); - } for (Map.Entry i : sameSetGroups.entrySet()) { @@ -390,7 +346,6 @@ private static boolean computeGroupUpdate(Configtx.ConfigGroup original, Configt final Configtx.ConfigGroup value = i.getValue(); readSetGroups.put(name, value); writeSetGroups.put(name, value); - } readSetBuilder.setVersion(original.getVersion()) @@ -417,7 +372,6 @@ public static boolean computeGroupsMapUpdate(Map o if (!updated.containsKey(groupName) || null == updated.get(groupName)) { updatedMembers = true; //missing from updated ie deleted. - } else { final Configtx.ConfigGroup updatedGroup = updated.get(groupName); @@ -426,14 +380,11 @@ public static boolean computeGroupsMapUpdate(Map o if (!computeGroupUpdate(originalGroup, updatedGroup, readSetBuilder, writeSetBuilder)) { sameSet.put(groupName, readSetBuilder.build()); - } else { readSet.put(groupName, readSetBuilder.build()); writeSet.put(groupName, writeSetBuilder.build()); } - } - } for (Map.Entry i : updated.entrySet()) { @@ -452,12 +403,8 @@ public static boolean computeGroupsMapUpdate(Map o .putAllPolicies(writeSetBuilder.getPoliciesMap()) .putAllValues(writeSetBuilder.getValuesMap()) .putAllGroups(writeSetBuilder.getGroupsMap()) - .build() - - ); - + .build()); } - } return updatedMembers; @@ -465,7 +412,6 @@ public static boolean computeGroupsMapUpdate(Map o private static boolean computeValuesMapUpdate(Map original, Map updated, Map writeSet, Map sameSet) { - boolean updatedMembers = false; for (Map.Entry i : original.entrySet()) { @@ -473,27 +419,20 @@ private static boolean computeValuesMapUpdate(Map final Configtx.ConfigValue originalValue = i.getValue(); if (!updated.containsKey(valueName) || null == updated.get(valueName)) { updatedMembers = true; //missing from updated ie deleted. - } else { // is in both... - final Configtx.ConfigValue updatedValue = updated.get(valueName); if (originalValue.getModPolicy().equals(updatedValue.getModPolicy()) && originalValue.getValue().equals(updatedValue.getValue())) { //same value sameSet.put(valueName, Configtx.ConfigValue.newBuilder().setVersion(originalValue.getVersion()).build()); - } else { // new value put in writeset. - writeSet.put(valueName, Configtx.ConfigValue.newBuilder() .setVersion(originalValue.getVersion() + 1) .setModPolicy(updatedValue.getModPolicy()) .setValue(updatedValue.getValue()) .build()); - } - } - } for (Map.Entry i : updated.entrySet()) { @@ -501,25 +440,20 @@ private static boolean computeValuesMapUpdate(Map final Configtx.ConfigValue updatedValue = i.getValue(); if (!original.containsKey(valueName) || null == original.get(valueName)) { - updatedMembers = true; - writeSet.put(valueName, Configtx.ConfigValue.newBuilder() .setVersion(0) .setModPolicy(updatedValue.getModPolicy()) .setValue(updatedValue.getValue()) .build()); - } } return updatedMembers; - } private static boolean computePoliciesMapUpdate(Map original, Map updated, Map writeSet, Map sameSet) { - boolean updatedMembers = false; for (Map.Entry i : original.entrySet()) { @@ -527,27 +461,19 @@ private static boolean computePoliciesMapUpdate(Map i : updated.entrySet()) { @@ -555,15 +481,12 @@ private static boolean computePoliciesMapUpdate(Map endorsements; + private ProposalPackage.Proposal chaincodeProposal; + private Collection endorsements; private ByteString proposalResponsePayload; public static TransactionBuilder newBuilder() { return new TransactionBuilder(); } - public TransactionBuilder chaincodeProposal(FabricProposal.Proposal chaincodeProposal) { + public TransactionBuilder chaincodeProposal(ProposalPackage.Proposal chaincodeProposal) { this.chaincodeProposal = chaincodeProposal; return this; } - public TransactionBuilder endorsements(Collection endorsements) { + public TransactionBuilder endorsements(Collection endorsements) { this.endorsements = endorsements; return this; } @@ -65,30 +65,29 @@ public Common.Payload build() throws InvalidProtocolBufferException { } - private Common.Payload createTransactionCommonPayload(FabricProposal.Proposal chaincodeProposal, ByteString proposalResponsePayload, - Collection endorsements) throws InvalidProtocolBufferException { + private Common.Payload createTransactionCommonPayload(ProposalPackage.Proposal chaincodeProposal, ByteString proposalResponsePayload, + Collection endorsements) throws InvalidProtocolBufferException { - FabricTransaction.ChaincodeEndorsedAction.Builder chaincodeEndorsedActionBuilder = FabricTransaction.ChaincodeEndorsedAction.newBuilder(); + TransactionPackage.ChaincodeEndorsedAction.Builder chaincodeEndorsedActionBuilder = TransactionPackage.ChaincodeEndorsedAction.newBuilder(); chaincodeEndorsedActionBuilder.setProposalResponsePayload(proposalResponsePayload); chaincodeEndorsedActionBuilder.addAllEndorsements(endorsements); //ChaincodeActionPayload - FabricTransaction.ChaincodeActionPayload.Builder chaincodeActionPayloadBuilder = FabricTransaction.ChaincodeActionPayload.newBuilder(); + TransactionPackage.ChaincodeActionPayload.Builder chaincodeActionPayloadBuilder = TransactionPackage.ChaincodeActionPayload.newBuilder(); chaincodeActionPayloadBuilder.setAction(chaincodeEndorsedActionBuilder.build()); //We need to remove any transient fields - they are not part of what the peer uses to calculate hash. - FabricProposal.ChaincodeProposalPayload.Builder chaincodeProposalPayloadNoTransBuilder = FabricProposal.ChaincodeProposalPayload.newBuilder(); + ProposalPackage.ChaincodeProposalPayload.Builder chaincodeProposalPayloadNoTransBuilder = ProposalPackage.ChaincodeProposalPayload.newBuilder(); chaincodeProposalPayloadNoTransBuilder.mergeFrom(chaincodeProposal.getPayload()); chaincodeProposalPayloadNoTransBuilder.clearTransientMap(); chaincodeActionPayloadBuilder.setChaincodeProposalPayload(chaincodeProposalPayloadNoTransBuilder.build().toByteString()); - FabricTransaction.TransactionAction.Builder transactionActionBuilder = FabricTransaction.TransactionAction.newBuilder(); + TransactionPackage.TransactionAction.Builder transactionActionBuilder = TransactionPackage.TransactionAction.newBuilder(); Common.Header header = Common.Header.parseFrom(chaincodeProposal.getHeader()); if (config.extraLogLevel(10)) { - if (null != diagnosticFileDumper) { StringBuilder sb = new StringBuilder(10000); sb.append("transaction header bytes:" + Arrays.toString(header.toByteArray())); @@ -101,7 +100,7 @@ private Common.Payload createTransactionCommonPayload(FabricProposal.Proposal ch transactionActionBuilder.setHeader(header.getSignatureHeader()); - FabricTransaction.ChaincodeActionPayload chaincodeActionPayload = chaincodeActionPayloadBuilder.build(); + TransactionPackage.ChaincodeActionPayload chaincodeActionPayload = chaincodeActionPayloadBuilder.build(); if (config.extraLogLevel(10)) { if (null != diagnosticFileDumper) { logger.trace("transactionActionBuilder.setPayload: " + @@ -111,7 +110,7 @@ private Common.Payload createTransactionCommonPayload(FabricProposal.Proposal ch transactionActionBuilder.setPayload(chaincodeActionPayload.toByteString()); //Transaction - FabricTransaction.Transaction.Builder transactionBuilder = FabricTransaction.Transaction.newBuilder(); + TransactionPackage.Transaction.Builder transactionBuilder = TransactionPackage.Transaction.newBuilder(); transactionBuilder.addActions(transactionActionBuilder.build()); Common.Payload.Builder payload = Common.Payload.newBuilder(); @@ -119,7 +118,5 @@ private Common.Payload createTransactionCommonPayload(FabricProposal.Proposal ch payload.setData(transactionBuilder.build().toByteString()); return payload.build(); - } - } diff --git a/src/main/proto/common/collection.proto b/src/main/proto/common/collection.proto index 99363226..77283d56 100644 --- a/src/main/proto/common/collection.proto +++ b/src/main/proto/common/collection.proto @@ -1,18 +1,16 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -import "common/policies.proto"; - -option go_package = "github.com/hyperledger/fabric/protos/common"; +option go_package = "github.com/hyperledger/fabric-protos-go/common"; option java_package = "org.hyperledger.fabric.protos.common"; package common; +import "common/policies.proto"; + // CollectionConfigPackage represents an array of CollectionConfig // messages; the extra struct is required because repeated oneof is // forbidden by the protobuf syntax @@ -75,10 +73,11 @@ message CollectionPolicyConfig { // Later, the SignaturePolicy will be replaced by a Policy. // Policy policy = 1; // A reference to a Policy is planned to be added later. - // string reference = 2; +// string reference = 2; } } + // CollectionCriteria defines an element of a private data that corresponds // to a certain transaction and collection message CollectionCriteria { diff --git a/src/main/proto/common/common.proto b/src/main/proto/common/common.proto index 2aeb8e68..ca18f4a6 100644 --- a/src/main/proto/common/common.proto +++ b/src/main/proto/common/common.proto @@ -1,28 +1,16 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/hyperledger/fabric/protos/common"; +option go_package = "github.com/hyperledger/fabric-protos-go/common"; option java_package = "org.hyperledger.fabric.protos.common"; package common; +import "google/protobuf/timestamp.proto"; + // These status codes are intended to resemble selected HTTP status codes enum Status { UNKNOWN = 0; @@ -37,34 +25,33 @@ enum Status { } enum HeaderType { - // Prevent removed tag re-use - // Uncomment after fabric-baseimage moves to 3.5.1 - // reserved 7; - // reserved "PEER_RESOURCE_UPDATE"; - - MESSAGE = 0; // Used for messages which are signed but opaque - CONFIG = 1; // Used for messages which express the channel config - CONFIG_UPDATE = 2; // Used for transactions which update the channel config - ENDORSER_TRANSACTION = 3; // Used by the SDK to submit endorser based transactions - ORDERER_TRANSACTION = 4; // Used internally by the orderer for management - DELIVER_SEEK_INFO = 5; // Used as the type for Envelope messages submitted to instruct the Deliver API to seek - CHAINCODE_PACKAGE = 6; // Used for packaging chaincode artifacts for install - PEER_ADMIN_OPERATION = 8; // Used for invoking an administrative operation on a peer - TOKEN_TRANSACTION = 9; // Used to denote transactions that invoke token management operations + reserved 7, 9; + reserved "PEER_RESOURCE_UPDATE", "TOKEN_TRANSACTION"; + + MESSAGE = 0; // Used for messages which are signed but opaque + CONFIG = 1; // Used for messages which express the channel config + CONFIG_UPDATE = 2; // Used for transactions which update the channel config + ENDORSER_TRANSACTION = 3; // Used by the SDK to submit endorser based transactions + ORDERER_TRANSACTION = 4; // Used internally by the orderer for management + DELIVER_SEEK_INFO = 5; // Used as the type for Envelope messages submitted to instruct the Deliver API to seek + CHAINCODE_PACKAGE = 6; // Used for packaging chaincode artifacts for install + PEER_ADMIN_OPERATION = 8; // Used for invoking an administrative operation on a peer } // This enum enlists indexes of the block metadata array enum BlockMetadataIndex { - SIGNATURES = 0; // Block metadata array position for block signatures - LAST_CONFIG = 1; // Block metadata array position to store last configuration block sequence number - TRANSACTIONS_FILTER = 2; // Block metadata array position to store serialized bit array filter of invalid transactions - ORDERER = 3; // Block metadata array position to store operational metadata for orderers - // e.g. For Kafka, this is where we store the last offset written to the local ledger. + SIGNATURES = 0; // Block metadata array position for block signatures + LAST_CONFIG = 1; // Block metadata array position to store last configuration block sequence number + TRANSACTIONS_FILTER = 2; // Block metadata array position to store serialized bit array filter of invalid transactions + ORDERER = 3 [deprecated=true]; /* Block metadata array position to store operational metadata for orderers + e.g. For Kafka, this is where we store the last offset written to the local ledger */ + COMMIT_HASH = 4; /* Block metadata array position to store the hash of TRANSACTIONS_FILTER, State Updates, + and the COMMIT_HASH of the previous block */ } // LastConfig is the encoded value for the Metadata message which is encoded in the LAST_CONFIGURATION block metadata index message LastConfig { - uint64 index = 1; + uint64 index = 1; } // Metadata is a common structure to be used to encode block metadata diff --git a/src/main/proto/common/configtx.proto b/src/main/proto/common/configtx.proto index 884d2119..188848e6 100644 --- a/src/main/proto/common/configtx.proto +++ b/src/main/proto/common/configtx.proto @@ -1,19 +1,17 @@ -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -import "common/common.proto"; -import "common/policies.proto"; - -option go_package = "github.com/hyperledger/fabric/protos/common"; +option go_package = "github.com/hyperledger/fabric-protos-go/common"; option java_package = "org.hyperledger.fabric.protos.common"; package common; +import "common/common.proto"; +import "common/policies.proto"; + // ConfigEnvelope is designed to contain _all_ configuration for a chain with no dependency // on previous configuration transactions. // @@ -80,9 +78,9 @@ message ConfigUpdate { reserved 4; reserved "type"; - string channel_id = 1; // Which channel this config update is for - ConfigGroup read_set = 2; // ReadSet explicitly lists the portion of the config which was read, this should be sparse with only Version set - ConfigGroup write_set = 3; // WriteSet lists the portion of the config which was written, this should included updated Versions + string channel_id = 1; // Which channel this config update is for + ConfigGroup read_set = 2; // ReadSet explicitly lists the portion of the config which was read, this should be sparse with only Version set + ConfigGroup write_set = 3; // WriteSet lists the portion of the config which was written, this should included updated Versions map isolated_data = 5; // Data which is not to be reflected in the resulting Config, but is still needed for some other purpose. For instance, rscc_seed_data } diff --git a/src/main/proto/common/configuration.proto b/src/main/proto/common/configuration.proto index e61945c2..a60d8754 100644 --- a/src/main/proto/common/configuration.proto +++ b/src/main/proto/common/configuration.proto @@ -1,22 +1,10 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/common"; +option go_package = "github.com/hyperledger/fabric-protos-go/common"; option java_package = "org.hyperledger.fabric.protos.common"; package common; @@ -86,5 +74,4 @@ message Capabilities { // message rather than a constant, so that we may extend capabilities with other fields // if the need arises in the future. For the time being, a capability being in the // capabilities map requires that that capability be supported. -message Capability { -} \ No newline at end of file +message Capability { } diff --git a/src/main/proto/common/ledger.proto b/src/main/proto/common/ledger.proto index a9b99711..ee5b1ba7 100644 --- a/src/main/proto/common/ledger.proto +++ b/src/main/proto/common/ledger.proto @@ -1,21 +1,10 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/common"; +option go_package = "github.com/hyperledger/fabric-protos-go/common"; option java_package = "org.hyperledger.fabric.protos.common"; package common; @@ -26,5 +15,4 @@ message BlockchainInfo { uint64 height = 1; bytes currentBlockHash = 2; bytes previousBlockHash = 3; - } diff --git a/src/main/proto/common/policies.proto b/src/main/proto/common/policies.proto index cef1b8ea..8ac81d09 100644 --- a/src/main/proto/common/policies.proto +++ b/src/main/proto/common/policies.proto @@ -1,28 +1,16 @@ -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -import "msp/msp_principal.proto"; - -option go_package = "github.com/hyperledger/fabric/protos/common"; +option go_package = "github.com/hyperledger/fabric-protos-go/common"; option java_package = "org.hyperledger.fabric.protos.common"; package common; +import "msp/msp_principal.proto"; + // Policy expresses a policy which the orderer can evaluate, because there has been some desire expressed to support // multiple policy engines, this is typed as a oneof for now message Policy { diff --git a/src/main/proto/discovery/protocol.proto b/src/main/proto/discovery/protocol.proto index f4fa3113..d2b29bdc 100644 --- a/src/main/proto/discovery/protocol.proto +++ b/src/main/proto/discovery/protocol.proto @@ -1,18 +1,17 @@ -// Copyright IBM Corp. All Rights Reserved. +// Copyright the Hyperledger Fabric contributors. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 -// -syntax = "proto3"; -import "gossip/message.proto"; -import "msp/msp_config.proto"; -import "msp/identities.proto"; +syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/discovery"; +option go_package = "github.com/hyperledger/fabric-protos-go/discovery"; option java_package = "org.hyperledger.fabric.protos.discovery"; package discovery; +import "gossip/message.proto"; +import "msp/msp_config.proto"; + // Discovery defines a service that serves information about the fabric network // like which peers, orderers, chaincodes, etc. service Discovery { @@ -26,7 +25,7 @@ service Discovery { // can be extracted from the authentication field of type AuthInfo // in the Request itself after deserializing it. message SignedRequest { - bytes payload = 1; + bytes payload = 1; bytes signature = 2; } @@ -232,5 +231,3 @@ message Endpoint { string host = 1; uint32 port = 2; } - - diff --git a/src/main/proto/gossip/message.proto b/src/main/proto/gossip/message.proto index 63bc820c..f567db5c 100644 --- a/src/main/proto/gossip/message.proto +++ b/src/main/proto/gossip/message.proto @@ -1,10 +1,10 @@ -// Copyright IBM Corp. All Rights Reserved. +// Copyright the Hyperledger Fabric contributors. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 -// + syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/gossip"; +option go_package = "github.com/hyperledger/fabric-protos-go/gossip"; option java_package = "org.hyperledger.fabric.protos.gossip"; package gossip; @@ -19,14 +19,15 @@ service Gossip { // Ping is used to probe a remote peer's aliveness rpc Ping (Empty) returns (Empty); - } +} + // Envelope contains a marshalled // GossipMessage and a signature over it. // It may also contain a SecretEnvelope // which is a marshalled Secret message Envelope { - bytes payload = 1; + bytes payload = 1; bytes signature = 2; SecretEnvelope secret_envelope = 3; } @@ -37,7 +38,7 @@ message Envelope { // that signed the Envelope the SecretEnvelope // came with message SecretEnvelope { - bytes payload = 1; + bytes payload = 1; bytes signature = 2; } @@ -55,7 +56,7 @@ message GossipMessage { // used mainly for testing, but will might be used in the future // for ensuring message delivery by acking - uint64 nonce = 1; + uint64 nonce = 1; // The channel of the message. // Some GossipMessages may set this to nil, because @@ -64,12 +65,12 @@ message GossipMessage { enum Tag { - UNDEFINED = 0; - EMPTY = 1; - ORG_ONLY = 2; - CHAN_ONLY = 3; + UNDEFINED = 0; + EMPTY = 1; + ORG_ONLY = 2; + CHAN_ONLY = 3; CHAN_AND_ORG = 4; - CHAN_OR_ORG = 5; + CHAN_OR_ORG = 5; } // determines to which peers it is allowed @@ -87,9 +88,9 @@ message GossipMessage { // Used for push&pull GossipHello hello = 9; - DataDigest data_dig = 10; + DataDigest data_dig = 10; DataRequest data_req = 11; - DataUpdate data_update = 12; + DataUpdate data_update = 12; // Empty message, used for pinging Empty empty = 13; @@ -137,12 +138,12 @@ message GossipMessage { // to other peers message StateInfo { PeerTime timestamp = 2; - bytes pki_id = 3; + bytes pki_id = 3; // channel_MAC is an authentication code that proves // that the peer that sent this message knows // the name of the channel. - bytes channel_MAC = 4; + bytes channel_MAC = 4; Properties properties = 5; } @@ -164,67 +165,68 @@ message StateInfoPullRequest { // channel_MAC is an authentication code that proves // that the peer that sent this message knows // the name of the channel. - bytes channel_MAC = 1; + bytes channel_MAC = 1; } // ConnEstablish is the message used for the gossip handshake // Whenever a peer connects to another peer, it handshakes // with it by sending this message that proves its identity message ConnEstablish { - bytes pki_id = 1; - bytes identity = 2; - bytes tls_cert_hash = 3; + bytes pki_id = 1; + bytes identity = 2; + bytes tls_cert_hash = 3; } // PeerIdentity defines the identity of the peer // Used to make other peers learn of the identity // of a certain peer message PeerIdentity { - bytes pki_id = 1; - bytes cert = 2; - bytes metadata = 3; + bytes pki_id = 1; + bytes cert = 2; + bytes metadata = 3; } // Messages related to pull mechanism enum PullMsgType { - UNDEFINED = 0; - BLOCK_MSG = 1; - IDENTITY_MSG = 2; + UNDEFINED = 0; + BLOCK_MSG = 1; + IDENTITY_MSG = 2; } // DataRequest is a message used for a peer to request // certain data blocks from a remote peer message DataRequest { - uint64 nonce = 1; - repeated bytes digests = 2; - PullMsgType msg_type = 3; + uint64 nonce = 1; + repeated bytes digests = 2; + PullMsgType msg_type = 3; } // GossipHello is the message that is used for the peer to initiate // a pull round with another peer message GossipHello { - uint64 nonce = 1; - bytes metadata = 2; + uint64 nonce = 1; + bytes metadata = 2; PullMsgType msg_type = 3; } // DataUpdate is the final message in the pull phase // sent from the receiver to the initiator message DataUpdate { - uint64 nonce = 1; - repeated Envelope data = 2; - PullMsgType msg_type = 3; + uint64 nonce = 1; + repeated Envelope data = 2; + PullMsgType msg_type = 3; } // DataDigest is the message sent from the receiver peer // to the initator peer and contains the data items it has message DataDigest { - uint64 nonce = 1; - repeated bytes digests = 2; // Maybe change this to bitmap later on - PullMsgType msg_type = 3; + uint64 nonce = 1; + repeated bytes digests = 2; // Maybe change this to bitmap later on + PullMsgType msg_type = 3; } + // Ledger block messages // DataMessage is the message that contains a block @@ -241,8 +243,8 @@ message PrivateDataMessage { // Payload contains a block message Payload { - uint64 seq_num = 1; - bytes data = 2; + uint64 seq_num = 1; + bytes data = 2; repeated bytes private_data = 3; } @@ -250,11 +252,11 @@ message Payload { // data with collection name to enable routing // based on collection partitioning message PrivatePayload { - string collection_name = 1; - string namespace = 2; - string tx_id = 3; - bytes private_rwset = 4; - uint64 private_sim_height = 5; + string collection_name = 1; + string namespace = 2; + string tx_id = 3; + bytes private_rwset = 4; + uint64 private_sim_height = 5; common.CollectionConfigPackage collection_configs = 6; } @@ -263,15 +265,15 @@ message PrivatePayload { // AliveMessage is sent to inform remote peers // of a peer's existence and activity message AliveMessage { - Member membership = 1; + Member membership = 1; PeerTime timestamp = 2; - bytes identity = 4; + bytes identity = 4; } // Leadership Message is sent during leader election to inform // remote peers about intent of peer to proclaim itself as leader message LeadershipMessage { - bytes pki_id = 1; + bytes pki_id = 1; PeerTime timestamp = 2; bool is_declaration = 3; } @@ -286,26 +288,26 @@ message PeerTime { // from a remote peer message MembershipRequest { Envelope self_information = 1; - repeated bytes known = 2; + repeated bytes known = 2; } // MembershipResponse is used for replying to MembershipRequests message MembershipResponse { repeated Envelope alive = 1; - repeated Envelope dead = 2; + repeated Envelope dead = 2; } // Member holds membership-related information // about a peer message Member { string endpoint = 1; - bytes metadata = 2; - bytes pki_id = 3; + bytes metadata = 2; + bytes pki_id = 3; } // Empty is used for pinging and in tests -message Empty { -} +message Empty {} + // State transfer @@ -368,4 +370,4 @@ message Chaincode { string name = 1; string version = 2; bytes metadata = 3; -} \ No newline at end of file +} diff --git a/src/main/proto/ledger/queryresult/kv_query_result.proto b/src/main/proto/ledger/queryresult/kv_query_result.proto new file mode 100644 index 00000000..77c64719 --- /dev/null +++ b/src/main/proto/ledger/queryresult/kv_query_result.proto @@ -0,0 +1,29 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package queryresult; + +option go_package = "github.com/hyperledger/fabric-protos-go/ledger/queryresult"; +option java_package = "org.hyperledger.fabric.protos.ledger.queryresult"; + +import "google/protobuf/timestamp.proto"; + + +// KV -- QueryResult for range/execute query. Holds a key and corresponding value. +message KV { + string namespace = 1; + string key = 2; + bytes value = 3; +} + +// KeyModification -- QueryResult for history query. Holds a transaction ID, value, +// timestamp, and delete marker which resulted from a history query. +message KeyModification { + string tx_id = 1; + bytes value = 2; + google.protobuf.Timestamp timestamp = 3; + bool is_delete = 4; +} diff --git a/src/main/proto/ledger/rwset/kvrwset/kv_rwset.proto b/src/main/proto/ledger/rwset/kvrwset/kv_rwset.proto index d1c480e8..c4f85550 100644 --- a/src/main/proto/ledger/rwset/kvrwset/kv_rwset.proto +++ b/src/main/proto/ledger/rwset/kvrwset/kv_rwset.proto @@ -1,12 +1,10 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/ledger/rwset/kvrwset"; +option go_package = "github.com/hyperledger/fabric-protos-go/ledger/rwset/kvrwset"; option java_package = "org.hyperledger.fabric.protos.ledger.rwset.kvrwset"; package kvrwset; diff --git a/src/main/proto/ledger/rwset/rwset.proto b/src/main/proto/ledger/rwset/rwset.proto index e1a49f0c..d9e29c59 100644 --- a/src/main/proto/ledger/rwset/rwset.proto +++ b/src/main/proto/ledger/rwset/rwset.proto @@ -1,22 +1,10 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/ledger/rwset"; +option go_package = "github.com/hyperledger/fabric-protos-go/ledger/rwset"; option java_package = "org.hyperledger.fabric.protos.ledger.rwset"; package rwset; @@ -54,8 +42,8 @@ message TxPvtReadWriteSet { // NsPvtReadWriteSet encapsulates the private read-write set for a chaincode message NsPvtReadWriteSet { - string namespace = 1; - repeated CollectionPvtReadWriteSet collection_pvt_rwset = 2; + string namespace = 1; + repeated CollectionPvtReadWriteSet collection_pvt_rwset = 2; } // CollectionPvtReadWriteSet encapsulates the private read-write set for a collection diff --git a/src/main/proto/msp/identities.proto b/src/main/proto/msp/identities.proto index c88af40a..46453cf3 100644 --- a/src/main/proto/msp/identities.proto +++ b/src/main/proto/msp/identities.proto @@ -1,13 +1,10 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/msp"; +option go_package = "github.com/hyperledger/fabric-protos-go/msp"; option java_package = "org.hyperledger.fabric.protos.msp"; package msp; @@ -16,7 +13,7 @@ package msp; // (with its MSP identifier) to be used // to serialize it and deserialize it message SerializedIdentity { - // The identifier of the associated membership service provider + // The identifier of the associated membership service provider string mspid = 1; // the Identity, serialized according to the rules of its MPS @@ -46,4 +43,4 @@ message SerializedIdemixIdentity { // proof contains the cryptographic evidence that this identity is valid bytes proof = 5; -} \ No newline at end of file +} diff --git a/src/main/proto/msp/msp_config.proto b/src/main/proto/msp/msp_config.proto index 2bd366d9..c459e3da 100644 --- a/src/main/proto/msp/msp_config.proto +++ b/src/main/proto/msp/msp_config.proto @@ -1,14 +1,12 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/msp"; +option go_package = "github.com/hyperledger/fabric-protos-go/msp"; option java_package = "org.hyperledger.fabric.protos.msp"; -option java_outer_classname = "MspConfig"; +option java_outer_classname = "MspConfigPackage"; package msp; @@ -205,4 +203,9 @@ message FabricNodeOUs { // OU Identifier of the peers FabricOUIdentifier peer_ou_identifier = 3; -} \ No newline at end of file + // OU Identifier of the admins + FabricOUIdentifier admin_ou_identifier = 4; + + // OU Identifier of the orderers + FabricOUIdentifier orderer_ou_identifier = 5; +} diff --git a/src/main/proto/msp/msp_principal.proto b/src/main/proto/msp/msp_principal.proto index a3186048..bb9521ac 100644 --- a/src/main/proto/msp/msp_principal.proto +++ b/src/main/proto/msp/msp_principal.proto @@ -1,28 +1,14 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/msp"; +option go_package = "github.com/hyperledger/fabric-protos-go/msp"; option java_package = "org.hyperledger.fabric.protos.common"; package common; - // msp_principal.proto contains proto messages defining the generalized // MSP notion of identity called an MSPPrincipal. It is used as part of // the chain configuration, in particular as the identity parameters to @@ -48,16 +34,15 @@ package common; // identity/certificate; this would mean that the Principal bytes // message message MSPPrincipal { - enum Classification { - ROLE = 0; // Represents the one of the dedicated MSP roles, the + ROLE = 0; // Represents the one of the dedicated MSP roles, the // one of a member of MSP network, and the one of an // administrator of an MSP network ORGANIZATION_UNIT = 1; // Denotes a finer grained (affiliation-based) // groupping of entities, per MSP affiliation // E.g., this can well be represented by an MSP's // Organization unit - IDENTITY = 2; // Denotes a principal that consists of a single + IDENTITY = 2; // Denotes a principal that consists of a single // identity ANONYMITY = 3; // Denotes a principal that can be used to enforce // an identity to be anonymous or nominal. @@ -106,7 +91,6 @@ message OrganizationUnit { // field of an MSPPrincipal when it aims to define one of the // two dedicated roles within an MSP: Admin and Members. message MSPRole { - // MSPIdentifier represents the identifier of the MSP this principal // refers to string msp_identifier = 1; @@ -116,31 +100,28 @@ message MSPRole { ADMIN = 1; // Represents an MSP Admin CLIENT = 2; // Represents an MSP Client PEER = 3; // Represents an MSP Peer + ORDERER = 4; // Represents an MSP Orderer } // MSPRoleType defines which of the available, pre-defined MSP-roles // an identiy should posess inside the MSP with identifier MSPidentifier MSPRoleType role = 2; - } // MSPIdentityAnonymity can be used to enforce an identity to be anonymous or nominal. message MSPIdentityAnonymity { - enum MSPIdentityAnonymityType { NOMINAL = 0; // Represents a nominal MSP Identity ANONYMOUS = 1; // Represents an anonymous MSP Identity } MSPIdentityAnonymityType anonymity_type = 1; - } // CombinedPrincipal governs the organization of the Principal // field of a policy principal when principal_classification has // indicated that a combined form of principals is required message CombinedPrincipal { - // Principals refer to combined principals repeated MSPPrincipal principals = 1; } diff --git a/src/main/proto/orderer/ab.proto b/src/main/proto/orderer/ab.proto index d88a5987..68c43e4d 100644 --- a/src/main/proto/orderer/ab.proto +++ b/src/main/proto/orderer/ab.proto @@ -1,28 +1,16 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -import "common/common.proto"; - -option go_package = "github.com/hyperledger/fabric/protos/orderer"; +option go_package = "github.com/hyperledger/fabric-protos-go/orderer"; option java_package = "org.hyperledger.fabric.protos.orderer"; package orderer; +import "common/common.proto"; + message BroadcastResponse { // Status code, which may be used to programatically respond to success/failure common.Status status = 1; @@ -30,9 +18,9 @@ message BroadcastResponse { string info = 2; } -message SeekNewest {} +message SeekNewest { } -message SeekOldest {} +message SeekOldest { } message SeekSpecified { uint64 number = 1; @@ -51,10 +39,10 @@ message SeekPosition { // Otherwise, blocks are returned until a missing block is encountered, then behavior is dictated // by the SeekBehavior specified. message SeekInfo { - // If BLOCK_UNTIL_READY is specified, the reply will block until the requested blocks are available, - // if FAIL_IF_NOT_READY is specified, the reply will return an error indicating that the block is not - // found. To request that all blocks be returned indefinitely as they are created, behavior should be - // set to BLOCK_UNTIL_READY and the stop should be set to specified with a number of MAX_UINT64 + // If BLOCK_UNTIL_READY is specified, the reply will block until the requested blocks are available, + // if FAIL_IF_NOT_READY is specified, the reply will return an error indicating that the block is not + // found. To request that all blocks be returned indefinitely as they are created, behavior should be + // set to BLOCK_UNTIL_READY and the stop should be set to specified with a number of MAX_UINT64 enum SeekBehavior { BLOCK_UNTIL_READY = 0; FAIL_IF_NOT_READY = 1; @@ -72,9 +60,9 @@ message SeekInfo { STRICT = 0; BEST_EFFORT = 1; } - SeekPosition start = 1; // The position to start the deliver from - SeekPosition stop = 2; // The position to stop the deliver - SeekBehavior behavior = 3; // The behavior when a missing block is encountered + SeekPosition start = 1; // The position to start the deliver from + SeekPosition stop = 2; // The position to stop the deliver + SeekBehavior behavior = 3; // The behavior when a missing block is encountered SeekErrorResponse error_response = 4; // How to respond to errors reported to the deliver service } @@ -87,8 +75,8 @@ message DeliverResponse { service AtomicBroadcast { // broadcast receives a reply of Acknowledgement for each common.Envelope in order, indicating success or type of failure - rpc Broadcast (stream common.Envelope) returns (stream BroadcastResponse); + rpc Broadcast(stream common.Envelope) returns (stream BroadcastResponse); // deliver first requires an Envelope of type DELIVER_SEEK_INFO with Payload data as a mashaled SeekInfo message, then a stream of block replies is received. - rpc Deliver (stream common.Envelope) returns (stream DeliverResponse); + rpc Deliver(stream common.Envelope) returns (stream DeliverResponse); } diff --git a/src/main/proto/orderer/cluster.proto b/src/main/proto/orderer/cluster.proto new file mode 100644 index 00000000..8ff94b3b --- /dev/null +++ b/src/main/proto/orderer/cluster.proto @@ -0,0 +1,64 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option go_package = "github.com/hyperledger/fabric-protos-go/orderer"; +option java_package = "org.hyperledger.fabric.protos.orderer"; + +package orderer; + +import "common/common.proto"; + +// Cluster defines communication between cluster members. +service Cluster { + // Step passes an implementation-specific message to another cluster member. + rpc Step(stream StepRequest) returns (stream StepResponse); +} + +// StepRequest wraps a message that is sent to a cluster member. +message StepRequest { + oneof payload { + // consensus_request is a consensus specific message. + ConsensusRequest consensus_request = 1; + // submit_request is a relay of a transaction. + SubmitRequest submit_request = 2; + } +} + +// StepResponse is a message received from a cluster member. +message StepResponse { + oneof payload { + SubmitResponse submit_res = 1; + } +} + +// ConsensusRequest is a consensus specific message sent to a cluster member. +message ConsensusRequest { + string channel = 1; + bytes payload = 2; + bytes metadata = 3; +} + +// SubmitRequest wraps a transaction to be sent for ordering. +message SubmitRequest { + string channel = 1; + // last_validation_seq denotes the last + // configuration sequence at which the + // sender validated this message. + uint64 last_validation_seq = 2; + // content is the fabric transaction + // that is forwarded to the cluster member. + common.Envelope payload = 3; +} + +// SubmitResponse returns a success +// or failure status to the sender. +message SubmitResponse { + string channel = 1; + // Status code, which may be used to programatically respond to success/failure. + common.Status status = 2; + // Info string which may contain additional information about the returned status. + string info = 3; +} diff --git a/src/main/proto/orderer/configuration.proto b/src/main/proto/orderer/configuration.proto new file mode 100644 index 00000000..c6faded8 --- /dev/null +++ b/src/main/proto/orderer/configuration.proto @@ -0,0 +1,64 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option go_package = "github.com/hyperledger/fabric-protos-go/orderer"; +option java_package = "org.hyperledger.fabric.protos.orderer"; + +package orderer; + +// The orderer config is specified by the following convention: +// For a configuration item with key "Key" +// the encoded value is a a proto message of type "Key" +// For example, for the configuration item of name "ConsensusType" +// the encoded value is the proto message "ConsensusType" + +message ConsensusType { + // The consensus type: "solo", "kafka" or "etcdraft". + string type = 1; + // Opaque metadata, dependent on the consensus type. + bytes metadata = 2; + + // State defines the orderer mode of operation, typically for consensus-type migration. + // NORMAL is during normal operation, when consensus-type migration is not, and can not, take place. + // MAINTENANCE is when the consensus-type can be changed. + enum State { + STATE_NORMAL = 0; + STATE_MAINTENANCE = 1; + } + // The state signals the ordering service to go into maintenance mode, typically for consensus-type migration. + State state = 3; +} + +message BatchSize { + // Simply specified as number of messages for now, in the future + // we may want to allow this to be specified by size in bytes + uint32 max_message_count = 1; + // The byte count of the serialized messages in a batch cannot + // exceed this value. + uint32 absolute_max_bytes = 2; + // The byte count of the serialized messages in a batch should not + // exceed this value. + uint32 preferred_max_bytes = 3; +} + +message BatchTimeout { + // Any duration string parseable by ParseDuration(): + // https://golang.org/pkg/time/#ParseDuration + string timeout = 1; +} + +// Carries a list of bootstrap brokers, i.e. this is not the exclusive set of +// brokers an ordering service +message KafkaBrokers { + // Each broker here should be identified using the (IP|host):port notation, + // e.g. 127.0.0.1:7050, or localhost:7050 are valid entries + repeated string brokers = 1; +} + +// ChannelRestrictions is the mssage which conveys restrictions on channel creation for an orderer +message ChannelRestrictions { + uint64 max_count = 1; // The max count of channels to allow to be created, a value of 0 indicates no limit +} diff --git a/src/main/proto/orderer/etcdraft/configuration.proto b/src/main/proto/orderer/etcdraft/configuration.proto new file mode 100644 index 00000000..3ad6037b --- /dev/null +++ b/src/main/proto/orderer/etcdraft/configuration.proto @@ -0,0 +1,36 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option go_package = "github.com/hyperledger/fabric-protos-go/orderer/etcdraft"; +option java_package = "org.hyperledger.fabric.protos.orderer.etcdraft"; + +package etcdraft; + +// ConfigMetadata is serialized and set as the value of ConsensusType.Metadata in +// a channel configuration when the ConsensusType.Type is set "etcdraft". +message ConfigMetadata { + repeated Consenter consenters = 1; + Options options = 2; +} + +// Consenter represents a consenting node (i.e. replica). +message Consenter { + string host = 1; + uint32 port = 2; + bytes client_tls_cert = 3; + bytes server_tls_cert = 4; +} + +// Options to be specified for all the etcd/raft nodes. These can be modified on a +// per-channel basis. +message Options { + string tick_interval = 1; // time duration format, e.g. 500ms + uint32 election_tick = 2; + uint32 heartbeat_tick = 3; + uint32 max_inflight_blocks = 4; + // Take snapshot when cumulative data exceeds certain size in bytes. + uint32 snapshot_interval_size = 5; +} diff --git a/src/main/proto/orderer/etcdraft/metadata.proto b/src/main/proto/orderer/etcdraft/metadata.proto new file mode 100644 index 00000000..0cf74a1c --- /dev/null +++ b/src/main/proto/orderer/etcdraft/metadata.proto @@ -0,0 +1,30 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option go_package = "github.com/hyperledger/fabric-protos-go/orderer/etcdraft"; +option java_package = "org.hyperledger.fabric.protos.orderer.etcdraft"; + +package etcdraft; + +// BlockMetadata stores data used by the Raft OSNs when +// coordinating with each other, to be serialized into +// block meta dta field and used after failres and restarts. +message BlockMetadata { + // Maintains a mapping between the cluster's OSNs + // and their Raft IDs. + repeated uint64 consenter_ids = 1; + // Carries the Raft ID value that will be assigned + // to the next OSN that will join this cluster. + uint64 next_consenter_id = 2; + // Index of etcd/raft entry for current block. + uint64 raft_index = 3; +} + +// ClusterMetadata encapsulates metadata that is exchanged among cluster nodes +message ClusterMetadata { + // Indicates active nodes in cluster that are reacheable by Raft leader + repeated uint64 active_nodes = 1; +} diff --git a/src/main/proto/orderer/kafka.proto b/src/main/proto/orderer/kafka.proto new file mode 100644 index 00000000..f71a79ed --- /dev/null +++ b/src/main/proto/orderer/kafka.proto @@ -0,0 +1,71 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option go_package = "github.com/hyperledger/fabric-protos-go/orderer"; +option java_package = "org.hyperledger.fabric.protos.orderer"; + +package orderer; + +// KafkaMessage is a wrapper type for the messages +// that the Kafka-based orderer deals with. +message KafkaMessage { + oneof Type { + KafkaMessageRegular regular = 1; + KafkaMessageTimeToCut time_to_cut = 2; + KafkaMessageConnect connect = 3; + } +} + +// KafkaMessageRegular wraps a marshalled envelope. +message KafkaMessageRegular { + enum Class { + UNKNOWN = 0; + NORMAL = 1; + CONFIG = 2; + } + bytes payload = 1; + uint64 config_seq = 2; + Class class = 3; + int64 original_offset = 4; +} + +// KafkaMessageTimeToCut is used to signal to the orderers +// that it is time to cut block . +message KafkaMessageTimeToCut { + uint64 block_number = 1; +} + +// KafkaMessageConnect is posted by an orderer upon booting up. +// It is used to prevent the panic that would be caused if we +// were to consume an empty partition. It is ignored by all +// orderers when processing the partition. +message KafkaMessageConnect { + bytes payload = 1; +} + +// KafkaMetadata is encoded into the ORDERER block to keep track of +// Kafka-related metadata associated with this block. +message KafkaMetadata { + // LastOffsetPersisted is the encoded value for the Metadata message + // which is encoded in the ORDERER block metadata index for the case + // of the Kafka-based orderer. + int64 last_offset_persisted = 1; + + // LastOriginalOffsetProcessed is used to keep track of the newest + // offset processed if a message is re-validated and re-ordered. + // This value is used to deduplicate re-submitted messages from + // multiple orderer so that we don't bother re-processing it again. + int64 last_original_offset_processed = 2; + + // LastResubmittedConfigOffset is used to capture the newest offset of + // CONFIG kafka message, which is revalidated and resubmitted. By comparing + // this with LastOriginalOffsetProcessed, we could detemine whether there + // are still CONFIG messages that have been resubmitted but NOT processed + // yet. It's used as condition to block ingress messages, so we could reduce + // the overhead of repeatedly resubmitting messages as config seq keeps + // advancing. + int64 last_resubmitted_config_offset = 3; +} diff --git a/src/main/proto/peer/chaincode.proto b/src/main/proto/peer/chaincode.proto index 9da9f80e..0f2f3740 100644 --- a/src/main/proto/peer/chaincode.proto +++ b/src/main/proto/peer/chaincode.proto @@ -1,25 +1,13 @@ -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -package protos; option java_package = "org.hyperledger.fabric.protos.peer"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; +package protos; //ChaincodeID contains the path as specified by the deploy transaction //that created it as well as the hashCode that is generated by the @@ -76,17 +64,11 @@ message ChaincodeSpec { // TODO: Define `codePackage`. message ChaincodeDeploymentSpec { // Prevent removed tag re-use - reserved 2; - reserved "effective_date"; - - enum ExecutionEnvironment { - DOCKER = 0; - SYSTEM = 1; - } + reserved 2, 4; + reserved "effective_date", "exec_env"; ChaincodeSpec chaincode_spec = 1; bytes code_package = 3; - ExecutionEnvironment exec_env= 4; } diff --git a/src/main/proto/peer/chaincode_event.proto b/src/main/proto/peer/chaincode_event.proto old mode 100755 new mode 100644 index 16bd10a5..41f75ea7 --- a/src/main/proto/peer/chaincode_event.proto +++ b/src/main/proto/peer/chaincode_event.proto @@ -1,23 +1,14 @@ -/* -Copyright IBM Corp. 2017 All Rights Reserved. +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ syntax = "proto3"; -package protos; + option java_package = "org.hyperledger.fabric.protos.peer"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option java_outer_classname = "ChaincodeEventPackage"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; +package protos; //ChaincodeEvent is used for events and registrations that are specific to chaincode //string type - "chaincode" diff --git a/src/main/proto/peer/chaincode_shim.proto b/src/main/proto/peer/chaincode_shim.proto new file mode 100644 index 00000000..48afbdb3 --- /dev/null +++ b/src/main/proto/peer/chaincode_shim.proto @@ -0,0 +1,179 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option java_package = "org.hyperledger.fabric.protos.peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; + +package protos; + +import "peer/chaincode_event.proto"; +import "peer/proposal.proto"; +import "google/protobuf/timestamp.proto"; + +message ChaincodeMessage { + enum Type { + UNDEFINED = 0; + REGISTER = 1; + REGISTERED = 2; + INIT = 3; + READY = 4; + TRANSACTION = 5; + COMPLETED = 6; + ERROR = 7; + GET_STATE = 8; + PUT_STATE = 9; + DEL_STATE = 10; + INVOKE_CHAINCODE = 11; + RESPONSE = 13; + GET_STATE_BY_RANGE = 14; + GET_QUERY_RESULT = 15; + QUERY_STATE_NEXT = 16; + QUERY_STATE_CLOSE = 17; + KEEPALIVE = 18; + GET_HISTORY_FOR_KEY = 19; + GET_STATE_METADATA = 20; + PUT_STATE_METADATA = 21; + GET_PRIVATE_DATA_HASH = 22; + } + + Type type = 1; + google.protobuf.Timestamp timestamp = 2; + bytes payload = 3; + string txid = 4; + + SignedProposal proposal = 5; + + //event emitted by chaincode. Used only with Init or Invoke. + // This event is then stored (currently) + //with Block.NonHashData.TransactionResult + ChaincodeEvent chaincode_event = 6; + + //channel id + string channel_id = 7; +} + +// TODO: We need to finalize the design on chaincode container +// compatibility upon upgrade, see FAB-5777. + +// GetState is the payload of a ChaincodeMessage. It contains a key which +// is to be fetched from the ledger. If the collection is specified, the key +// would be fetched from the collection (i.e., private state) +message GetState { + string key = 1; + string collection = 2; +} + +message GetStateMetadata { + string key = 1; + string collection = 2; +} + +// PutState is the payload of a ChaincodeMessage. It contains a key and value +// which needs to be written to the transaction's write set. If the collection is +// specified, the key and value would be written to the transaction's private +// write set. +message PutState { + string key = 1; + bytes value = 2; + string collection = 3; +} + +message PutStateMetadata { + string key = 1; + string collection = 3; + StateMetadata metadata = 4; +} + +// DelState is the payload of a ChaincodeMessage. It contains a key which +// needs to be recorded in the transaction's write set as a delete operation. +// If the collection is specified, the key needs to be recorded in the +// transaction's private write set as a delete operation. +message DelState { + string key = 1; + string collection = 2; +} + +// GetStateByRange is the payload of a ChaincodeMessage. It contains a start key and +// a end key required to execute range query. If the collection is specified, +// the range query needs to be executed on the private data. The metadata hold +// the byte representation of QueryMetadata. +message GetStateByRange { + string startKey = 1; + string endKey = 2; + string collection = 3; + bytes metadata = 4; +} + +// GetQueryResult is the payload of a ChaincodeMessage. It contains a query +// string in the form that is supported by the underlying state database. +// If the collection is specified, the query needs to be executed on the +// private data. The metadata hold the byte representation of QueryMetadata. +message GetQueryResult { + string query = 1; + string collection = 2; + bytes metadata = 3; +} + +// QueryMetadata is the metadata of a GetStateByRange and GetQueryResult. +// It contains a pageSize which denotes the number of records to be fetched +// and a bookmark. +message QueryMetadata { + int32 pageSize = 1; + string bookmark = 2; +} + +// GetHistoryForKey is the payload of a ChaincodeMessage. It contains a key +// for which the historical values need to be retrieved. +message GetHistoryForKey { + string key = 1; +} + +message QueryStateNext { + string id = 1; +} + +message QueryStateClose { + string id = 1; +} + +// QueryResultBytes hold the byte representation of a record returned by the peer. +message QueryResultBytes { + bytes resultBytes = 1; +} + +// QueryResponse is returned by the peer as a result of a GetStateByRange, +// GetQueryResult, and GetHistoryForKey. It holds a bunch of records in +// results field, a flag to denote whether more results need to be fetched from +// the peer in has_more field, transaction id in id field, and a QueryResponseMetadata +// in metadata field. +message QueryResponse { + repeated QueryResultBytes results = 1; + bool has_more = 2; + string id = 3; + bytes metadata = 4; +} + +// QueryResponseMetadata is the metadata of a QueryResponse. It contains a count +// which denotes the number of records fetched from the ledger and a bookmark. +message QueryResponseMetadata { + int32 fetched_records_count = 1; + string bookmark = 2; +} + +message StateMetadata { + string metakey = 1; + bytes value = 2; +} + +message StateMetadataResult { + repeated StateMetadata entries = 1; +} + +// Interface that provides support to chaincode execution. ChaincodeContext +// provides the context necessary for the server to respond appropriately. +service ChaincodeSupport { + rpc Register(stream ChaincodeMessage) returns (stream ChaincodeMessage); +} diff --git a/src/main/proto/peer/configuration.proto b/src/main/proto/peer/configuration.proto index 4c201088..e9b41bc8 100644 --- a/src/main/proto/peer/configuration.proto +++ b/src/main/proto/peer/configuration.proto @@ -1,23 +1,11 @@ -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; option java_package = "org.hyperledger.fabric.protos.peer"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; package protos; @@ -29,13 +17,8 @@ message AnchorPeers { // AnchorPeer message structure which provides information about anchor peer, it includes host name, // port number and peer certificate. message AnchorPeer { - - // DNS host name of the anchor peer - string host = 1; - - // The port number - int32 port = 2; - + string host = 1; // DNS host name of the anchor peer + int32 port = 2; // The port number } // APIResource represents an API resource in the peer whose ACL diff --git a/src/main/proto/peer/events.proto b/src/main/proto/peer/events.proto index d659343c..522189cd 100644 --- a/src/main/proto/peer/events.proto +++ b/src/main/proto/peer/events.proto @@ -1,22 +1,20 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -import "common/common.proto"; -// import "google/protobuf/timestamp.proto"; -import "peer/chaincode_event.proto"; -import "peer/transaction.proto"; - option java_package = "org.hyperledger.fabric.protos.peer"; -option java_outer_classname = "PeerEvents"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option java_outer_classname = "EventsPackage"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; package protos; +import "common/common.proto"; +import "ledger/rwset/rwset.proto"; +import "peer/chaincode_event.proto"; +import "peer/transaction.proto"; + // FilteredBlock is a minimal set of information about a block message FilteredBlock { string channel_id = 1; @@ -47,24 +45,37 @@ message FilteredChaincodeAction { ChaincodeEvent chaincode_event = 1; } +// BlockAndPrivateData contains Block and a map from tx_seq_in_block to rwset.TxPvtReadWriteSet +message BlockAndPrivateData { + common.Block block = 1; + // map from tx_seq_in_block to rwset.TxPvtReadWriteSet + map private_data_map = 2; +} + // DeliverResponse message DeliverResponse { oneof Type { common.Status status = 1; common.Block block = 2; FilteredBlock filtered_block = 3; + BlockAndPrivateData block_and_private_data = 4; } } service Deliver { - // deliver first requires an Envelope of type ab.DELIVER_SEEK_INFO with + // Deliver first requires an Envelope of type ab.DELIVER_SEEK_INFO with // Payload data as a marshaled orderer.SeekInfo message, // then a stream of block replies is received rpc Deliver (stream common.Envelope) returns (stream DeliverResponse) { } - // deliver first requires an Envelope of type ab.DELIVER_SEEK_INFO with + // DeliverFiltered first requires an Envelope of type ab.DELIVER_SEEK_INFO with // Payload data as a marshaled orderer.SeekInfo message, // then a stream of **filtered** block replies is received rpc DeliverFiltered (stream common.Envelope) returns (stream DeliverResponse) { } + // DeliverWithPrivateData first requires an Envelope of type ab.DELIVER_SEEK_INFO with + // Payload data as a marshaled orderer.SeekInfo message, + // then a stream of block and private data replies is received + rpc DeliverWithPrivateData (stream common.Envelope) returns (stream DeliverResponse) { + } } diff --git a/src/main/proto/peer/lifecycle/chaincode_definition.proto b/src/main/proto/peer/lifecycle/chaincode_definition.proto new file mode 100644 index 00000000..bfe01fb8 --- /dev/null +++ b/src/main/proto/peer/lifecycle/chaincode_definition.proto @@ -0,0 +1,31 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option java_package = "org.hyperledger.fabric.protos.peer.lifecycle"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer/lifecycle"; + +package lifecycle; + +// These protos are used for encoding chaincode definitions into the statedb +// in general, it should not be necessary for clients to utilize them. + +// ChaincodeEndorsementInfo is (most) everything the peer needs to know in order +// to execute a chaincode +message ChaincodeEndorsementInfo { + string version = 1; + bool init_required = 2; + string endorsement_plugin = 3; +} + +// ValidationInfo is (most) everything the peer needs to know in order +// to validate a transaction +message ChaincodeValidationInfo { + string validation_plugin = 1; + bytes validation_parameter = 2; +} + +// The notable omission in this file is the collection configuration info. +// It should be moved to this package, but... defering for now. diff --git a/src/main/proto/peer/lifecycle/db.proto b/src/main/proto/peer/lifecycle/db.proto new file mode 100644 index 00000000..9adb5d51 --- /dev/null +++ b/src/main/proto/peer/lifecycle/db.proto @@ -0,0 +1,30 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option java_package = "org.hyperledger.fabric.protos.peer.lifecycle"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer/lifecycle"; + +package lifecycle; + +// These protos are used for encoding data into the statedb +// in general, it should not be necessary for clients to utilize them. + +// StateMetadata describes the keys in a namespace. It is necessary because +// in collections, range scans are not possible during transactions which +// write. Therefore we must track the keys in our namespace ourselves. +message StateMetadata { + string datatype = 1; + repeated string fields = 2; +} + +// StateData encodes a particular field of a datatype +message StateData { + oneof Type { + int64 Int64 = 1; + bytes Bytes = 2; + string String = 3; + } +} diff --git a/src/main/proto/peer/lifecycle/lifecycle.proto b/src/main/proto/peer/lifecycle/lifecycle.proto index e7442dad..4e48e687 100644 --- a/src/main/proto/peer/lifecycle/lifecycle.proto +++ b/src/main/proto/peer/lifecycle/lifecycle.proto @@ -1,17 +1,15 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -import "common/collection.proto"; +option java_package = "org.hyperledger.fabric.protos.peer.lifecycle"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer/lifecycle"; package lifecycle; -option java_package = "org.hyperledger.fabric.protos.peer.lifecycle"; -option go_package = "github.com/hyperledger/fabric/protos/peer/lifecycle"; +import "common/collection.proto"; // InstallChaincodeArgs is the message used as the argument to // '_lifecycle.InstallChaincode'. @@ -37,6 +35,16 @@ message QueryInstalledChaincodeArgs { message QueryInstalledChaincodeResult { string package_id = 1; string label = 2; + map references = 3; + + message References { + repeated Chaincode chaincodes = 1; + } + + message Chaincode { + string name = 1; + string version = 2; + } } // GetInstalledChaincodePackageArgs is the message used as the argument to @@ -174,8 +182,7 @@ message QueryChaincodeDefinitionResult { // QueryChaincodeDefinitionsArgs is the message used as arguments to // `_lifecycle.QueryChaincodeDefinitions`. -message QueryChaincodeDefinitionsArgs { -} +message QueryChaincodeDefinitionsArgs { } // QueryChaincodeDefinitionsResult is the message returned by // `_lifecycle.QueryChaincodeDefinitions`. diff --git a/src/main/proto/peer/peer.proto b/src/main/proto/peer/peer.proto index 6923e7a5..396b74af 100644 --- a/src/main/proto/peer/peer.proto +++ b/src/main/proto/peer/peer.proto @@ -1,22 +1,11 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ syntax = "proto3"; option java_package = "org.hyperledger.fabric.protos.peer"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; package protos; @@ -24,5 +13,5 @@ import "peer/proposal.proto"; import "peer/proposal_response.proto"; service Endorser { - rpc ProcessProposal (SignedProposal) returns (ProposalResponse); + rpc ProcessProposal(SignedProposal) returns (ProposalResponse); } diff --git a/src/main/proto/peer/policy.proto b/src/main/proto/peer/policy.proto index 5ea74ad3..1f67451a 100644 --- a/src/main/proto/peer/policy.proto +++ b/src/main/proto/peer/policy.proto @@ -1,12 +1,10 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; option java_package = "org.hyperledger.fabric.protos.peer"; package protos; diff --git a/src/main/proto/peer/proposal.proto b/src/main/proto/peer/proposal.proto index 04b036ed..a9459467 100644 --- a/src/main/proto/peer/proposal.proto +++ b/src/main/proto/peer/proposal.proto @@ -1,31 +1,17 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; option java_package = "org.hyperledger.fabric.protos.peer"; -option java_outer_classname = "FabricProposal"; +option java_outer_classname = "ProposalPackage"; package protos; import "peer/chaincode.proto"; import "peer/proposal_response.proto"; -//REMOVED BY RICK put back once token support is/f done -//import "token/operations.proto"; /* The flow to get a generic transaction approved goes as follows: @@ -105,13 +91,13 @@ SignedTransaction // 4. Detect replay attacks; message SignedProposal { - // The bytes of Proposal - bytes proposal_bytes = 1; + // The bytes of Proposal + bytes proposal_bytes = 1; // Signaure over proposalBytes; this signature is to be verified against // the creator identity contained in the header of the Proposal message // marshaled as proposalBytes - bytes signature = 2; + bytes signature = 2; } // A Proposal is sent to an endorser for endorsement. The proposal contains: @@ -135,17 +121,17 @@ message SignedProposal { // submitting peer model. message Proposal { - // The header of the proposal. It is the bytes of the Header - bytes header = 1; + // The header of the proposal. It is the bytes of the Header + bytes header = 1; - // The payload of the proposal as defined by the type in the proposal - // header. - bytes payload = 2; + // The payload of the proposal as defined by the type in the proposal + // header. + bytes payload = 2; - // Optional extensions to the proposal. Its content depends on the Header's - // type field. For the type CHAINCODE, it might be the bytes of a - // ChaincodeAction message. - bytes extension = 3; + // Optional extensions to the proposal. Its content depends on the Header's + // type field. For the type CHAINCODE, it might be the bytes of a + // ChaincodeAction message. + bytes extension = 3; } //-------- the Chaincode Proposal ----------- @@ -218,21 +204,11 @@ SignedTransaction // chaincode to invoke and what should appear on the ledger. message ChaincodeHeaderExtension { - // The PayloadVisibility field controls to what extent the Proposal's payload - // (recall that for the type CHAINCODE, it is ChaincodeProposalPayload - // message) field will be visible in the final transaction and in the ledger. - // Ideally, it would be configurable, supporting at least 3 main visibility - // modes: - // 1. all bytes of the payload are visible; - // 2. only a hash of the payload is visible; - // 3. nothing is visible. - // Notice that the visibility function may be potentially part of the ESCC. - // In that case it overrides PayloadVisibility field. Finally notice that - // this field impacts the content of ProposalResponsePayload.proposalHash. - bytes payload_visibility = 1; - - // The ID of the chaincode to target. - ChaincodeID chaincode_id = 2; + reserved 1; + reserved "payload_visbility"; + + // The ID of the chaincode to target. + ChaincodeID chaincode_id = 2; } // ChaincodeProposalPayload is the Proposal's payload message to be used when @@ -240,42 +216,39 @@ message ChaincodeHeaderExtension { // invocation. message ChaincodeProposalPayload { - // Input contains the arguments for this invocation. If this invocation - // deploys a new chaincode, ESCC/VSCC are part of this field. - // This is usually a marshaled ChaincodeInvocationSpec - bytes input = 1; + // Input contains the arguments for this invocation. If this invocation + // deploys a new chaincode, ESCC/VSCC are part of this field. + // This is usually a marshaled ChaincodeInvocationSpec + bytes input = 1; - // TransientMap contains data (e.g. cryptographic material) that might be used - // to implement some form of application-level confidentiality. The contents - // of this field are supposed to always be omitted from the transaction and - // excluded from the ledger. - map TransientMap = 2; + // TransientMap contains data (e.g. cryptographic material) that might be used + // to implement some form of application-level confidentiality. The contents + // of this field are supposed to always be omitted from the transaction and + // excluded from the ledger. + map TransientMap = 2; } // ChaincodeAction contains the actions the events generated by the execution // of the chaincode. message ChaincodeAction { - - // This field contains the read set and the write set produced by the - // chaincode executing this invocation. - bytes results = 1; - - // This field contains the events generated by the chaincode executing this - // invocation. - bytes events = 2; - - // This field contains the result of executing this invocation. - Response response = 3; - - // This field contains the ChaincodeID of executing this invocation. Endorser - // will set it with the ChaincodeID called by endorser while simulating proposal. - // Committer will validate the version matching with latest chaincode version. - // Adding ChaincodeID to keep version opens up the possibility of multiple - // ChaincodeAction per transaction. - ChaincodeID chaincode_id = 4; - - // This field contains the token operations requests generated by the chaincode - // executing this invocation - //REMOVED BY RICK put back once token support is/f done - //repeated token.TokenOperation token_operations = 5; -} \ No newline at end of file + reserved 5; + reserved "token_operations"; + + // This field contains the read set and the write set produced by the + // chaincode executing this invocation. + bytes results = 1; + + // This field contains the events generated by the chaincode executing this + // invocation. + bytes events = 2; + + // This field contains the result of executing this invocation. + Response response = 3; + + // This field contains the ChaincodeID of executing this invocation. Endorser + // will set it with the ChaincodeID called by endorser while simulating proposal. + // Committer will validate the version matching with latest chaincode version. + // Adding ChaincodeID to keep version opens up the possibility of multiple + // ChaincodeAction per transaction. + ChaincodeID chaincode_id = 4; +} diff --git a/src/main/proto/peer/proposal_response.proto b/src/main/proto/peer/proposal_response.proto index 0c2f8e6d..4a29e9e7 100644 --- a/src/main/proto/peer/proposal_response.proto +++ b/src/main/proto/peer/proposal_response.proto @@ -1,24 +1,12 @@ -/* -Copyright IBM Corp. 2016 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; option java_package = "org.hyperledger.fabric.protos.peer"; -option java_outer_classname = "FabricProposalResponse"; +option java_outer_classname = "ProposalResponsePackage"; package protos; @@ -33,38 +21,36 @@ import "google/protobuf/timestamp.proto"; // endorsers agree on the same action and produce signature to that effect, a // transaction can be generated and sent for ordering. message ProposalResponse { + // Version indicates message protocol version + int32 version = 1; - // Version indicates message protocol version - int32 version = 1; - - // Timestamp is the time that the message - // was created as defined by the sender - google.protobuf.Timestamp timestamp = 2; + // Timestamp is the time that the message + // was created as defined by the sender + google.protobuf.Timestamp timestamp = 2; - // A response message indicating whether the - // endorsement of the action was successful - Response response = 4; + // A response message indicating whether the + // endorsement of the action was successful + Response response = 4; - // The payload of response. It is the bytes of ProposalResponsePayload - bytes payload = 5; + // The payload of response. It is the bytes of ProposalResponsePayload + bytes payload = 5; - // The endorsement of the proposal, basically - // the endorser's signature over the payload - Endorsement endorsement = 6; + // The endorsement of the proposal, basically + // the endorser's signature over the payload + Endorsement endorsement = 6; } // A response with a representation similar to an HTTP response that can // be used within another message. message Response { + // A status code that should follow the HTTP status codes. + int32 status = 1; - // A status code that should follow the HTTP status codes. - int32 status = 1; + // A message associated with the response code. + string message = 2; - // A message associated with the response code. - string message = 2; - - // A payload that can be used to include metadata with this response. - bytes payload = 3; + // A payload that can be used to include metadata with this response. + bytes payload = 3; } // ProposalResponsePayload is the payload of a proposal response. This message @@ -73,30 +59,19 @@ message Response { // representation of the proposal (proposalHash) and a representation of the // chaincode state changes and events inside the extension field. message ProposalResponsePayload { - - // Hash of the proposal that triggered this response. The hash is used to - // link a response with its proposal, both for bookeeping purposes on an - // asynchronous system and for security reasons (accountability, - // non-repudiation). The hash usually covers the entire Proposal message - // (byte-by-byte). However this implies that the hash can only be verified - // if the entire proposal message is available when ProposalResponsePayload is - // included in a transaction or stored in the ledger. For confidentiality - // reasons, with chaincodes it might be undesirable to store the proposal - // payload in the ledger. If the type is CHAINCODE, this is handled by - // separating the proposal's header and - // the payload: the header is always hashed in its entirety whereas the - // payload can either be hashed fully, or only its hash may be hashed, or - // nothing from the payload can be hashed. The PayloadVisibility field in the - // Header's extension controls to which extent the proposal payload is - // "visible" in the sense that was just explained. - bytes proposal_hash = 1; - - // Extension should be unmarshaled to a type-specific message. The type of - // the extension in any proposal response depends on the type of the proposal - // that the client selected when the proposal was initially sent out. In - // particular, this information is stored in the type field of a Header. For - // chaincode, it's a ChaincodeAction message - bytes extension = 2; + // Hash of the proposal that triggered this response. The hash is used to + // link a response with its proposal, both for bookeeping purposes on an + // asynchronous system and for security reasons (accountability, + // non-repudiation). The hash usually covers the entire Proposal message + // (byte-by-byte). + bytes proposal_hash = 1; + + // Extension should be unmarshaled to a type-specific message. The type of + // the extension in any proposal response depends on the type of the proposal + // that the client selected when the proposal was initially sent out. In + // particular, this information is stored in the type field of a Header. For + // chaincode, it's a ChaincodeAction message + bytes extension = 2; } // An endorsement is a signature of an endorser over a proposal response. By @@ -109,11 +84,10 @@ message ProposalResponsePayload { // expected to endorse a single proposal response/action (many endorsements // over a single proposal response) message Endorsement { + // Identity of the endorser (e.g. its certificate) + bytes endorser = 1; - // Identity of the endorser (e.g. its certificate) - bytes endorser = 1; - - // Signature of the payload included in ProposalResponse concatenated with - // the endorser's certificate; ie, sign(ProposalResponse.payload + endorser) - bytes signature = 2; + // Signature of the payload included in ProposalResponse concatenated with + // the endorser's certificate; ie, sign(ProposalResponse.payload + endorser) + bytes signature = 2; } diff --git a/src/main/proto/peer/query.proto b/src/main/proto/peer/query.proto index d934104f..5c25abda 100644 --- a/src/main/proto/peer/query.proto +++ b/src/main/proto/peer/query.proto @@ -1,23 +1,11 @@ -/* -Copyright IBM Corp. 2017 All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; option java_package = "org.hyperledger.fabric.protos.peer"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; package protos; diff --git a/src/main/proto/peer/resources.proto b/src/main/proto/peer/resources.proto new file mode 100644 index 00000000..be9bdd06 --- /dev/null +++ b/src/main/proto/peer/resources.proto @@ -0,0 +1,54 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option java_package = "org.hyperledger.fabric.protos.peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; + +package protos; + +import "common/configtx.proto"; + +// ChaincodeIdentifier identifies a piece of chaincode. For a peer to accept invocations of +// this chaincode, the hash of the installed code must match, as must the version string +// included with the install command. +message ChaincodeIdentifier { + bytes hash = 1; // The hash of the chaincode bytes + string version = 2; // A user friendly human readable name corresponding to the ID +} + +// ChaincodeValidation instructs the peer how transactions for this chaincode should be +// validated. The only validation mechanism which ships with fabric today is the standard +// 'vscc' validation mechanism. This built in validation method utilizes an endorsement policy +// which checks that a sufficient number of signatures have been included. The 'arguement' +// field encodes any parameters required by the validation implementation. +message ChaincodeValidation { + string name = 1; // Specifies which code to run to validate transactions, defaults to 'vscc' + bytes argument = 2; // When 'vscc' a marshaled VSCCArgs +} + +// VSCCArgs is passed (marshaled) as a parameter to the VSCC imlementation via the +// argument field of the ChaincodeValidation message. +message VSCCArgs { + string endorsement_policy_ref = 1; // A named reference to an endorsement policy, + // for instance /Channel/Application/Writers +} + +// ChaincodeEndorsement instructs the peer how transactions should be endorsed. The only +// endorsement mechanism which ships with the fabric today is the standard 'escc' mechanism. +// This code simply simulates the proposal to generate a RW set, then signs the result +// using the peer's local signing identity. +message ChaincodeEndorsement { + string name = 1; // Specifies what code to run for endorsements, defaults 'escc' + // Eventually we may wish add an arg here, just like the ChaincodeValidation message, but + // omitting now until there is a need for it. +} + +// ConfigTree encapsulates channel and resources configuration of a channel. +// Both configurations are represented as common.Config +message ConfigTree { + common.Config channel_config = 1; + common.Config resources_config = 2; +} diff --git a/src/main/proto/peer/signed_cc_dep_spec.proto b/src/main/proto/peer/signed_cc_dep_spec.proto new file mode 100644 index 00000000..05f46892 --- /dev/null +++ b/src/main/proto/peer/signed_cc_dep_spec.proto @@ -0,0 +1,30 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +option java_package = "org.hyperledger.fabric.protos.peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; + +package protos; + +import "peer/proposal_response.proto"; + +// SignedChaincodeDeploymentSpec carries the CDS along with endorsements +message SignedChaincodeDeploymentSpec { + // This is the bytes of the ChaincodeDeploymentSpec + bytes chaincode_deployment_spec = 1; + + // This is the instantiation policy which is identical in structure + // to endorsement policy. This policy is checked by the VSCC at commit + // time on the instantiation (all peers will get the same policy as it + // will be part of the LSCC instantation record and will be part of the + // hash as well) + bytes instantiation_policy = 2; + + // The endorsements of the above deployment spec, the owner's signature over + // chaincode_deployment_spec and Endorsement.endorser. + repeated Endorsement owner_endorsements = 3; +} + diff --git a/src/main/proto/peer/transaction.proto b/src/main/proto/peer/transaction.proto index 2e4a4877..fdffba33 100644 --- a/src/main/proto/peer/transaction.proto +++ b/src/main/proto/peer/transaction.proto @@ -1,14 +1,12 @@ -/* -Copyright IBM Corp. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; -option go_package = "github.com/hyperledger/fabric/protos/peer"; +option go_package = "github.com/hyperledger/fabric-protos-go/peer"; option java_package = "org.hyperledger.fabric.protos.peer"; -option java_outer_classname = "FabricTransaction"; +option java_outer_classname = "TransactionPackage"; package protos; @@ -19,15 +17,14 @@ import "common/common.proto"; // (in the signature field) over the bytes of the transaction (in the // transactionBytes field). message SignedTransaction { - - // The bytes of the Transaction. NDD - bytes transaction_bytes = 1; - - // Signature of the transactionBytes The public key of the signature is in - // the header field of TransactionAction There might be multiple - // TransactionAction, so multiple headers, but there should be same - // transactor identity (cert) in all headers - bytes signature = 2; + // The bytes of the Transaction. NDD + bytes transaction_bytes = 1; + + // Signature of the transactionBytes The public key of the signature is in + // the header field of TransactionAction There might be multiple + // TransactionAction, so multiple headers, but there should be same + // transactor identity (cert) in all headers + bytes signature = 2; } // ProcessedTransaction wraps an Envelope that includes a transaction along with an indication @@ -58,21 +55,21 @@ message ProcessedTransaction { // to ensure that they are treated atomically. message Transaction { - // The payload is an array of TransactionAction. An array is necessary to - // accommodate multiple actions per transaction - repeated TransactionAction actions = 1; + // The payload is an array of TransactionAction. An array is necessary to + // accommodate multiple actions per transaction + repeated TransactionAction actions = 1; } // TransactionAction binds a proposal to its action. The type field in the // header dictates the type of action to be applied to the ledger. message TransactionAction { - // The header of the proposal action, which is the proposal header - bytes header = 1; + // The header of the proposal action, which is the proposal header + bytes header = 1; - // The payload of the action as defined by the type in the header For - // chaincode, it's the bytes of ChaincodeActionPayload - bytes payload = 2; + // The payload of the action as defined by the type in the header For + // chaincode, it's the bytes of ChaincodeActionPayload + bytes payload = 2; } //---------- Chaincode Transaction ------------ @@ -81,69 +78,67 @@ message TransactionAction { // payload when the Header's type is set to CHAINCODE. It carries the // chaincodeProposalPayload and an endorsed action to apply to the ledger. message ChaincodeActionPayload { - - // This field contains the bytes of the ChaincodeProposalPayload message from - // the original invocation (essentially the arguments) after the application - // of the visibility function. The main visibility modes are "full" (the - // entire ChaincodeProposalPayload message is included here), "hash" (only - // the hash of the ChaincodeProposalPayload message is included) or - // "nothing". This field will be used to check the consistency of - // ProposalResponsePayload.proposalHash. For the CHAINCODE type, - // ProposalResponsePayload.proposalHash is supposed to be H(ProposalHeader || - // f(ChaincodeProposalPayload)) where f is the visibility function. - bytes chaincode_proposal_payload = 1; - - // The list of actions to apply to the ledger - ChaincodeEndorsedAction action = 2; + // This field contains the bytes of the ChaincodeProposalPayload message from + // the original invocation (essentially the arguments) after the application + // of the visibility function. The main visibility modes are "full" (the + // entire ChaincodeProposalPayload message is included here), "hash" (only + // the hash of the ChaincodeProposalPayload message is included) or + // "nothing". This field will be used to check the consistency of + // ProposalResponsePayload.proposalHash. For the CHAINCODE type, + // ProposalResponsePayload.proposalHash is supposed to be H(ProposalHeader || + // f(ChaincodeProposalPayload)) where f is the visibility function. + bytes chaincode_proposal_payload = 1; + + // The list of actions to apply to the ledger + ChaincodeEndorsedAction action = 2; } // ChaincodeEndorsedAction carries information about the endorsement of a // specific proposal message ChaincodeEndorsedAction { - - // This is the bytes of the ProposalResponsePayload message signed by the - // endorsers. Recall that for the CHAINCODE type, the - // ProposalResponsePayload's extenstion field carries a ChaincodeAction - bytes proposal_response_payload = 1; - - // The endorsement of the proposal, basically the endorser's signature over - // proposalResponsePayload - repeated Endorsement endorsements = 2; + // This is the bytes of the ProposalResponsePayload message signed by the + // endorsers. Recall that for the CHAINCODE type, the + // ProposalResponsePayload's extenstion field carries a ChaincodeAction + bytes proposal_response_payload = 1; + + // The endorsement of the proposal, basically the endorser's signature over + // proposalResponsePayload + repeated Endorsement endorsements = 2; } enum TxValidationCode { - VALID = 0; - NIL_ENVELOPE = 1; - BAD_PAYLOAD = 2; - BAD_COMMON_HEADER = 3; - BAD_CREATOR_SIGNATURE = 4; - INVALID_ENDORSER_TRANSACTION = 5; - INVALID_CONFIG_TRANSACTION = 6; - UNSUPPORTED_TX_PAYLOAD = 7; - BAD_PROPOSAL_TXID = 8; - DUPLICATE_TXID = 9; - ENDORSEMENT_POLICY_FAILURE = 10; - MVCC_READ_CONFLICT = 11; - PHANTOM_READ_CONFLICT = 12; - UNKNOWN_TX_TYPE = 13; - TARGET_CHAIN_NOT_FOUND = 14; - MARSHAL_TX_ERROR = 15; - NIL_TXACTION = 16; - EXPIRED_CHAINCODE = 17; - CHAINCODE_VERSION_CONFLICT = 18; - BAD_HEADER_EXTENSION = 19; - BAD_CHANNEL_HEADER = 20; - BAD_RESPONSE_PAYLOAD = 21; - BAD_RWSET = 22; - ILLEGAL_WRITESET = 23; - INVALID_WRITESET = 24; - INVALID_CHAINCODE = 25; - NOT_VALIDATED = 254; - INVALID_OTHER_REASON = 255; + VALID = 0; + NIL_ENVELOPE = 1; + BAD_PAYLOAD = 2; + BAD_COMMON_HEADER = 3; + BAD_CREATOR_SIGNATURE = 4; + INVALID_ENDORSER_TRANSACTION = 5; + INVALID_CONFIG_TRANSACTION = 6; + UNSUPPORTED_TX_PAYLOAD = 7; + BAD_PROPOSAL_TXID = 8; + DUPLICATE_TXID = 9; + ENDORSEMENT_POLICY_FAILURE = 10; + MVCC_READ_CONFLICT = 11; + PHANTOM_READ_CONFLICT = 12; + UNKNOWN_TX_TYPE = 13; + TARGET_CHAIN_NOT_FOUND = 14; + MARSHAL_TX_ERROR = 15; + NIL_TXACTION = 16; + EXPIRED_CHAINCODE = 17; + CHAINCODE_VERSION_CONFLICT = 18; + BAD_HEADER_EXTENSION = 19; + BAD_CHANNEL_HEADER = 20; + BAD_RESPONSE_PAYLOAD = 21; + BAD_RWSET = 22; + ILLEGAL_WRITESET = 23; + INVALID_WRITESET = 24; + INVALID_CHAINCODE = 25; + NOT_VALIDATED = 254; + INVALID_OTHER_REASON = 255; } // Reserved entries in the key-level metadata map enum MetaDataKeys { - VALIDATION_PARAMETER = 0; - VALIDATION_PARAMETER_V2 = 1; + VALIDATION_PARAMETER = 0; + VALIDATION_PARAMETER_V2 = 1; } diff --git a/src/main/proto/transientstore/transientstore.proto b/src/main/proto/transientstore/transientstore.proto new file mode 100644 index 00000000..1b6d577e --- /dev/null +++ b/src/main/proto/transientstore/transientstore.proto @@ -0,0 +1,22 @@ +// Copyright the Hyperledger Fabric contributors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package transientstore; + +option go_package = "github.com/hyperledger/fabric-protos-go/transientstore"; +option java_package = "org.hyperledger.fabric.protos.transientstore"; + +import "ledger/rwset/rwset.proto"; +import "common/collection.proto"; + +// TxPvtReadWriteSetWithConfigInfo encapsulates the transaction's private +// read-write set and additional information about the configurations such as +// the latest collection config when the transaction is simulated +message TxPvtReadWriteSetWithConfigInfo { + uint64 endorsed_at = 1; + rwset.TxPvtReadWriteSet pvt_rwset = 2; + map collection_configs = 3; +} diff --git a/src/test/java/org/hyperledger/fabric/sdk/ChannelTest.java b/src/test/java/org/hyperledger/fabric/sdk/ChannelTest.java index d386db04..fabc308e 100644 --- a/src/test/java/org/hyperledger/fabric/sdk/ChannelTest.java +++ b/src/test/java/org/hyperledger/fabric/sdk/ChannelTest.java @@ -39,8 +39,8 @@ import org.hyperledger.fabric.protos.common.Common; import org.hyperledger.fabric.protos.orderer.Ab; import org.hyperledger.fabric.protos.peer.Chaincode; -import org.hyperledger.fabric.protos.peer.FabricProposal; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalPackage; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.sdk.Channel.NOfEvents; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.PeerException; @@ -72,7 +72,6 @@ //CHECKSTYLE.ON: IllegalImport public class ChannelTest { - @Rule public ExpectedException thrown = ExpectedException.none(); @@ -85,7 +84,6 @@ public class ChannelTest { @BeforeClass public static void setupClient() { - try { hfclient = TestHFClient.newInstance(); @@ -95,7 +93,6 @@ public static void setupClient() { 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); @@ -105,25 +102,19 @@ Ab.BroadcastResponse sendTransaction(Common.Envelope transaction) throws Excepti 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()); - } } @Test public void testChannelCreation() { - try { - final String channelName = "channel3"; Channel testchannel = new Channel(channelName, hfclient); Assert.assertEquals(channelName, testchannel.getName()); @@ -131,16 +122,13 @@ public void testChannelCreation() { Assert.assertEquals(testchannel.getOrderers().size(), 0); Assert.assertEquals(testchannel.getPeers().size(), 0); Assert.assertEquals(testchannel.isInitialized(), false); - } catch (InvalidArgumentException e) { Assert.fail("Unexpected exception " + e.getMessage()); } - } @Test public void testChannelAddPeer() throws Exception { - final String channelName = "channel3"; final Channel testchannel = new Channel(channelName, hfclient); final Peer peer = hfclient.newPeer("peer_", "grpc://localhost:7051"); @@ -149,12 +137,10 @@ public void testChannelAddPeer() throws Exception { Assert.assertEquals(testchannel.getPeers().size(), 1); Assert.assertEquals(testchannel.getPeers().iterator().next(), peer); - } @Test public void testChannelAddOrder() throws Exception { - final Channel testChannel = new Channel(CHANNEL_NAME, hfclient); final Orderer orderer = hfclient.newOrderer("testorder", "grpc://localhost:7051"); @@ -162,17 +148,14 @@ public void testChannelAddOrder() throws Exception { Assert.assertEquals(testChannel.getOrderers().size(), 1); Assert.assertEquals(testChannel.getOrderers().iterator().next(), orderer); - } @Test public void testChannelNullClient() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel client is invalid can not be null."); new Channel(CHANNEL_NAME, null); - } @Test @@ -180,18 +163,14 @@ public void testChannelAddNullPeer() { Channel testChannel = null; try { - testChannel = new Channel(CHANNEL_NAME, hfclient); testChannel.addPeer(null); - Assert.fail("Expected set null peer to throw exception."); - } catch (InvalidArgumentException e) { Assert.assertEquals(testChannel.getPeers().size(), 0); Assert.assertTrue(e.getClass() == InvalidArgumentException.class); } - } @Test @@ -199,7 +178,6 @@ public void testChannelAddNoNamePeer() { Channel testChannel = null; try { - testChannel = new Channel(CHANNEL_NAME, hfclient); final Peer peer = hfclient.newPeer(null, "grpc://localhost:7051"); @@ -210,7 +188,6 @@ public void testChannelAddNoNamePeer() { Assert.assertEquals(testChannel.getPeers().size(), 0); Assert.assertTrue(e.getClass() == InvalidArgumentException.class); } - } @Test @@ -218,39 +195,30 @@ public void testChannelAddNullOrder() { Channel testChannel = null; try { - testChannel = new Channel(CHANNEL_NAME, hfclient); testChannel.addOrderer(null); - Assert.fail("Expected set null order to throw exception."); - } catch (InvalidArgumentException e) { Assert.assertEquals(testChannel.getOrderers().size(), 0); Assert.assertTrue(e.getClass() == InvalidArgumentException.class); } - } @Test public void testChannelInitialize() throws Exception { //test may not be doable once initialize is done - class MockChannel extends Channel { - MockChannel(String name, HFClient client) throws InvalidArgumentException { super(name, client); } @Override protected Map parseConfigBlock(boolean force) { - return null; } @Override - protected void loadCACertificates(boolean force) { - - } + protected void loadCACertificates(boolean force) { } } final Channel testChannel = new MockChannel(CHANNEL_NAME, hfclient); @@ -260,7 +228,6 @@ protected void loadCACertificates(boolean force) { assertFalse(testChannel.isInitialized()); testChannel.initialize(); Assert.assertTrue(testChannel.isInitialized()); - } // Allow no peers // @Test @@ -287,83 +254,66 @@ protected void loadCACertificates(boolean force) { @Test public void testChannelShutdown() { - try { - Assert.assertTrue(shutdownChannel.isShutdown()); - } catch (Exception e) { - Assert.assertTrue(e.getClass() == InvalidArgumentException.class); Assert.assertTrue(shutdownChannel.isInitialized()); } - } @Test public void testChannelShutdownAddPeer() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel shutdown has been shutdown."); Assert.assertTrue(shutdownChannel.isShutdown()); shutdownChannel.addPeer(hfclient.newPeer("name", "grpc://myurl:90")); - } @Test public void testChannelShutdownAddOrderer() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel shutdown has been shutdown."); Assert.assertTrue(shutdownChannel.isShutdown()); shutdownChannel.addOrderer(hfclient.newOrderer("name", "grpc://myurl:90")); - } @Test public void testChannelShutdownJoinPeer() throws Exception { - thrown.expect(ProposalException.class); thrown.expectMessage("Channel shutdown has been shutdown."); Assert.assertTrue(shutdownChannel.isShutdown()); shutdownChannel.joinPeer(hfclient.newPeer("name", "grpc://myurl:90")); - } @Test public void testChannelShutdownInitialize() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel shutdown has been shutdown."); shutdownChannel.initialize(); - } @Test public void testChannelShutdownInstiateProposal() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel shutdown has been shutdown."); Assert.assertTrue(shutdownChannel.isShutdown()); shutdownChannel.sendInstantiationProposal(hfclient.newInstantiationProposalRequest()); - } @Test public void testChannelShutdownQueryTransactionByIDl() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel shutdown has been shutdown."); Assert.assertTrue(shutdownChannel.isShutdown()); shutdownChannel.queryBlockByHash(new byte[] {}); - } @Test @@ -373,12 +323,10 @@ public void testChannelBadOrderer() throws Exception { CompletableFuture future = shutdownChannel.sendTransaction(null); future.get(); - } @Test public void testChannelBadPeerNull() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Peer value is null."); @@ -388,7 +336,6 @@ public void testChannelBadPeerNull() throws Exception { @Test public void testChannelBadPeerDoesNotBelong() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel channel does not have peer peer2"); @@ -399,12 +346,10 @@ public void testChannelBadPeerDoesNotBelong() throws Exception { createRunningChannel("testChannelBadPeerDoesNotBelong", peers); channel.sendInstantiationProposal(hfclient.newInstantiationProposalRequest(), peers); - } @Test public void testChannelBadPeerDoesNotBelong2() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Peer peer1 not set for channel channel"); @@ -417,12 +362,10 @@ public void testChannelBadPeerDoesNotBelong2() throws Exception { setField(peer, "channel", channel2); channel.sendInstantiationProposal(hfclient.newInstantiationProposalRequest()); - } @Test public void testChannelBadPeerCollection() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Peer value is null."); @@ -430,12 +373,10 @@ public void testChannelBadPeerCollection() throws Exception { channel.queryByChaincode(hfclient.newQueryProposalRequest(), Arrays.asList((Peer[]) new Peer[] {null})); - } @Test public void testChannelBadPeerCollectionEmpty() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Collection of peers is empty."); @@ -444,30 +385,25 @@ public void testChannelBadPeerCollectionEmpty() throws Exception { channel.sendUpgradeProposal(hfclient.newUpgradeProposalRequest(), Arrays.asList((Peer[]) new Peer[] {}) ); - } @Test public void testChannelBadPeerCollectionNull() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Collection of peers is null."); final Channel channel = createRunningChannel(null); channel.sendTransactionProposal(hfclient.newTransactionProposalRequest(), null); - } @Test public void testTwoChannelsSameName() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel by the name testTwoChannelsSameName already exists"); createRunningChannel("testTwoChannelsSameName", null); createRunningChannel("testTwoChannelsSameName", null); - } @Test @@ -552,7 +488,6 @@ public void testMspidPeers() throws Exception { assertTrue(channel.getPeersForOrganization("fud").isEmpty()); assertTrue(channel.getPeersForOrganization("blah").isEmpty()); - } @Test @@ -641,7 +576,6 @@ public void testMspidOrderers() throws Exception { @Test public void testSD() throws Exception { - Channel sd = createRunningChannel("testTwoChannelsSameName", null); Class[] declaredClasses = Channel.class.getDeclaredClasses(); @@ -729,7 +663,6 @@ public Map getEndpointMap() { peer = sd.sdPeerAddition.addPeer(sdPeerAdditionInfo); properties = peer.getProperties(); assertArrayEquals(new byte[] {88, 2, 4}, (byte[]) properties.get("clientKeyBytes")); - } static final String CHANNEL_NAME2 = "channel"; @@ -743,7 +676,6 @@ public static Channel createRunningChannel(Collection peers) throws Invali } public static Channel createRunningChannel(String channelName, Collection peers) throws InvalidArgumentException, NoSuchFieldException, IllegalAccessException { - Channel channel = hfclient.newChannel(channelName); if (peers == null) { Peer peer = hfclient.newPeer("peer1", "grpc://localhost:22"); @@ -752,19 +684,16 @@ public static Channel createRunningChannel(String channelName, Collection } else { for (Peer peer : peers) { channel.addPeer(peer); - } } setField(channel, "initialized", true); return channel; - } @Test public void testChannelBadPeerDoesNotBelongJoin() throws Exception { - thrown.expect(ProposalException.class); thrown.expectMessage("Can not add peer peer2 to channel testChannelBadPeerDoesNotBelongJoin because it already belongs to channel testChannelBadPeerDoesNotBelongJoin2"); @@ -777,12 +706,10 @@ public void testChannelBadPeerDoesNotBelongJoin() throws Exception { //Peer joining channel when it belongs to another channel. channel.joinPeer(peers.iterator().next()); - } @Test public void testChannelPeerJoinNoOrderer() throws Exception { - thrown.expect(ProposalException.class); thrown.expectMessage("Channel channel does not have any orderers associated with it."); @@ -793,12 +720,10 @@ public void testChannelPeerJoinNoOrderer() throws Exception { //Peer joining channel were no orderer is there .. not likely. channel.joinPeer(hfclient.newPeer("peerJoiningNOT", "grpc://localhost:22")); - } @Test public void testChannelInitNoname() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Can not initialize channel without a valid name."); @@ -806,12 +731,10 @@ public void testChannelInitNoname() throws Exception { setField(channel, "name", null); channel.initialize(); - } @Test public void testChannelInitNullClient() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Can not initialize channel without a client object."); @@ -819,62 +742,52 @@ public void testChannelInitNullClient() throws Exception { setField(channel, "client", null); channel.initialize(); - } @Test public void testChannelsendInstantiationProposalNull() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("InstantiateProposalRequest is null"); final Channel channel = createRunningChannel(null); channel.sendInstantiationProposal(null); - } @Test public void testChannelsendInstallProposalNull() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("InstallProposalRequest is null"); final Channel channel = createRunningChannel(null); channel.sendInstallProposal(null); - } @Test public void testChannelsendUpgradeProposalNull() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Upgradeproposal is null"); final Channel channel = createRunningChannel(null); channel.sendUpgradeProposal(null); - } //queryBlockByHash @Test public void testChannelQueryBlockByHashNull() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("blockHash parameter is null."); final Channel channel = createRunningChannel(null); channel.queryBlockByHash(null); - } @Test public void testChannelQueryBlockByHashNotInitialized() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel channel has not been initialized."); @@ -882,36 +795,30 @@ public void testChannelQueryBlockByHashNotInitialized() throws Exception { setField(channel, "initialized", false); channel.queryBlockByHash("hyper this hyper that".getBytes()); - } @Test public void testChannelQueryBlockByTransactionIDNull() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("TxID parameter is null."); final Channel channel = createRunningChannel(null); channel.queryBlockByTransactionID(null); - } @Test public void testChannelQueryTransactionByIDNull() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("TxID parameter is null."); final Channel channel = createRunningChannel(null); channel.queryTransactionByID(null); - } @Test public void testQueryInstalledChaincodesThrowInterrupted() throws Exception { - thrown.expect(ProposalException.class); thrown.expectMessage("You interrupting me?"); @@ -921,12 +828,10 @@ public void testQueryInstalledChaincodesThrowInterrupted() throws Exception { setField(peer, "endorserClent", new MockEndorserClient(new InterruptedException("You interrupting me?"))); hfclient.queryChannels(peer); - } @Test public void testQueryInstalledChaincodesThrowPeerException() throws Exception { - thrown.expect(ProposalException.class); thrown.expectMessage("rick did this:)"); @@ -936,12 +841,10 @@ public void testQueryInstalledChaincodesThrowPeerException() throws Exception { setField(peer, "endorserClent", new MockEndorserClient(new PeerException("rick did this:)"))); hfclient.queryChannels(peer); - } @Test public void testQueryInstalledChaincodesThrowTimeoutException() throws Exception { - thrown.expect(ProposalException.class); thrown.expectMessage("What time is it?"); @@ -951,43 +854,38 @@ public void testQueryInstalledChaincodesThrowTimeoutException() throws Exception setField(peer, "endorserClent", new MockEndorserClient(new PeerException("What time is it?"))); hfclient.queryChannels(peer); - } @Test public void testQueryInstalledChaincodesERROR() throws Exception { - thrown.expect(Error.class); thrown.expectMessage("Error bad bad bad"); final Channel channel = createRunningChannel(null); Peer peer = channel.getPeers().iterator().next(); - final CompletableFuture settableFuture = new CompletableFuture<>(); + final CompletableFuture settableFuture = new CompletableFuture<>(); // settableFuture.setException(new Error("Error bad bad bad")); settableFuture.completeExceptionally(new Error("Error bad bad bad")); setField(peer, "endorserClent", new MockEndorserClient(settableFuture)); hfclient.queryChannels(peer); - } @Test public void testQueryInstalledChaincodesStatusRuntimeException() throws Exception { - thrown.expect(ProposalException.class); thrown.expectMessage("ABORTED"); final Channel channel = createRunningChannel(null); Peer peer = channel.getPeers().iterator().next(); - final CompletableFuture settableFuture = new CompletableFuture<>(); + final CompletableFuture settableFuture = new CompletableFuture<>(); settableFuture.completeExceptionally(new StatusRuntimeException(Status.ABORTED)); setField(peer, "endorserClent", new MockEndorserClient(settableFuture)); hfclient.queryChannels(peer); - } private static final String SAMPLE_GO_CC = "src/test/fixture/sdkintegration/gocc/sample1"; @@ -1010,9 +908,9 @@ public void testProposalBuilderWithMetaInf() throws Exception { installProposalBuilder.context(transactionContext); - FabricProposal.Proposal proposal = installProposalBuilder.build(); // Build it get the proposal. Then unpack it to see if it's what we expect. + ProposalPackage.Proposal proposal = installProposalBuilder.build(); // Build it get the proposal. Then unpack it to see if it's what we expect. - FabricProposal.ChaincodeProposalPayload chaincodeProposalPayload = FabricProposal.ChaincodeProposalPayload.parseFrom(proposal.getPayload()); + ProposalPackage.ChaincodeProposalPayload chaincodeProposalPayload = ProposalPackage.ChaincodeProposalPayload.parseFrom(proposal.getPayload()); Chaincode.ChaincodeInvocationSpec chaincodeInvocationSpec = Chaincode.ChaincodeInvocationSpec.parseFrom(chaincodeProposalPayload.getInput()); Chaincode.ChaincodeSpec chaincodeSpec = chaincodeInvocationSpec.getChaincodeSpec(); Chaincode.ChaincodeInput input = chaincodeSpec.getInput(); @@ -1044,8 +942,8 @@ public void testProposalBuilderWithOutMetaInf() throws Exception { installProposalBuilder.context(transactionContext); - FabricProposal.Proposal proposal = installProposalBuilder.build(); // Build it get the proposal. Then unpack it to see if it's what we expect. - FabricProposal.ChaincodeProposalPayload chaincodeProposalPayload = FabricProposal.ChaincodeProposalPayload.parseFrom(proposal.getPayload()); + ProposalPackage.Proposal proposal = installProposalBuilder.build(); // Build it get the proposal. Then unpack it to see if it's what we expect. + ProposalPackage.ChaincodeProposalPayload chaincodeProposalPayload = ProposalPackage.ChaincodeProposalPayload.parseFrom(proposal.getPayload()); Chaincode.ChaincodeInvocationSpec chaincodeInvocationSpec = Chaincode.ChaincodeInvocationSpec.parseFrom(chaincodeProposalPayload.getInput()); Chaincode.ChaincodeSpec chaincodeSpec = chaincodeInvocationSpec.getChaincodeSpec(); Chaincode.ChaincodeInput input = chaincodeSpec.getInput(); @@ -1062,7 +960,6 @@ public void testProposalBuilderWithOutMetaInf() throws Exception { @Test public void testProposalBuilderWithNoMetaInfDir() throws Exception { - thrown.expect(java.lang.IllegalArgumentException.class); thrown.expectMessage(matchesRegex("The META-INF directory does not exist in.*src.test.fixture.meta-infs.test1.META-INF")); @@ -1085,7 +982,6 @@ public void testProposalBuilderWithNoMetaInfDir() throws Exception { @Test public void testProposalBuilderWithMetaInfExistsNOT() throws Exception { - thrown.expect(java.lang.IllegalArgumentException.class); thrown.expectMessage(matchesRegex("Directory to find chaincode META-INF.*tmp.fdsjfksfj.fjksfjskd.fjskfjdsk.should never exist does not exist")); @@ -1108,7 +1004,6 @@ public void testProposalBuilderWithMetaInfExistsNOT() throws Exception { @Test public void testNOf() throws Exception { - Peer peer1Org1 = new Peer("peer1Org1", "grpc://localhost:9", null); Peer peer1Org12nd = new Peer("org12nd", "grpc://localhost:9", null); Peer peer2Org2 = new Peer("peer2Org2", "grpc://localhost:9", null); @@ -1156,12 +1051,10 @@ public void testNOf() throws Exception { nOfEvents = NOfEvents.createNoEvents(); assertTrue(nOfEvents.ready); - } @Test public void testProposalBuilderWithMetaInfEmpty() throws Exception { - thrown.expect(java.lang.IllegalArgumentException.class); thrown.expectMessage(matchesRegex("The META-INF directory.*src.test.fixture.meta-infs.emptyMetaInf.META-INF is empty\\.")); @@ -1185,85 +1078,73 @@ public void testProposalBuilderWithMetaInfEmpty() throws Exception { installProposalBuilder.context(transactionContext); - FabricProposal.Proposal proposal = installProposalBuilder.build(); // Build it get the proposal. Then unpack it to see if it's what we epect. + ProposalPackage.Proposal proposal = installProposalBuilder.build(); // Build it get the proposal. Then unpack it to see if it's what we epect. } //testing of blocklistner @Test public void testRegisterBlockListenerNULL() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("BlockEventQueue parameter is null."); Channel channel = hfclient.newChannel("testRegisterBlockListenerNULL"); BlockingQueue nblis = null; channel.registerBlockListener(nblis); - } @Test public void testRegisterBlockListenerNULL2() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("BlockEventQueue parameter is null."); Channel channel = hfclient.newChannel("testRegisterBlockListenerNULL2"); BlockingQueue nblis = null; channel.registerBlockListener(nblis, 10, TimeUnit.SECONDS); - } @Test public void testRegisterBlockListenerBadArg() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Timeout parameter must be greater than 0 not -1"); Channel channel = hfclient.newChannel("testRegisterBlockListenerBadArg"); BlockingQueue nblis = null; channel.registerBlockListener(new LinkedBlockingQueue<>(), -1, TimeUnit.SECONDS); - } @Test public void testRegisterBlockListenerBadNULLArg() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("TimeUnit parameter must not be null."); Channel channel = hfclient.newChannel("testRegisterBlockListenerBadNULLArg"); channel.registerBlockListener(new LinkedBlockingQueue<>(), 10, null); - } @Test public void testRegisterBlockListenerShutdown() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel testRegisterBlockListenerShutdown has been shutdown."); Channel channel = hfclient.newChannel("testRegisterBlockListenerShutdown"); channel.shutdown(false); channel.registerBlockListener(new LinkedBlockingQueue<>(), 10, TimeUnit.SECONDS); - } @Test public void testRegisterBlockListenerShutdown2() throws Exception { - thrown.expect(InvalidArgumentException.class); thrown.expectMessage("Channel testRegisterBlockListenerShutdown2 has been shutdown."); Channel channel = hfclient.newChannel("testRegisterBlockListenerShutdown2"); channel.shutdown(false); channel.registerBlockListener(new LinkedBlockingQueue<>()); - } class MockEndorserClient extends EndorserClient { final Throwable throwThis; - private final CompletableFuture returnedFuture; + private final CompletableFuture returnedFuture; MockEndorserClient(Throwable throwThis) { super("blahchannlname", "blahpeerName", "blahURL", new Endpoint("grpc://loclhost:99", null).getChannelBuilder()); @@ -1274,26 +1155,23 @@ class MockEndorserClient extends EndorserClient { this.returnedFuture = null; } - MockEndorserClient(CompletableFuture returnedFuture) { + MockEndorserClient(CompletableFuture returnedFuture) { super("blahchannlname", "blahpeerName", "blahURL", new Endpoint("grpc://loclhost:99", null).getChannelBuilder()); this.throwThis = null; this.returnedFuture = returnedFuture; } @Override - public CompletableFuture sendProposalAsync(FabricProposal.SignedProposal proposal) { + public CompletableFuture sendProposalAsync(ProposalPackage.SignedProposal proposal) { if (throwThis != null) { getUnsafe().throwException(throwThis); } return returnedFuture; - } @Override public boolean isChannelActive() { - return true; - } private Unsafe getUnsafe() { //lets us throw undeclared exceptions. diff --git a/src/test/java/org/hyperledger/fabric/sdk/PeerTest.java b/src/test/java/org/hyperledger/fabric/sdk/PeerTest.java index c24b7bb1..e208bb37 100644 --- a/src/test/java/org/hyperledger/fabric/sdk/PeerTest.java +++ b/src/test/java/org/hyperledger/fabric/sdk/PeerTest.java @@ -17,7 +17,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.exception.PeerException; import org.hyperledger.fabric.sdk.testutils.TestUtils; @@ -56,7 +56,6 @@ public void testGetName() { } catch (InvalidArgumentException e) { Assert.fail("Unexpected Exeception " + e.getMessage()); } - } @Test (expected = InvalidArgumentException.class) @@ -73,7 +72,7 @@ public void testSetEmptyName() throws InvalidArgumentException { @Test (expected = Exception.class) public void testSendAsyncNullProposal() throws PeerException, InvalidArgumentException, ExecutionException, InterruptedException { - Future future = peer.sendProposalAsync(null); + Future future = peer.sendProposalAsync(null); future.get(); } @@ -96,9 +95,7 @@ public void testDuplicateChannel() throws InvalidArgumentException { @Test public void getPeerEventingServiceDisconnectedTest() throws InvalidArgumentException { Peer somePeer = hfclient.newPeer("somePeer", "grpc://localhost:4"); - final Peer.PeerEventingServiceDisconnected disconnectedHandlerExpect = (Peer.PeerEventingServiceDisconnected) TestUtils.getField(somePeer, "disconnectedHandler"); - Peer.PeerEventingServiceDisconnected disconnectedHandler = somePeer.getPeerEventingServiceDisconnected(); Assert.assertSame(disconnectedHandlerExpect, disconnectedHandler); @@ -106,12 +103,8 @@ public void getPeerEventingServiceDisconnectedTest() throws InvalidArgumentExcep Peer.PeerEventingServiceDisconnected peerEventingServiceDisconnectedCurrent = somePeer.setPeerEventingServiceDisconnected(null); Assert.assertSame(disconnectedHandlerExpect, peerEventingServiceDisconnectedCurrent); - Assert.assertNull(somePeer.getPeerEventingServiceDisconnected()); - Assert.assertNull(somePeer.setPeerEventingServiceDisconnected(disconnectedHandlerExpect)); - Assert.assertSame(disconnectedHandlerExpect, somePeer.getPeerEventingServiceDisconnected()); - } } diff --git a/src/test/java/org/hyperledger/fabric/sdk/identity/IdemixIdentitiesTest.java b/src/test/java/org/hyperledger/fabric/sdk/identity/IdemixIdentitiesTest.java index 11fd643f..f7904003 100644 --- a/src/test/java/org/hyperledger/fabric/sdk/identity/IdemixIdentitiesTest.java +++ b/src/test/java/org/hyperledger/fabric/sdk/identity/IdemixIdentitiesTest.java @@ -35,7 +35,7 @@ import org.hyperledger.fabric.protos.common.MspPrincipal; import org.hyperledger.fabric.protos.idemix.Idemix; import org.hyperledger.fabric.protos.msp.Identities; -import org.hyperledger.fabric.protos.msp.MspConfig.IdemixMSPSignerConfig; +import org.hyperledger.fabric.protos.msp.MspConfigPackage; import org.hyperledger.fabric.sdk.exception.CryptoException; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.idemix.IdemixCredential; @@ -90,7 +90,7 @@ public class IdemixIdentitiesTest { public static void setup() { // Parse crypto material from files - IdemixMSPSignerConfig signerConfig = null; + MspConfigPackage.IdemixMSPSignerConfig signerConfig = null; try { signerConfig = readIdemixMSPConfig(TEST_PATH + MSP1OU1 + USER_PATH, SIGNER_CONFIG); } catch (Exception e) { @@ -175,7 +175,7 @@ public void testIdemixSigningIdentityBroken() throws IOException { // Test creating a signer config @Test public void testIdemixMSPSignerConfigSuccess() { - IdemixMSPSignerConfig signerConfig = null; + MspConfigPackage.IdemixMSPSignerConfig signerConfig = null; try { signerConfig = readIdemixMSPConfig(TEST_PATH + MSP1OU1 + USER_PATH, SIGNER_CONFIG); } catch (InvalidProtocolBufferException e) { @@ -402,7 +402,7 @@ public boolean testSigning(IdemixSigningIdentity signIdentity, byte[] msg, byte[ * @throws InvalidProtocolBufferException */ private IdemixSigningIdentity createIdemixSigningIdentity(String mspId) throws CryptoException, InvalidArgumentException, IOException, InvalidKeySpecException, NoSuchAlgorithmException { - IdemixMSPSignerConfig signerConfig = null; + MspConfigPackage.IdemixMSPSignerConfig signerConfig = null; signerConfig = readIdemixMSPConfig(TEST_PATH + mspId + USER_PATH, SIGNER_CONFIG); assertNotNull(signerConfig); @@ -432,11 +432,11 @@ private IdemixSigningIdentity createIdemixSigningIdentity(String mspId) throws C * @param id * @return IdemixMSPSignerConfig proto */ - public static IdemixMSPSignerConfig readIdemixMSPConfig(String configPath, String id) throws IOException { + public static MspConfigPackage.IdemixMSPSignerConfig readIdemixMSPConfig(String configPath, String id) throws IOException { Path path = Paths.get(configPath + id); byte[] data = Files.readAllBytes(path); - IdemixMSPSignerConfig signerConfig = IdemixMSPSignerConfig.parseFrom(data); + MspConfigPackage.IdemixMSPSignerConfig signerConfig = MspConfigPackage.IdemixMSPSignerConfig.parseFrom(data); return signerConfig; } diff --git a/src/test/java/org/hyperledger/fabric/sdk/security/TLSCertGenTest.java b/src/test/java/org/hyperledger/fabric/sdk/security/TLSCertGenTest.java index ded0add8..477a4f38 100644 --- a/src/test/java/org/hyperledger/fabric/sdk/security/TLSCertGenTest.java +++ b/src/test/java/org/hyperledger/fabric/sdk/security/TLSCertGenTest.java @@ -23,7 +23,6 @@ import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; - import javax.net.ssl.SSLSession; import io.grpc.Grpc; @@ -41,8 +40,8 @@ import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import org.hyperledger.fabric.protos.peer.EndorserGrpc; -import org.hyperledger.fabric.protos.peer.FabricProposal; -import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.ProposalPackage; +import org.hyperledger.fabric.protos.peer.ProposalResponsePackage; import org.hyperledger.fabric.sdk.security.certgen.TLSCertificateBuilder; import org.hyperledger.fabric.sdk.security.certgen.TLSCertificateKeyPair; import org.junit.AfterClass; @@ -95,7 +94,7 @@ public void selfSignedTLSCertTest() throws Exception { .sslContext(getSslContextBuilder(clientCertFile, clientKeyFile, serverCertFile).protocols(TLS_PROTOCOL).build()) .negotiationType(NegotiationType.TLS); ManagedChannel chan = channelBuilder.build(); - FabricProposal.SignedProposal prop = FabricProposal.SignedProposal.getDefaultInstance(); + ProposalPackage.SignedProposal prop = ProposalPackage.SignedProposal.getDefaultInstance(); EndorserGrpc.newBlockingStub(chan).processProposal(prop); // Ensure that TLS handshake occurred Assert.assertTrue("Handshake didn't occur", handshakeOccured.get()); @@ -144,9 +143,9 @@ private static File createFile(String path, byte[] data) throws IOException { } private static class MockEndorser extends EndorserGrpc.EndorserImplBase { - public void processProposal(org.hyperledger.fabric.protos.peer.FabricProposal.SignedProposal request, - io.grpc.stub.StreamObserver responseObserver) { - responseObserver.onNext(FabricProposalResponse.ProposalResponse.newBuilder().getDefaultInstanceForType()); + public void processProposal(org.hyperledger.fabric.protos.peer.ProposalPackage.SignedProposal request, + io.grpc.stub.StreamObserver responseObserver) { + responseObserver.onNext(ProposalResponsePackage.ProposalResponse.newBuilder().getDefaultInstanceForType()); responseObserver.onCompleted(); } } diff --git a/src/test/java/org/hyperledger/fabric/sdkintegration/End2endIT.java b/src/test/java/org/hyperledger/fabric/sdkintegration/End2endIT.java index 56be5dd4..7a1f5758 100644 --- a/src/test/java/org/hyperledger/fabric/sdkintegration/End2endIT.java +++ b/src/test/java/org/hyperledger/fabric/sdkintegration/End2endIT.java @@ -357,7 +357,6 @@ class ChaincodeEventCapture { //A test class to capture chaincode events String chaincodeEventListenerHandle = channel.registerChaincodeEventListener(Pattern.compile(".*"), Pattern.compile(Pattern.quote(EXPECTED_EVENT_NAME)), (handle, blockEvent, chaincodeEvent) -> { - chaincodeEvents.add(new ChaincodeEventCapture(handle, blockEvent, chaincodeEvent)); String es = blockEvent.getPeer() != null ? blockEvent.getPeer().getName() : "peer was null!!!"; @@ -367,14 +366,12 @@ class ChaincodeEventCapture { //A test class to capture chaincode events chaincodeEvent.getEventName(), chaincodeEvent.getTxId(), new String(chaincodeEvent.getPayload()), es); - }); //For non foo channel unregister event listener to test events are not called. if (!isFooChain) { channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle); chaincodeEventListenerHandle = null; - } ///////////////////////////////////////////////////////////////////////////////////////////////// @@ -402,7 +399,6 @@ class ChaincodeEventCapture { //A test class to capture chaincode events .setVersion(CHAIN_CODE_VERSION); if (null != CHAIN_CODE_PATH) { chaincodeIDBuilder.setPath(CHAIN_CODE_PATH); - } chaincodeID = chaincodeIDBuilder.build(); @@ -533,9 +529,7 @@ policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in ei out("Received %d instantiate proposal responses. Successful+verified: %d . Failed: %d", responses.size(), successful.size(), failed.size()); if (failed.size() > 0) { for (ProposalResponse fail : failed) { - out("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + fail.getMessage() + ", on peer" + fail.getPeer()); - } ProposalResponse first = failed.iterator().next(); fail("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + first.getMessage() + ". Was verified:" + first.isVerified()); @@ -559,12 +553,11 @@ policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in ei .orderers(channel.getOrderers()) // specify the orderers we want to try this transaction. Fails once all Orderers are tried. .nOfEvents(nOfEvents) // The events to signal the completion of the interest in the transaction ).thenApply(transactionEvent -> { - waitOnFabric(0); assertTrue(transactionEvent.isValid()); // must be valid to be here. - assertNotNull(transactionEvent.getSignature()); //musth have a signature. + BlockEvent blockEvent = transactionEvent.getBlockEvent(); // This is the blockevent that has this transaction. assertNotNull(blockEvent.getBlock()); // Make sure the RAW Fabric block is returned. @@ -592,7 +585,6 @@ policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in ei tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8)); // ditto tm2.put("result", ":)".getBytes(UTF_8)); // This should be returned in the payload see chaincode why. if (Type.GO_LANG.equals(CHAIN_CODE_LANG) && testConfig.isFabricVersionAtOrAfter("1.2")) { - expectedMoveRCMap.put(channelName, random.nextInt(300) + 100L); // the chaincode will return this as status see chaincode why. tm2.put("rc", (expectedMoveRCMap.get(channelName) + "").getBytes(UTF_8)); // This should be returned see chaincode why. // 400 and above results in the peer not endorsing! @@ -658,11 +650,8 @@ policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in ei final String path = cid.getPath(); if (null == CHAIN_CODE_PATH) { assertTrue(path == null || "".equals(path)); - } else { - assertEquals(CHAIN_CODE_PATH, path); - } assertEquals(CHAIN_CODE_NAME, cid.getName()); @@ -672,7 +661,6 @@ policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in ei // Send Transaction Transaction to orderer out("Sending chaincode transaction(move a,b,100) to orderer."); return channel.sendTransaction(successful).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS); - } catch (Exception e) { out("Caught an exception while invoking chaincode"); e.printStackTrace(); @@ -680,10 +668,8 @@ policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in ei } return null; - }).thenApply(transactionEvent -> { try { - waitOnFabric(0); assertTrue(transactionEvent.isValid()); // must be valid to be here. @@ -782,7 +768,6 @@ policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in ei + "\n validation code " + txInfo.getValidationCode().getNumber()); if (chaincodeEventListenerHandle != null) { - channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle); final int numberEventsExpected = @@ -807,9 +792,7 @@ policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in ei BlockEvent blockEvent = chaincodeEventCapture.blockEvent; assertEquals(channelName, blockEvent.getChannelId()); - } - } else { assertTrue(chaincodeEvents.isEmpty()); } @@ -840,7 +823,6 @@ Channel constructChannel(String name, HFClient client, SampleOrg sampleOrg) thro Collection orderers = new LinkedList<>(); for (String orderName : sampleOrg.getOrdererNames()) { - Properties ordererProperties = testConfig.getOrdererProperties(orderName); //example of setting keepAlive to avoid timeouts on inactive http2 connections. @@ -881,7 +863,6 @@ Channel constructChannel(String name, HFClient client, SampleOrg sampleOrg) thro Peer peer = client.newPeer(peerName, peerLocation, peerProperties); if (testConfig.isFabricVersionAtOrAfter("1.3")) { newChannel.joinPeer(peer, createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.ENDORSING_PEER, PeerRole.LEDGER_QUERY, PeerRole.CHAINCODE_QUERY, PeerRole.EVENT_SOURCE))); //Default is all roles. - } else { if (doPeerEventing && everyother) { newChannel.joinPeer(peer, createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.ENDORSING_PEER, PeerRole.LEDGER_QUERY, PeerRole.CHAINCODE_QUERY, PeerRole.EVENT_SOURCE))); //Default is all roles. @@ -913,12 +894,10 @@ Channel constructChannel(String name, HFClient client, SampleOrg sampleOrg) thro newChannel.shutdown(true); return client.deSerializeChannel(serializedChannelBytes).initialize(); - } private void waitOnFabric(int additional) { //NOOP today - } void blockWalker(HFClient client, Channel channel) throws InvalidArgumentException, ProposalException, IOException { @@ -1008,9 +987,8 @@ void blockWalker(HFClient client, Channel channel) throws InvalidArgumentExcepti assertEquals(CHAIN_CODE_NAME, chaincodeEvent.getChaincodeId()); assertEquals(EXPECTED_EVENT_NAME, chaincodeEvent.getEventName()); assertEquals(CHAIN_CODE_NAME, chaincodeIDName); - assertEquals("github.com/example_cc", chaincodeIDPath); + assertEquals(CHAIN_CODE_PATH, chaincodeIDPath); assertEquals("1", chaincodeIDVersion); - } TxReadWriteSetInfo rwsetInfo = transactionActionInfo.getTxReadWriteSet(); @@ -1076,7 +1054,6 @@ void blockWalker(HFClient client, Channel channel) throws InvalidArgumentExcepti } assertEquals(transactionCount, returnedBlock.getTransactionCount()); - } } if (!TX_EXPECTED.isEmpty()) {