org.hyperledger.fabric.sdk.User Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.User. 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: FabricManager.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
public void setUser(String leagueName, String orgName, String peerName, String username, String skPath, String certificatePath) throws InvalidArgumentException {
    if (StringUtils.equals(username, org.getUsername())) {
        return;
    }
    User user = org.getUser(username);
    if (null == user) {
        IntermediateUser intermediateUser = new IntermediateUser(leagueName, orgName, peerName, username, skPath, certificatePath);
        org.setUsername(username);
        org.addUser(leagueName, orgName, peerName, intermediateUser, org.getFabricStore());
    }
    org.getClient().setUserContext(org.getUser(username));
}
 
Example #2
Source File: TransactionContextTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignByteStrings() throws Exception {
    Assert.assertNull(context.signByteStrings((ByteString) null));
    Assert.assertNull(context.signByteStrings((ByteString[]) null));
    Assert.assertNull(context.signByteStrings(new ByteString[0]));

    User[] users = new User[0];
    Assert.assertNull(context.signByteStrings(users, (ByteString) null));
    Assert.assertNull(context.signByteStrings(users, (ByteString[]) null));
    Assert.assertNull(context.signByteStrings(users, new ByteString[0]));
}
 
Example #3
Source File: HFCAClientIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private static int createSuccessfulHCAIdentity(HFCAIdentity ident, User user) throws InvalidArgumentException, IdentityException {

        int rc = ident.create(user);
        assertTrue(rc < 400);
        assertNotNull(ident.getSecret());
        assertFalse(ident.getSecret().isEmpty());
        assertNotNull(ident.getEnrollmentId());
        assertFalse(ident.getEnrollmentId().isEmpty());
        assertNotNull(ident.getType());
        assertFalse(ident.getType().isEmpty());

        return rc;
    }
 
Example #4
Source File: X509SigningIdentity.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public X509SigningIdentity(CryptoSuite cryptoSuite, User user) {
    super(user);

    if (cryptoSuite == null) {
        throw new IllegalArgumentException("CryptoSuite is null");
    }

    this.cryptoSuite = cryptoSuite;
}
 
Example #5
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 #6
Source File: X509Identity.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public X509Identity(User user) {
    if (user == null) {
        throw new IllegalArgumentException("User is null");
    }
    if (user.getEnrollment() == null) {
        throw new IllegalArgumentException("user.getEnrollment() is null");
    }
    if (user.getEnrollment().getCert() == null) {
        throw new IllegalArgumentException("user.getEnrollment().getCert() is null");
    }

    this.user = user;
}
 
Example #7
Source File: IdentityFactory.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public static SigningIdentity getSigningIdentity(CryptoSuite cryptoSuite, User user) {
    Enrollment enrollment = user.getEnrollment();

    try {
        if (enrollment instanceof IdemixEnrollment) { // Need Idemix signer for this.
            return new IdemixSigningIdentity((IdemixEnrollment) enrollment);
        } else { // for now all others are x509
            return new X509SigningIdentity(cryptoSuite, user);
        }

    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example #8
Source File: ProtoUtils.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
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));
                }
            }
        }

        if (isDebugLevel) {
            logger.debug(format("SignatureHeader: nonce: %s, User:%s, MSPID: %s, idBytes: %s",
                    toHexString(transactionContext.getNonce()),
                    user.getName(),
                    identity.getMspid(),
                    toHexString(cert)
            ));
        }
    }

    return Common.SignatureHeader.newBuilder()
            .setCreator(identity.toByteString())
            .setNonce(transactionContext.getNonce())
            .build().toByteString();
}
 
Example #9
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
/**
 * Generate certificate revocation list.
 *
 * @param registrar     admin user configured in CA-server
 * @param revokedBefore Restrict certificates returned to revoked before this date if not null.
 * @param revokedAfter  Restrict certificates returned to revoked after this date if not null.
 * @param expireBefore  Restrict certificates returned to expired before this date if not null.
 * @param expireAfter   Restrict certificates returned to expired after this date if not null.
 * @throws InvalidArgumentException
 */

public String generateCRL(User registrar, Date revokedBefore, Date revokedAfter, Date expireBefore, Date expireAfter)
        throws InvalidArgumentException, GenerateCRLException {

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

    if (registrar == null) {
        throw new InvalidArgumentException("registrar is not set");
    }

    try {
        setUpSSL();

        //---------------------------------------
        JsonObjectBuilder factory = Json.createObjectBuilder();
        if (revokedBefore != null) {
            factory.add("revokedBefore", Util.dateToString(revokedBefore));
        }
        if (revokedAfter != null) {
            factory.add("revokedAfter", Util.dateToString(revokedAfter));
        }
        if (expireBefore != null) {
            factory.add("expireBefore", Util.dateToString(expireBefore));
        }
        if (expireAfter != null) {
            factory.add("expireAfter", Util.dateToString(expireAfter));
        }
        if (caName != null) {
            factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
        }

        JsonObject jsonObject = factory.build();

        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
        jsonWriter.writeObject(jsonObject);
        jsonWriter.close();
        String body = stringWriter.toString();

        //---------------------------------------

        // send revoke request
        JsonObject ret = httpPost(url + HFCA_GENCRL, body, registrar);

        return ret.getString("CRL");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new GenerateCRLException(e.getMessage(), e);
    }
}
 
