Search in sources :

Example 91 with ByteString

use of org.apache.beam.vendor.grpc.v1p26p0.com.google.protobuf.ByteString in project fabric-sdk-java by hyperledger.

the class Channel method sendUpdateChannel.

private void sendUpdateChannel(byte[] configupdate, byte[][] signers, Orderer orderer) throws TransactionException, InvalidArgumentException {
    logger.debug(format("Channel %s sendUpdateChannel", name));
    checkOrderer(orderer);
    try {
        final long nanoTimeStart = System.nanoTime();
        int statusCode = 0;
        do {
            // Make sure we have fresh transaction context for each try just to be safe.
            TransactionContext transactionContext = getTransactionContext();
            ConfigUpdateEnvelope.Builder configUpdateEnvBuilder = ConfigUpdateEnvelope.newBuilder();
            configUpdateEnvBuilder.setConfigUpdate(ByteString.copyFrom(configupdate));
            for (byte[] signer : signers) {
                configUpdateEnvBuilder.addSignatures(ConfigSignature.parseFrom(signer));
            }
            // --------------
            // Construct Payload Envelope.
            final ByteString sigHeaderByteString = getSignatureHeaderAsByteString(transactionContext);
            final ChannelHeader payloadChannelHeader = ProtoUtils.createChannelHeader(HeaderType.CONFIG_UPDATE, transactionContext.getTxID(), name, transactionContext.getEpoch(), transactionContext.getFabricTimestamp(), null, null);
            final Header payloadHeader = Header.newBuilder().setChannelHeader(payloadChannelHeader.toByteString()).setSignatureHeader(sigHeaderByteString).build();
            final ByteString payloadByteString = Payload.newBuilder().setHeader(payloadHeader).setData(configUpdateEnvBuilder.build().toByteString()).build().toByteString();
            ByteString payloadSignature = transactionContext.signByteStrings(payloadByteString);
            Envelope payloadEnv = Envelope.newBuilder().setSignature(payloadSignature).setPayload(payloadByteString).build();
            BroadcastResponse trxResult = orderer.sendTransaction(payloadEnv);
            statusCode = trxResult.getStatusValue();
            logger.debug(format("Channel %s sendUpdateChannel %d", name, statusCode));
            if (statusCode == 404 || statusCode == 503) {
                // these we can retry..
                final long duration = TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanoTimeStart, TimeUnit.NANOSECONDS);
                if (duration > CHANNEL_CONFIG_WAIT_TIME) {
                    // waited long enough .. throw an exception
                    String info = trxResult.getInfo();
                    if (null == info) {
                        info = "";
                    }
                    throw new TransactionException(format("Channel %s update error timed out after %d ms. Status value %d. Status %s. %s", name, duration, statusCode, trxResult.getStatus().name(), info));
                }
                try {
                    // try again sleep
                    Thread.sleep(ORDERER_RETRY_WAIT_TIME);
                } catch (InterruptedException e) {
                    TransactionException te = new TransactionException("update thread Sleep", e);
                    logger.warn(te.getMessage(), te);
                }
            } else if (200 != statusCode) {
                // Can't retry.
                String info = trxResult.getInfo();
                if (null == info) {
                    info = "";
                }
                throw new TransactionException(format("New channel %s error. StatusValue %d. Status %s. %s", name, statusCode, "" + trxResult.getStatus(), info));
            }
        } while (// try again
        200 != statusCode);
    } catch (TransactionException e) {
        logger.error(format("Channel %s error: %s", name, e.getMessage()), e);
        throw e;
    } catch (Exception e) {
        String msg = format("Channel %s error: %s", name, e.getMessage());
        logger.error(msg, e);
        throw new TransactionException(msg, e);
    }
}
Also used : ConfigUpdateEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigUpdateEnvelope) BroadcastResponse(org.hyperledger.fabric.protos.orderer.Ab.BroadcastResponse) ProtoUtils.getSignatureHeaderAsByteString(org.hyperledger.fabric.sdk.transaction.ProtoUtils.getSignatureHeaderAsByteString) ByteString(com.google.protobuf.ByteString) ProtoUtils.getSignatureHeaderAsByteString(org.hyperledger.fabric.sdk.transaction.ProtoUtils.getSignatureHeaderAsByteString) ByteString(com.google.protobuf.ByteString) ConfigEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigEnvelope) ConfigUpdateEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigUpdateEnvelope) Envelope(org.hyperledger.fabric.protos.common.Common.Envelope) ProtoUtils.createSeekInfoEnvelope(org.hyperledger.fabric.sdk.transaction.ProtoUtils.createSeekInfoEnvelope) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StatusRuntimeException(io.grpc.StatusRuntimeException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) TimeoutException(java.util.concurrent.TimeoutException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) Header(org.hyperledger.fabric.protos.common.Common.Header) ChannelHeader(org.hyperledger.fabric.protos.common.Common.ChannelHeader) ChannelHeader(org.hyperledger.fabric.protos.common.Common.ChannelHeader) TransactionContext(org.hyperledger.fabric.sdk.transaction.TransactionContext)

