org.hyperledger.fabric.sdk.helper.Utils Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.helper.Utils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Find organizations for a peer.
 *
 * @param peerName name of peer
 * @return returns map of orgName to {@link OrgInfo} that the peer belongs to.
 * @throws InvalidArgumentException
 */
public Map<String, OrgInfo> getPeerOrgInfos(final String peerName) throws InvalidArgumentException {
    if (Utils.isNullOrEmpty(peerName)) {
        throw new InvalidArgumentException("peerName can not be null or empty.");
    }

    if (organizations == null || organizations.isEmpty()) {
        return new HashMap<>();
    }

    Map<String, OrgInfo> ret = new HashMap<>(16);
    organizations.forEach((name, orgInfo) -> {

        if (orgInfo.getPeerNames().contains(peerName)) {
            ret.put(name, orgInfo);
        }
    });

    return ret;
}
 
Example #2
Source File: Config.java    From fabric-jdbc-connector with Apache License 2.0 5 votes vote down vote up
private String grpcTLSify(String location) {
    location = location.trim();
    Exception e = Utils.checkGrpcUrl(location);
    if (e != null) {
        throw new RuntimeException(String.format("Bad  parameters for grpc url %s", location), e);
    }
    return runningFabricTLS ? location.replaceFirst("^grpc://", "grpcs://") : location;

}
 
Example #3
Source File: TestConfig.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private String grpcTLSify(String location) {
    location = location.trim();
    Exception e = Utils.checkGrpcUrl(location);
    if (e != null) {
        throw new RuntimeException(String.format("Bad TEST parameters for grpc url %s", location), e);
    }
    return runningFabricTLS ?
            location.replaceFirst("^grpc://", "grpcs://") : location;

}
 
Example #4
Source File: User.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
static void userContextCheck(User userContext) {
    if (userContext == null) {
        throw new NullPointerException("UserContext is null");
    }

    final String userName = userContext.getName();
    if (Utils.isNullOrEmpty(userName)) {
        throw new IllegalArgumentException("UserContext user's name missing.");
    }

    Enrollment enrollment = userContext.getEnrollment();
    if (enrollment == null) {
        throw new IllegalArgumentException(format("UserContext for user %s has no enrollment set.", userName));
    }
    if (enrollment instanceof X509Enrollment) {
        if (Utils.isNullOrEmpty(enrollment.getCert())) {
            throw new IllegalArgumentException(format("UserContext for user %s enrollment missing user certificate.", userName));
        }
        if (null == enrollment.getKey()) {
            throw new IllegalArgumentException(format("UserContext for user %s has Enrollment missing signing key", userName));
        }
    }

    if (Utils.isNullOrEmpty(userContext.getMspId())) {
        throw new IllegalArgumentException(format("UserContext for user %s  has user's MSPID missing.", userName));
    }
}
 
Example #5
Source File: LifecycleApproveChaincodeDefinitionForMyOrgRequest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * This is the chaincode validation plugin. Should default, not needing set. ONLY set if there is a specific validation is set for your organization
 *
 * @param chaincodeValidationPlugin
 * @throws InvalidArgumentException
 */
public void setChaincodeValidationPlugin(String chaincodeValidationPlugin) throws InvalidArgumentException {
    if (Utils.isNullOrEmpty(chaincodeValidationPlugin)) {
        throw new InvalidArgumentException("The getChaincodeValidationPlugin parameter can not be null or empty.");
    }
    this.chaincodeValidationPlugin = chaincodeValidationPlugin;
}
 
Example #6
Source File: LifecycleApproveChaincodeDefinitionForMyOrgRequest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * This is the chaincode endorsement plugin. Should default, not needing set. ONLY set if there is a specific endorsement is set for your organization
 *
 * @param chaincodeEndorsementPlugin
 * @throws InvalidArgumentException
 */
public void setChaincodeEndorsementPlugin(String chaincodeEndorsementPlugin) throws InvalidArgumentException {
    if (Utils.isNullOrEmpty(chaincodeEndorsementPlugin)) {
        throw new InvalidArgumentException("The getChaincodeEndorsementPlugin parameter can not be null or empty.");
    }
    this.chaincodeEndorsementPlugin = chaincodeEndorsementPlugin;
}
 