Example #10
Source File: TransactionContextTest.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private TransactionContext createTestContext() {
    Channel channel = createTestChannel("channel1");
    User user = hfclient.getUserContext();
    CryptoSuite cryptoSuite = hfclient.getCryptoSuite();
    return new TransactionContext(channel, user, cryptoSuite);
}
 
Example #11
Source File: SampleOrg.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
public User getUser(String name) {
    return userMap.get(name);
}
 
Example #12
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
CompletableFuture<TransactionEvent> executeChaincode(HFClient client, User userContext, Channel channel, String fcn, Boolean doInit, String chaincodeName, Type chaincodeType, String... args) throws InvalidArgumentException, ProposalException {

        final ExecutionException[] executionExceptions = new ExecutionException[1];

        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();

        TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
        transactionProposalRequest.setChaincodeName(chaincodeName);
        transactionProposalRequest.setChaincodeLanguage(chaincodeType);
        transactionProposalRequest.setUserContext(userContext);

        transactionProposalRequest.setFcn(fcn);
        transactionProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
        transactionProposalRequest.setArgs(args);
        if (null != doInit) {
            transactionProposalRequest.setInit(doInit);
        }

        //  Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposalToEndorsers(transactionProposalRequest);
        Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers());
        for (ProposalResponse response : transactionPropResp) {
            if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                out("Successful transaction proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
                successful.add(response);
            } else {
                failed.add(response);
            }
        }

        out("Received %d transaction proposal responses. Successful+verified: %d . Failed: %d",
                transactionPropResp.size(), successful.size(), failed.size());
        if (failed.size() > 0) {
            ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
            fail("Not enough endorsers for executeChaincode(move a,b,100):" + failed.size() + " endorser error: " +
                    firstTransactionProposalResponse.getMessage() +
                    ". Was verified: " + firstTransactionProposalResponse.isVerified());
        }
        out("Successfully received transaction proposal responses.");

        //  System.exit(10);

        ////////////////////////////
        // Send Transaction Transaction to orderer
        out("Sending chaincode transaction(move a,b,100) to orderer.");
        return channel.sendTransaction(successful);

    }
 
Example #13
Source File: PrivateDataIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
CompletableFuture<BlockEvent.TransactionEvent> setAmount(HFClient client, Channel channel, ChaincodeID chaincodeID, int delta, User user) {

        try {
            Collection<ProposalResponse> successful = new LinkedList<>();
            Collection<ProposalResponse> failed = new LinkedList<>();

            ///////////////
            /// Send transaction proposal to all peers
            TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
            transactionProposalRequest.setChaincodeID(chaincodeID);
            transactionProposalRequest.setFcn("set");

            Map<String, byte[]> transientMap = new HashMap<>();
            transientMap.put("A", "a".getBytes(UTF_8));   // test using bytes as args. End2end uses Strings.
            transientMap.put("AVal", "500".getBytes(UTF_8));
            transientMap.put("B", "b".getBytes(UTF_8));
            String arg3 = "" + (200 + delta);
            transientMap.put("BVal", arg3.getBytes(UTF_8));
            transactionProposalRequest.setTransientMap(transientMap);

            transactionProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
            if (user != null) { // specific user use that
                transactionProposalRequest.setUserContext(user);
            }

            Collection<ProposalResponse> invokePropResp = channel.sendTransactionProposal(transactionProposalRequest);
            for (ProposalResponse response : invokePropResp) {
                if (response.getStatus() == Status.SUCCESS) {
                    out("Successful transaction proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
                    successful.add(response);
                } else {
                    failed.add(response);
                }
            }

            out("Received %d transaction proposal responses for setAmount. Successful+verified: %d . Failed: %d",
                    invokePropResp.size(), successful.size(), failed.size());
            if (failed.size() > 0) {
                ProposalResponse firstTransactionProposalResponse = failed.iterator().next();

                throw new ProposalException(format("Not enough endorsers for set(move a,b,%s):%d endorser error:%s. Was verified:%b",
                        0, firstTransactionProposalResponse.getStatus().getStatus(), firstTransactionProposalResponse.getMessage(), firstTransactionProposalResponse.isVerified()));

            }
            out("Successfully received transaction proposal responses for setAmount. Now sending to orderer.");

            ////////////////////////////
            // Send transaction to orderer

            if (user != null) {
                return channel.sendTransaction(successful, user);
            }
            return channel.sendTransaction(successful);
        } catch (Exception e) {

            throw new CompletionException(e);

        }

    }
 
Example #14
Source File: ProtoUtils.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
public static Identities.SerializedIdentity createSerializedIdentity(User user) {
    return Identities.SerializedIdentity.newBuilder()
            .setIdBytes(ByteString.copyFromUtf8(user.getEnrollment().getCert()))
            .setMspid(user.getMspId()).build();
}
 
Example #15
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
JsonObject httpGet(String url, User registrar) throws Exception {
    return httpGet(url, registrar, null);
}
 
Example #16
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
JsonObject httpPost(String url, String body, User registrar) throws Exception {
    String authHTTPCert = getHTTPAuthCertificate(registrar.getEnrollment(), "POST", url, body);
    return post(url, body, authHTTPCert);
}
 
Example #17
Source File: IntermediateOrg.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
User getUser(String username) {
    return userMap.get(username);
}
 
Example #18
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 #19
Source File: Org.java    From balance-transfer-java with Apache License 2.0 4 votes vote down vote up
public User getUser(String name) {
    return userMap.get(name);
}
 
Example #20
Source File: SampleOrg.java    From fabric_sdk_java_study with Apache License 2.0 4 votes vote down vote up
public User getUser(String name) {
    return userMap.get(name);
}
 
Example #21
Source File: FabricClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor
 * 
 * @param context
 * @throws CryptoException
 * @throws InvalidArgumentException
 * @throws InvocationTargetException 
 * @throws NoSuchMethodException 
 * @throws ClassNotFoundException 
 * @throws InstantiationException 
 * @throws IllegalAccessException 
 */
public FabricClient(User context) throws CryptoException, InvalidArgumentException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
	CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
	// setup the client
	instance = HFClient.createNewInstance();
	instance.setCryptoSuite(cryptoSuite);
	instance.setUserContext(context);
}
 