Example 92 with ByteString

use of org.apache.beam.vendor.grpc.v1p26p0.com.google.protobuf.ByteString in project fabric-sdk-java by hyperledger.

the class Channel method getChannelConfigurationSignature.

byte[] getChannelConfigurationSignature(ChannelConfiguration channelConfiguration, User signer) throws InvalidArgumentException {
    userContextCheck(signer);
    if (null == channelConfiguration) {
        throw new InvalidArgumentException("channelConfiguration is null");
    }
    try {
        Envelope ccEnvelope = Envelope.parseFrom(channelConfiguration.getChannelConfigurationAsBytes());
        final Payload ccPayload = Payload.parseFrom(ccEnvelope.getPayload());
        TransactionContext transactionContext = getTransactionContext(signer);
        final ConfigUpdateEnvelope configUpdateEnv = ConfigUpdateEnvelope.parseFrom(ccPayload.getData());
        final ByteString configUpdate = configUpdateEnv.getConfigUpdate();
        ByteString sigHeaderByteString = getSignatureHeaderAsByteString(signer, transactionContext);
        ByteString signatureByteSting = transactionContext.signByteStrings(new User[] { signer }, sigHeaderByteString, configUpdate)[0];
        return ConfigSignature.newBuilder().setSignatureHeader(sigHeaderByteString).setSignature(signatureByteSting).build().toByteArray();
    } catch (Exception e) {
        throw new InvalidArgumentException(e);
    } finally {
        logger.debug("finally done");
    }
}
Also used : ConfigUpdateEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigUpdateEnvelope) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TransactionContext(org.hyperledger.fabric.sdk.transaction.TransactionContext) ProtoUtils.getSignatureHeaderAsByteString(org.hyperledger.fabric.sdk.transaction.ProtoUtils.getSignatureHeaderAsByteString) ByteString(com.google.protobuf.ByteString) Payload(org.hyperledger.fabric.protos.common.Common.Payload) ConfigEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigEnvelope) ConfigUpdateEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigUpdateEnvelope) Envelope(org.hyperledger.fabric.protos.common.Common.Envelope) ProtoUtils.createSeekInfoEnvelope(org.hyperledger.fabric.sdk.transaction.ProtoUtils.createSeekInfoEnvelope) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StatusRuntimeException(io.grpc.StatusRuntimeException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) TimeoutException(java.util.concurrent.TimeoutException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException)

Example 93 with ByteString

use of org.apache.beam.vendor.grpc.v1p26p0.com.google.protobuf.ByteString in project fabric-sdk-java by hyperledger.

the class InstallProposalBuilder method createNetModeTransaction.