Example #7
Source File: LifecycleApproveChaincodeDefinitionForMyOrgRequest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * The packageId being approved. This is the package id gotten from {@link LifecycleInstallChaincodeProposalResponse#getPackageId()}
 * or from {@link LifecycleQueryInstalledChaincodesProposalResponse}, {@link LifecycleQueryInstalledChaincodeProposalResponse}
 * <p>
 * Only packageID or the sourceUnavailable to true may be set any time.
 *
 * @param packageId the package ID
 * @throws InvalidArgumentException
 */

public void setPackageId(String packageId) throws InvalidArgumentException {
    if (sourceUnavailable) {
        throw new InvalidArgumentException("The source none has be set to true already. Can not have packageId set when source none set to true.");
    }
    if (Utils.isNullOrEmpty(packageId)) {
        throw new InvalidArgumentException("The packageId parameter can not be null or empty.");
    }

    this.packageId = packageId;

}
 
Example #8
Source File: LifecycleApproveChaincodeDefinitionForMyOrgRequest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * The version of the chaincode to approve.
 *
 * @param chaincodeVersion the version.
 */

public void setChaincodeVersion(String chaincodeVersion) throws InvalidArgumentException {
    if (Utils.isNullOrEmpty(chaincodeVersion)) {
        throw new InvalidArgumentException("The chaincodeVersion parameter can not be null or empty.");
    }
    this.chaincodeVersion = chaincodeVersion;

}
 
Example #9
Source File: LifecycleApproveChaincodeDefinitionForMyOrgRequest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * The name of the chaincode to approve.
 *
 * @param chaincodeName
 */
public void setChaincodeName(String chaincodeName) throws InvalidArgumentException {
    if (Utils.isNullOrEmpty(chaincodeName)) {
        throw new InvalidArgumentException("The chaincodeName parameter can not be null or empty.");
    }
    this.chaincodeName = chaincodeName;
}
 
Example #10
Source File: QueryLifecycleQueryChaincodeDefinitionRequest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public void setChaincodeName(String chaincodeName) throws InvalidArgumentException {
    if (Utils.isNullOrEmpty(chaincodeName)) {
        throw new InvalidArgumentException("The chaincodeName parameter can not be null or empty.");
    }

    this.chaincodeName = chaincodeName;
}
 
Example #11
Source File: LifecycleQueryInstalledChaincodeRequest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * The packageId of the chaincode to query. Sent to peer to get a {@link LifecycleQueryInstalledChaincodeProposalResponse}
 *
 * @param packageId
 * @throws InvalidArgumentException
 */
public void setPackageID(String packageId) throws InvalidArgumentException {

    if (Utils.isNullOrEmpty(packageId)) {
        throw new InvalidArgumentException("The packageId parameter can not be null or empty.");
    }
    this.packageId = packageId;
}
 
Example #12
Source File: LifecycleCommitChaincodeDefinitionProposalBuilder.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #13
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private PublicKey getRevocationPublicKey(String str) throws EnrollmentException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (Utils.isNullOrEmpty(str)) {
        throw new EnrollmentException("fabric-ca-server did not return 'issuerPublicKey' in the response from " + HFCA_IDEMIXCRED);
    }
    String pem = new String(Base64.getDecoder().decode(str));
    byte[] der = convertPemToDer(pem);
    return KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(der));
}
 
Example #14
Source File: OrgManager.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
private String grpcTLSify(boolean openTLS, String location) {
    location = location.trim();
    Exception e = Utils.checkGrpcUrl(location);
    if (e != null) {
        throw new RuntimeException(String.format("Bad TEST parameters for grpc url %s", location), e);
    }
    return openTLS ? location.replaceFirst("^grpc://", "grpcs://") : location;

}
 
Example #15
Source File: Config.java    From balance-transfer-java with Apache License 2.0 5 votes vote down vote up
private String grpcTLSify(String location) {
	location = location.trim();
	Exception e = Utils.checkGrpcUrl(location);
	if (e != null) {
		throw new RuntimeException(String.format("Bad  parameters for grpc url %s", location), e);
	}
	return runningFabricTLS ? location.replaceFirst("^grpc://", "grpcs://") : location;

}
 
Example #16
Source File: TestConfig.java    From fabric_sdk_java_study with Apache License 2.0 5 votes vote down vote up
private String grpcTLSify(String location) {
    location = location.trim();
    Exception e = Utils.checkGrpcUrl(location);
    if (e != null) {
        throw new RuntimeException(String.format("Bad TEST parameters for grpc url %s", location), e);
    }
    return runningFabricTLS ?
            location.replaceFirst("^grpc://", "grpcs://") : location;

}
 
Example #17
Source File: HFCAIdentity.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
HFCAIdentity(String enrollmentID, HFCAClient client) throws InvalidArgumentException {
    if (Utils.isNullOrEmpty(enrollmentID)) {
        throw new InvalidArgumentException("EnrollmentID cannot be null or empty");
    }

    if (client.getCryptoSuite() == null) {
        throw new InvalidArgumentException("Client's crypto primitives not set");
    }

    this.enrollmentID = enrollmentID;
    this.client = client;
}
 
Example #18
Source File: HFCAAffiliation.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
static void checkFormat(String name) throws InvalidArgumentException {
    if (Utils.isNullOrEmpty(name)) {
        throw new InvalidArgumentException("Affiliation name cannot be null or empty");
    }
    if (name.contains(" ") || name.contains("\t")) {
        throw new InvalidArgumentException("Affiliation name cannot contain an empty space or tab");
    }
}
 