Example #22
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() + "}";

    }
 
Example #23
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 3 votes vote down vote up
private static HFClient getTheClient() throws Exception {

        HFClient client = HFClient.createNewInstance();
        client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

        User peerAdmin = getAdminUser(TEST_ORG);
        client.setUserContext(peerAdmin);

        return client;
    }
 
Example #24
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * Re-Enroll the user with member service
 *
 * @param user User to be re-enrolled
 * @return enrollment
 * @throws EnrollmentException
 * @throws InvalidArgumentException
 */
public Enrollment reenroll(User user) throws EnrollmentException, InvalidArgumentException {
    return reenroll(user, new EnrollmentRequest());
}
 
Example #25
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
private static User getAdminUser(String orgName) throws Exception {

        return networkConfig.getPeerAdmin(orgName);
    }
 
Example #26
Source File: HFCAAffiliation.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * create an affiliation
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @return Response of request
 * @throws AffiliationException    if adding an affiliation fails.
 * @throws InvalidArgumentException
 */

public HFCAAffiliationResp create(User registrar) throws AffiliationException, InvalidArgumentException {
    return create(registrar, false);
}
 
Example #27
Source File: HFCAAffiliation.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * update an affiliation
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @return Response of request
 * @throws AffiliationException If updating an affiliation fails
 * @throws InvalidArgumentException
 */

public HFCAAffiliationResp update(User registrar) throws AffiliationException, InvalidArgumentException {
    return update(registrar, false);
}
 
Example #28
Source File: HFCAAffiliation.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * delete an affiliation
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @return Response of request
 * @throws AffiliationException    if deleting an affiliation fails.
 * @throws InvalidArgumentException
 */

public HFCAAffiliationResp delete(User registrar) throws AffiliationException, InvalidArgumentException {
    return delete(registrar, false);
}
 
Example #29
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * revoke one certificate
 *
 * @param revoker admin user who has revoker attribute configured in CA-server
 * @param serial  serial number of the certificate to be revoked
 * @param aki     aki of the certificate to be revoke
 * @param reason  revoke reason, see RFC 5280
 * @throws RevocationException
 * @throws InvalidArgumentException
 */

public void revoke(User revoker, String serial, String aki, String reason) throws RevocationException, InvalidArgumentException {
    revokeInternal(revoker, serial, aki, reason, false);
}
 
Example #30
Source File: HFCAClient.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * revoke one enrollment of user
 *
 * @param revoker    admin user who has revoker attribute configured in CA-server
 * @param enrollment the user enrollment to be revoked
 * @param reason     revoke reason, see RFC 5280
 * @throws RevocationException
 * @throws InvalidArgumentException
 */

public void revoke(User revoker, Enrollment enrollment, String reason) throws RevocationException, InvalidArgumentException {
    revokeInternal(revoker, enrollment, reason, false);
}