private void createNetModeTransaction() throws IOException {
    logger.debug("createNetModeTransaction");
    if (null == chaincodeSource && chaincodeInputStream == null) {
        throw new IllegalArgumentException("Missing chaincodeSource or chaincodeInputStream in InstallRequest");
    }
    if (null != chaincodeSource && chaincodeInputStream != null) {
        throw new IllegalArgumentException("Both chaincodeSource and chaincodeInputStream in InstallRequest were set. Specify one or the other");
    }
    final Type ccType;
    File projectSourceDir = null;
    String targetPathPrefix = null;
    String dplang;
    File metainf = null;
    if (null != chaincodeMetaInfLocation) {
        if (!chaincodeMetaInfLocation.exists()) {
            throw new IllegalArgumentException(format("Directory to find chaincode META-INF %s does not exist", chaincodeMetaInfLocation.getAbsolutePath()));
        }
        if (!chaincodeMetaInfLocation.isDirectory()) {
            throw new IllegalArgumentException(format("Directory to find chaincode META-INF %s is not a directory", chaincodeMetaInfLocation.getAbsolutePath()));
        }
        metainf = new File(chaincodeMetaInfLocation, "META-INF");
        logger.trace("META-INF directory is " + metainf.getAbsolutePath());
        if (!metainf.exists()) {
            throw new IllegalArgumentException(format("The META-INF directory does not exist in %s", chaincodeMetaInfLocation.getAbsolutePath()));
        }
        if (!metainf.isDirectory()) {
            throw new IllegalArgumentException(format("The META-INF in %s is not a directory.", chaincodeMetaInfLocation.getAbsolutePath()));
        }
        File[] files = metainf.listFiles();
        if (files == null) {
            throw new IllegalArgumentException("null for listFiles on: " + chaincodeMetaInfLocation.getAbsolutePath());
        }
        if (files.length < 1) {
            throw new IllegalArgumentException(format("The META-INF directory %s is empty.", metainf.getAbsolutePath()));
        }
        logger.trace(format("chaincode META-INF found %s", metainf.getAbsolutePath()));
    }
    switch(chaincodeLanguage) {
        case GO_LANG:
            // Verify that chaincodePath is being passed
            if (Utils.isNullOrEmpty(chaincodePath)) {
                throw new IllegalArgumentException("Missing chaincodePath in InstallRequest");
            }
            dplang = "Go";
            ccType = Type.GOLANG;
            if (null != chaincodeSource) {
                projectSourceDir = Paths.get(chaincodeSource.toString(), "src", chaincodePath).toFile();
                targetPathPrefix = Paths.get("src", chaincodePath).toString();
            }
            break;
        case JAVA:
            // Verify that chaincodePath is null
            if (!Utils.isNullOrEmpty(chaincodePath)) {
                throw new IllegalArgumentException("chaincodePath must be null for Java chaincode");
            }
            dplang = "Java";
            ccType = Type.JAVA;
            if (null != chaincodeSource) {
                targetPathPrefix = "src";
                projectSourceDir = Paths.get(chaincodeSource.toString()).toFile();
            }
            break;
        case NODE:
            // Verify that chaincodePath is null
            if (!Utils.isNullOrEmpty(chaincodePath)) {
                throw new IllegalArgumentException("chaincodePath must be null for Node chaincode");
            }
            dplang = "Node";
            ccType = Type.NODE;
            if (null != chaincodeSource) {
                projectSourceDir = Paths.get(chaincodeSource.toString()).toFile();
                // Paths.get("src", chaincodePath).toString();
                targetPathPrefix = "src";
            }
            break;
        default:
            throw new IllegalArgumentException("Unexpected chaincode language: " + chaincodeLanguage);
    }
    ccType(ccType);
    final byte[] data;
    String chaincodeID = chaincodeName + "::" + chaincodePath + "::" + chaincodeVersion;
    if (chaincodeSource != null) {
        if (!projectSourceDir.exists()) {
            final String message = "The project source directory does not exist: " + projectSourceDir.getAbsolutePath();
            logger.error(message);
            throw new IllegalArgumentException(message);
        }
        if (!projectSourceDir.isDirectory()) {
            final String message = "The project source directory is not a directory: " + projectSourceDir.getAbsolutePath();
            logger.error(message);
            throw new IllegalArgumentException(message);
        }
        logger.info(format("Installing '%s' language %s chaincode from directory: '%s' with source location: '%s'. chaincodePath:'%s'", chaincodeID, dplang, projectSourceDir.getAbsolutePath(), targetPathPrefix, chaincodePath));
        // generate chaincode source tar
        data = Utils.generateTarGz(projectSourceDir, targetPathPrefix, metainf);
        if (null != diagnosticFileDumper) {
            logger.trace(format("Installing '%s' language %s chaincode from directory: '%s' with source location: '%s'. chaincodePath:'%s' tar file dump %s", chaincodeID, dplang, projectSourceDir.getAbsolutePath(), targetPathPrefix, chaincodePath, diagnosticFileDumper.createDiagnosticTarFile(data)));
        }
    } else {
        logger.info(format("Installing '%s'  %s chaincode chaincodePath:'%s' from input stream", chaincodeID, dplang, chaincodePath));
        data = IOUtils.toByteArray(chaincodeInputStream);
        if (null != diagnosticFileDumper) {
            logger.trace(format("Installing '%s' language %s chaincode from input stream tar file dump %s", chaincodeID, dplang, diagnosticFileDumper.createDiagnosticTarFile(data)));
        }
    }
    final ChaincodeDeploymentSpec depspec = createDeploymentSpec(ccType, this.chaincodeName, this.chaincodePath, this.chaincodeVersion, null, data);
    // set args
    final List<ByteString> argList = new ArrayList<>();
    argList.add(ByteString.copyFrom(action, StandardCharsets.UTF_8));
    argList.add(depspec.toByteString());
    args(argList);
}
Also used : Type(org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeSpec.Type) ChaincodeDeploymentSpec(org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeDeploymentSpec) ByteString(com.google.protobuf.ByteString) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) File(java.io.File)

Example 94 with ByteString

use of org.apache.beam.vendor.grpc.v1p26p0.com.google.protobuf.ByteString in project fabric-sdk-java by hyperledger.