Example #19
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Register a user.
 *
 * @param request   Registration request with the following fields: name, role.
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @return the enrollment secret.
 * @throws RegistrationException    if registration fails.
 * @throws InvalidArgumentException
 */

public String register(RegistrationRequest request, User registrar) throws RegistrationException, InvalidArgumentException {

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    if (Utils.isNullOrEmpty(request.getEnrollmentID())) {
        throw new InvalidArgumentException("EntrollmentID cannot be null or empty");
    }

    if (registrar == null) {
        throw new InvalidArgumentException("Registrar should be a valid member");
    }
    logger.debug(format("register  url: %s, registrar: %s", url, registrar.getName()));

    setUpSSL();

    try {
        String body = request.toJson();
        JsonObject resp = httpPost(url + HFCA_REGISTER, body, registrar);
        String secret = resp.getString("secret");
        if (secret == null) {
            throw new Exception("secret was not found in response");
        }
        logger.debug(format("register  url: %s, registrar: %s done.", url, registrar));
        return secret;
    } catch (Exception e) {

        RegistrationException registrationException = new RegistrationException(format("Error while registering the user %s url: %s  %s ", registrar, url, e.getMessage()), e);
        logger.error(registrar);
        throw registrationException;

    }

}
 
Example #20
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private IdemixIssuerPublicKey getIssuerPublicKey(String str) throws EnrollmentException, InvalidProtocolBufferException {
    if (Utils.isNullOrEmpty(str)) {
        throw new EnrollmentException("fabric-ca-server did not return 'issuerPublicKey' in the response from " + HFCA_IDEMIXCRED);
    }
    byte[] ipkBytes = Base64.getDecoder().decode(str.getBytes());
    Idemix.IssuerPublicKey ipkProto = Idemix.IssuerPublicKey.parseFrom(ipkBytes);
    return new IdemixIssuerPublicKey(ipkProto);
}
 
Example #21
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
String getURL(String endpoint, Map<String, String> queryMap) throws URISyntaxException, MalformedURLException, InvalidArgumentException {
    setUpSSL();
    String url = addCAToURL(this.url + endpoint);
    URIBuilder uri = new URIBuilder(url);
    if (queryMap != null) {
        for (Map.Entry<String, String> param : queryMap.entrySet()) {
            if (!Utils.isNullOrEmpty(param.getValue())) {
                uri.addParameter(param.getKey(), param.getValue());
            }
        }
    }
    return uri.build().toURL().toString();
}
 
Example #22
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
String getHTTPAuthCertificate(Enrollment enrollment, String method, String url, String body) throws Exception {
    Base64.Encoder b64 = Base64.getEncoder();
    String cert = b64.encodeToString(enrollment.getCert().getBytes(UTF_8));
    body = b64.encodeToString(body.getBytes(UTF_8));
    String signString;
    // Cache the version, so don't need to make info call everytime the same client is used
    if (newPayloadType == null) {
        newPayloadType = true;

        // If CA version is less than 1.4.0, use old payload
        String caVersion = info().getVersion();
        logger.info(format("CA Version: %s", caVersion));

        if (Utils.isNullOrEmpty(caVersion)) {
            newPayloadType = false;
        }

        String version = caVersion + ".";
        if (version.startsWith("1.1.") || version.startsWith("1.2.") || version.startsWith("1.3.")) {
            newPayloadType = false;
        }
    }

    if (newPayloadType) {
        url = addCAToURL(url);
        String file = b64.encodeToString(new URL(url).getFile().getBytes(UTF_8));
        signString = method + "." + file + "." + body + "." + cert;
    } else {
        signString = body + "." + cert;
    }

    byte[] signature = cryptoSuite.sign(enrollment.getKey(), signString.getBytes(UTF_8));
    return cert + "." + b64.encodeToString(signature);
}
 
Example #23
Source File: LifecycleCommitChaincodeDefinitionProposalBuilder.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
public void chaincodeCodeValidationPlugin(String chaincodeValidationPlugin) {
    if (!Utils.isNullOrEmpty(chaincodeValidationPlugin)) {
        builder.setValidationPlugin(chaincodeValidationPlugin);
    }
}
 