the class InstantiateProposalBuilder method createNetModeTransaction.

private void createNetModeTransaction() throws InvalidArgumentException {
    logger.debug("NetModeTransaction");
    if (chaincodeType == null) {
        throw new InvalidArgumentException("Chaincode type is required");
    }
    List<String> modlist = new LinkedList<>();
    modlist.add("init");
    modlist.addAll(argList);
    switch(chaincodeType) {
        case JAVA:
            ccType(Chaincode.ChaincodeSpec.Type.JAVA);
            break;
        case NODE:
            ccType(Chaincode.ChaincodeSpec.Type.NODE);
            break;
        case GO_LANG:
            ccType(Chaincode.ChaincodeSpec.Type.GOLANG);
            break;
        default:
            throw new InvalidArgumentException("Requested chaincode type is not supported: " + chaincodeType);
    }
    ChaincodeDeploymentSpec depspec = createDeploymentSpec(ccType, chaincodeName, chaincodePath, chaincodeVersion, modlist, null);
    List<ByteString> argList = new ArrayList<>();
    argList.add(ByteString.copyFrom(action, StandardCharsets.UTF_8));
    argList.add(ByteString.copyFrom(context.getChannelID(), StandardCharsets.UTF_8));
    argList.add(depspec.toByteString());
    if (chaincodePolicy != null) {
        argList.add(ByteString.copyFrom(chaincodePolicy));
    }
    args(argList);
}
Also used : ChaincodeDeploymentSpec(org.hyperledger.fabric.protos.peer.Chaincode.ChaincodeDeploymentSpec) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) ByteString(com.google.protobuf.ByteString) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) LinkedList(java.util.LinkedList)

Example 95 with ByteString

use of org.apache.beam.vendor.grpc.v1p26p0.com.google.protobuf.ByteString in project fabric-sdk-java by hyperledger.

the class ProposalResponse method verify.

/*
     * Verifies that a Proposal response is properly signed. The payload is the
     * concatenation of the response payload byte string and the endorsement The
     * certificate (public key) is gotten from the Endorsement.Endorser.IdBytes
     * field
     *
     * @param crypto the CryptoPrimitives instance to be used for signing and
     * verification
     *
     * @return true/false depending on result of signature verification
     */
public boolean verify(CryptoSuite crypto) {
    if (isVerified()) {
        // check if this proposalResponse was already verified   by client code
        return isVerified();
    }
    if (isInvalid()) {
        this.isVerified = false;
    }
    FabricProposalResponse.Endorsement endorsement = this.proposalResponse.getEndorsement();
    ByteString sig = endorsement.getSignature();
    try {
        Identities.SerializedIdentity endorser = Identities.SerializedIdentity.parseFrom(endorsement.getEndorser());
        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()));
                sb.append("\n");
                sb.append("endorser bytes in hex: " + DatatypeConverter.printHexBinary(endorsement.getEndorser().toByteArray()));
                sb.append("\n");
                sb.append("plainText bytes in hex: " + DatatypeConverter.printHexBinary(plainText.toByteArray()));
                logger.trace("payload TransactionBuilderbytes:  " + diagnosticFileDumper.createDiagnosticFile(sb.toString()));
            }
        }
        this.isVerified = crypto.verify(endorser.getIdBytes().toByteArray(), config.getSignatureAlgorithm(), sig.toByteArray(), plainText.toByteArray());
    } catch (InvalidProtocolBufferException | CryptoException e) {
        logger.error("verify: Cannot retrieve peer identity from ProposalResponse. Error is: " + e.getMessage(), e);
        this.isVerified = false;
    }
    return this.isVerified;
}
Also used : ByteString(com.google.protobuf.ByteString) FabricProposalResponse(org.hyperledger.fabric.protos.peer.FabricProposalResponse) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) Identities(org.hyperledger.fabric.protos.msp.Identities) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException)

Aggregations

ByteString (com.google.protobuf.ByteString)407 Test (org.junit.Test)143 ArrayList (java.util.ArrayList)65 ByteString (org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString)63 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)40 HashMap (java.util.HashMap)40 IOException (java.io.IOException)38 List (java.util.List)34 Map (java.util.Map)33 ServerRequest (com.pokegoapi.main.ServerRequest)17 ExecutionException (java.util.concurrent.ExecutionException)16 AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)15 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)15 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)15 Feature (com.google.cloud.vision.v1.Feature)15 Image (com.google.cloud.vision.v1.Image)15 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)15 ByteBuffer (java.nio.ByteBuffer)14 FileInputStream (java.io.FileInputStream)13 WebImage (com.google.cloud.vision.v1.WebDetection.WebImage)12