Example #24
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private String revokeInternal(User revoker, String revokee, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException {

        if (cryptoSuite == null) {
            throw new InvalidArgumentException("Crypto primitives not set.");
        }

        logger.debug(format("revoke revoker: %s, revokee: %s, reason: %s", revoker, revokee, reason));

        if (Utils.isNullOrEmpty(revokee)) {
            throw new InvalidArgumentException("revokee user is not set");
        }
        if (revoker == null) {
            throw new InvalidArgumentException("revoker is not set");
        }

        try {
            setUpSSL();

            // build request body
            RevocationRequest req = new RevocationRequest(caName, revokee, null, null, reason, genCRL);
            String body = req.toJson();

            // send revoke request
            JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker);

            logger.debug(format("revoke revokee: %s done.", revokee));

            if (genCRL) {
                if (resp.isEmpty()) {
                    throw new RevocationException("Failed to return CRL, revoke response is empty");
                }
                if (resp.isNull("CRL")) {
                    throw new RevocationException("Failed to return CRL");
                }
                return resp.getString("CRL");
            }
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RevocationException("Error while revoking the user. " + e.getMessage(), e);
        }
    }
 
Example #25
Source File: LifecycleCommitChaincodeDefinitionProposalBuilder.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
public void chaincodeCodeEndorsementPlugin(String chaincodeEndorsementPlugin) {
    if (!Utils.isNullOrEmpty(chaincodeEndorsementPlugin)) {
        builder.setEndorsementPlugin(chaincodeEndorsementPlugin);
    }
}
 
Example #26
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
/**
 * HFCAClient constructor
 *
 * @param url        Http URL for the Fabric's certificate authority services endpoint
 * @param properties PEM used for SSL .. not implemented.
 *                   <p>
 *                   Supported properties
 *                   <ul>
 *                   <li>pemFile - File location for x509 pem certificate for SSL.</li>
 *                   <li>allowAllHostNames - boolen(true/false) override certificates CN Host matching -- for development only.</li>
 *                   </ul>
 * @throws MalformedURLException
 */
HFCAClient(String caName, String url, Properties properties) throws MalformedURLException {
    logger.debug(format("new HFCAClient %s", url));
    this.url = url;

    this.caName = caName; //name may be null

    URL purl = new URL(url);
    final String proto = purl.getProtocol();
    if (!"http".equals(proto) && !"https".equals(proto)) {
        throw new IllegalArgumentException("HFCAClient only supports http or https not " + proto);
    }
    final String host = purl.getHost();

    if (Utils.isNullOrEmpty(host)) {
        throw new IllegalArgumentException("HFCAClient url needs host");
    }

    final String path = purl.getPath();

    if (!Utils.isNullOrEmpty(path)) {

        throw new IllegalArgumentException("HFCAClient url does not support path portion in url remove path: '" + path + "'.");
    }

    final String query = purl.getQuery();

    if (!Utils.isNullOrEmpty(query)) {

        throw new IllegalArgumentException("HFCAClient url does not support query portion in url remove query: '" + query + "'.");
    }

    isSSL = "https".equals(proto);

    if (properties != null) {
        this.properties = (Properties) properties.clone(); //keep our own copy.
    } else {
        this.properties = null;
    }

}
 
Example #27
Source File: LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
public void chaincodeCodeValidationPlugin(String chaincodeValidationPlugin) {
    if (!Utils.isNullOrEmpty(chaincodeValidationPlugin)) {
        builder.setValidationPlugin(chaincodeValidationPlugin);
    }
}
 
Example #28
Source File: LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
public void chaincodeCodeEndorsementPlugin(String chaincodeEndorsementPlugin) {
    if (!Utils.isNullOrEmpty(chaincodeEndorsementPlugin)) {
        builder.setEndorsementPlugin(chaincodeEndorsementPlugin);
    }
}
 
Example #29
Source File: LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
protected LifecycleApproveChaincodeDefinitionForMyOrgProposalBuilder() {
    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);
    }

    builder.setSource(Lifecycle.ChaincodeSource.newBuilder()
            .setUnavailable(Lifecycle.ChaincodeSource.Unavailable.newBuilder().build()).build());

}
 
Example #30
Source File: TransactionContext.java    From fabric-sdk-java with Apache License 2.0 3 votes vote down vote up
public TransactionContext(Channel channel, User user, CryptoSuite cryptoPrimitives) {

        this.user = user;
        this.channel = channel;
        //TODO clean up when public classes are interfaces.
        this.verify = !"".equals(channel.getName());  //if name is not blank not system channel and need verify.

        //  this.txID = transactionID;
        this.cryptoPrimitives = cryptoPrimitives;

        // Get the signing identity from the user
        this.signingIdentity = IdentityFactory.getSigningIdentity(cryptoPrimitives, user);

        // Serialize signingIdentity
        this.identity = signingIdentity.createSerializedIdentity();

        ByteString no = getNonce();

        ByteString comp = no.concat(identity.toByteString());

        byte[] txh = cryptoPrimitives.hash(comp.toByteArray());

        //    txID = Hex.encodeHexString(txh);
        txID = new String(Utils.toHexString(txh));
        toString = "TransactionContext{ txID: " + txID + ", mspid: " + user.getMspId() + ", user: " + user.getName() + "}";

    }