Esempio n. 1
0
    def chaincode_instantiate(self, requestor, channel_name, peer_names, args,
                              cc_name, cc_version, timeout=10):
        """
            Instantiate installed chaincode to particular peer in
            particular channel

        :param requestor: User role who issue the request
        :param channel_name: the name of the channel to send tx proposal
        :param peer_names: Names of the peers to install
        :param args (list): arguments (keys and values) for initialization
        :param cc_name: chaincode name
        :param cc_version: chaincode version
        :param timeout: Timeout to wait
        :return: True or False
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        tran_prop_req_dep = create_tx_prop_req(
            prop_type=CC_INSTANTIATE,
            cc_type=CC_TYPE_GOLANG,
            cc_name=cc_name,
            cc_version=cc_version,
            fcn='init',
            args=args
        )

        tx_context_dep = create_tx_context(
            requestor,
            ecies(),
            tran_prop_req_dep
        )

        res = self.send_instantiate_proposal(
            tx_context_dep, peers, channel_name)

        sleep(5)

        tx_context = create_tx_context(requestor,
                                       ecies(),
                                       TXProposalRequest())
        tran_req = utils.build_tx_req(res)
        response = utils.send_transaction(self.orderers, tran_req, tx_context)

        sleep(5)

        self.txid_for_test = tx_context_dep.tx_id  # used only for query test

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        res, _ = queue.get(timeout=timeout)
        _logger.debug(res)
        return res.status == 200
Esempio n. 2
0
def build_channel_request(client, channel_tx, channel_name):
    """
    Args:
        client: the client instance
        channel_tx: channel config file
        channel_name: channel name
    return channel request to create a channel
    """

    signatures = []
    prop_req = TXProposalRequest()
    with open(channel_tx, 'rb') as f:
        envelope = f.read()
        config = utils.extract_channel_config(envelope)

    orderer_config = TRUSTAS_NETWORK['orderer']

    if "LOCAL_DEPLOY" in os.environ:
        LOCAL_DEPLOY = os.environ["LOCAL_DEPLOY"] == "True"
    env = "local_" if LOCAL_DEPLOY else "gcp_"

    orderer = Orderer(
        endpoint=orderer_config[env + 'grpc_endpoint'],
        tls_ca_cert_file=orderer_config['tls_cacerts'],
        opts=(('grpc.ssl_target_name_override', 'orderer.example.com'), ),
    )

    orderer_admin = get_orderer_org_user(state_store=client.state_store)
    orderer_tx_context = TXContext(orderer_admin, ecies(), prop_req, {})
    client.tx_context = orderer_tx_context
    orderer_admin_signature = client.sign_channel_config(config)
    signatures.append(orderer_admin_signature)
    tx_id = orderer_tx_context.tx_id
    nonce = orderer_tx_context.nonce

    org1_admin = get_peer_org_user('org1.example.com', "Admin",
                                   client.state_store)
    org1_tx_context = TXContext(org1_admin, ecies(), prop_req, {})
    client.tx_context = org1_tx_context
    org1_admin_signature = client.sign_channel_config(config)
    signatures.append(org1_admin_signature)

    # org2_admin = get_peer_org_user('org2.example.com', "Admin",
    #                                client.state_store)
    # org2_tx_context = TXContext(org2_admin, ecies(), prop_req, {})
    # client.tx_context = org2_tx_context
    # org2_admin_signature = client.sign_channel_config(config)
    # signatures.append(org2_admin_signature)

    request = {
        'config': config,
        'signatures': signatures,
        'channel_name': channel_name,
        'orderer': orderer,
        'tx_id': tx_id,
        'nonce': nonce
    }

    return request
Esempio n. 3
0
    def channel_join(self, requestor, channel_name, peer_names, orderer_name):
        """
        Join a channel.
        Get genesis block from orderer, then send request to peer

        :param requestor: User to send the request
        :param channel_name: Name of channel to create
        :param peer_names: List of peers to join to the channel
        :param orderer_name: Name of orderer to get genesis block from

        :return: True (creation succeeds) or False (creation failed)
        """
        channel = self.get_channel(channel_name)
        if not channel:
            _logger.warning(
                "channel {} not existed when join".format(channel_name))
            return False

        orderer = self.get_orderer(orderer_name)
        if not orderer:
            _logger.warning("orderer {} not existed when channel join".format(
                orderer_name))
            return False

        tx_prop_req = TXProposalRequest()

        # get the genesis block
        orderer_admin = self.get_user('orderer.example.com', 'Admin')
        tx_context = TXContext(orderer_admin, ecies(), tx_prop_req)
        genesis_block = orderer.get_genesis_block(
            tx_context, channel.name).SerializeToString()

        # create the peer
        tx_context = TXContext(requestor, ecies(), tx_prop_req)

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)
        """
        # connect the peer
        eh = EventHub()
        event = peer_config['grpc_event_endpoint']

        tx_id = client.tx_context.tx_id
        eh.set_peer_addr(event)
        eh.connect()
        eh.register_block_event(block_event_callback)
        all_ehs.append(eh)
        """

        request = {
            "targets": peers,
            "block": genesis_block,
            "tx_context": tx_context,
            "transient_map": {}
        }

        return channel.join_channel(request)
Esempio n. 4
0
def build_channel_request(client, channel_tx, channel_name):
    """
    Args:
        client: the client instance
        channel_tx: channel config file
        channel_name: channel name
    return channel request to create a channel
    """

    signatures = []
    prop_req = TXProposalRequest()
    with open(channel_tx, 'rb') as f:
        envelope = f.read()
        config = utils.extract_channel_config(envelope)

    orderer_config = E2E_CONFIG['test-network']['orderer']
    with open(orderer_config['tls_cacerts'], 'rb') as tls_cacerts:
        pem = tls_cacerts.read()

    opts = (('grpc.ssl_target_name_override', 'orderer.example.com'),)
    orderer = Orderer(
        endpoint=orderer_config['grpc_endpoint'],
        pem=pem,
        opts=opts
    )
    orderer_admin = get_orderer_org_admin(client)
    orderer_tx_context = TXContext(orderer_admin, ecies(), prop_req, {})
    client.tx_context = orderer_tx_context
    orderer_admin_signature = client.sign_channel_config(config)
    orderer_admin_signature_bytes = orderer_admin_signature.SerializeToString()
    signatures.append(orderer_admin_signature_bytes)
    tx_id = orderer_tx_context.tx_id
    nonce = orderer_tx_context.nonce

    org1_admin = get_peer_org_user(client, 'org1.example.com')
    org1_tx_context = TXContext(org1_admin, ecies(), prop_req, {})
    client.tx_context = org1_tx_context
    org1_admin_signature = client.sign_channel_config(config)
    org1_admin_signature_bytes = org1_admin_signature.SerializeToString()

    signatures.append(org1_admin_signature_bytes)

    org2_admin = get_peer_org_user(client, 'org2.example.com')
    org2_tx_context = TXContext(org2_admin, ecies(), prop_req, {})
    client.tx_context = org2_tx_context
    org2_admin_signature = client.sign_channel_config(config)
    org2_admin_signature_bytes = org2_admin_signature.SerializeToString()
    signatures.append(org2_admin_signature_bytes)

    request = {'config': config,
               'signatures': signatures,
               'channel_name': channel_name,
               'orderer': orderer,
               'tx_id': tx_id,
               'nonce': nonce}

    return request
Esempio n. 5
0
    def chaincode_invoke(self, requestor, channel_name, peer_names, args,
                         cc_name, cc_version, cc_type=CC_TYPE_JAVA, timeout=10):
        """
        Invoke chaincode for ledger update

        :param requestor: User role who issue the request
        :param channel_name: the name of the channel to send tx proposal
        :param peer_names: Names of the peers to install
        :param args (list): arguments (keys and values) for initialization
        :param cc_name: chaincode name
        :param cc_version: chaincode version
        :param cc_type: chaincode language
        :param timeout: Timeout to wait
        :return: True or False
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        tran_prop_req = create_tx_prop_req(
            prop_type=CC_INVOKE,
            cc_type=cc_type,
            cc_name=cc_name,
            cc_version=cc_version,
            fcn='invoke',
            args=args
        )

        tx_context = create_tx_context(
            requestor,
            ecies(),
            tran_prop_req
        )

        res = self.get_channel(
            channel_name).send_tx_proposal(tx_context, peers)

        tran_req = utils.build_tx_req(res)
        tx_context_tx = create_tx_context(
            requestor,
            ecies(),
            tran_req
        )

        utils.send_transaction(self.orderers, tran_req, tx_context_tx)

        queue = Queue(1)
        res.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        res = queue.get(timeout=timeout)
        _logger.debug(res)
        return res[0][0][0].response
Esempio n. 6
0
def build_join_channel_req(org, channel, client):
    """
    For test, there is only one peer.

    Args:
        org: org
        channel: the channel to join
        client: client instance
    Return:
        return request for joining channel
        """

    tx_prop_req = TXProposalRequest()

    # add the orderer
    orderer = client.get_orderer('orderer.example.com')
    channel.add_orderer(orderer)  # TODO: where should we add orderer?

    # get the genesis block
    orderer_admin = client.get_user('orderer.example.com', 'Admin')
    tx_context = TXContext(orderer_admin, ecies(), tx_prop_req)
    genesis_block = orderer.get_genesis_block(
        tx_context,
        channel.name).SerializeToString()

    org_admin = client.get_user(org, 'Admin')
    tx_context = TXContext(org_admin, ecies(), tx_prop_req)

    peer = client.get_peer('peer0.'+org)

    """
    # connect the peer
    eh = EventHub()
    event = peer_config['grpc_event_endpoint']

    tx_id = client.tx_context.tx_id
    eh.set_peer_addr(event)
    eh.connect()
    eh.register_block_event(block_event_callback)
    all_ehs.append(eh)
    """

    request = {
        "targets": [peer],
        "block": genesis_block,
        "tx_context": tx_context,
        "transient_map": {},
    }

    return request
Esempio n. 7
0
    def create_user(self, enrollment_id, org, msp_id, state_store=None):
        """Returns an instance of a user whose identity
            is stored in the CouchDBWallet

        :param enrollment_id: enrollment id
        :param org: organization
        :param msp_id: MSP id
        :param state_store:  (Default value = None)
        :return: a validated user instance
        """
        crypto_suit = ecies()

        if not self.exists(enrollment_id):
            raise AttributeError('"user" does not exist')

        key_pem = self.db[enrollment_id]['PrivateKey']
        cert_pem = self.db[enrollment_id]['EnrollmentCert']

        private_key = load_pem_private_key(key_pem, None, default_backend())
        enrollment = Enrollment(private_key, cert_pem)

        user = User(enrollment_id, org, state_store)
        user.enrollment = enrollment
        user.msp_id = msp_id
        user.cryptoSuite = crypto_suit

        return validate(user)
Esempio n. 8
0
def create_user(name, org, state_store, msp_id, key_pem, cert_pem,
                crypto_suite=ecies()):
    """Create user

    :param name: user's name
    :param org: org name
    :param state_store: user state store
    :param msp_id: msp id for the user
    :param crypto_suite: the cryptoSuite used to store crypto and key store
         settings (Default value = ecies())
    :param key_pem: identity private key pem encoded
    :param cert_pem: identity public cert pem encoded
    :return: a user instance
    """

    _logger.debug("Create user with {}:{}:{}:{}:{}".format(
        name, org, state_store, msp_id, cert_pem
    ))

    private_key = load_pem_private_key(key_pem, None, default_backend())
    enrollment = Enrollment(private_key, cert_pem)

    user = User(name, org, state_store)
    user.enrollment = enrollment
    user.msp_id = msp_id
    user.cryptoSuite = crypto_suite

    return validate(user)
Esempio n. 9
0
    def query_info(self, requestor, channel_name, peer_names, decode=True):
        """
        Queries information of a channel

        :param requestor: User role who issue the request
        :param channel_name: Name of channel to query
        :param peer_names: Names of the peers to install
        :param deocode: Decode the response payload
        :return: A `BlockchainInfo` or `ProposalResponse`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        channel = self.get_channel(channel_name)
        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())

        responses = channel.query_info(tx_context, peers)

        try:
            if responses[0][0].response and decode:
                chain_info = ledger_pb2.BlockchainInfo()
                chain_info.ParseFromString(responses[0][0].response.payload)
                _logger.debug('response status {}'.format(
                    responses[0][0].response.status))
                return chain_info
            return responses[0][0]

        except Exception:
            _logger.error("Failed to query info: {}", sys.exc_info()[0])
            raise
    def test_install_chaincode_success(self):
        self.client.state_store = file_key_value_store(self.kv_store_path)

        with open(self.peer0Org1_tls_certs) as f:
            pem = f.read()

        opts = (
            ('grpc.ssl_target_name_override', self.peer0Org1_tls_hostname),)
        peer0_org1 = create_peer(endpoint=self.peer0Org1_req_endpoint,
                                 pem=pem, opts=opts)
        org1_admin = get_peer_org_admin(self.client, 'org1.example.com')

        crypto = ecies()
        tran_prop_req = create_tx_prop_req(CC_INSTALL, CC_PATH, CC_TYPE_GOLANG,
                                           CC_NAME, CC_VERSION)
        tx_context = create_tx_context(org1_admin, crypto, tran_prop_req)

        queue = Queue(1)

        sleep(5)
        response = self.client.send_install_proposal(tx_context, [peer0_org1])

        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        res = queue.get(timeout=5)
        proposal_response, _ = res[0][0]
        self.assertEqual(proposal_response.response.status, 200)
Esempio n. 11
0
    def chaincode_install(self, requestor, peer_names, cc_path, cc_name,
                          cc_version, timeout=5):
        """
        Install chaincode to given peers by requestor role

        :param requestor: User role who issue the request
        :param peer_names: Names of the peers to install
        :param cc_path: chaincode path
        :param cc_name: chaincode name
        :param cc_version: chaincode version
        :param timeout: Timeout to wait
        :return: True or False
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        tran_prop_req = create_tx_prop_req(CC_INSTALL, cc_path, CC_TYPE_GOLANG,
                                           cc_name, cc_version)
        tx_context = create_tx_context(requestor, ecies(), tran_prop_req)

        # sleep(5)
        response = self.send_install_proposal(tx_context, peers)

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        res = queue.get(timeout=timeout)
        proposal_response, _ = res[0][0]
        return proposal_response.response.status == 200
Esempio n. 12
0
    def test_instantiate_chaincode(self):

        channel = self.client.new_channel(self.channel_name)
        org1 = 'org1.example.com'
        peer_config = test_network['org1.example.com']['peers']['peer0']
        tls_cacerts = peer_config['tls_cacerts']
        opts = (('grpc.ssl_target_name_override',
                 peer_config['server_hostname']), )
        endpoint = peer_config['grpc_request_endpoint']

        peer = create_peer(endpoint=endpoint,
                           tls_cacerts=tls_cacerts,
                           opts=opts)

        org1_admin = get_peer_org_user(org1, 'Admin', self.client.state_store)
        crypto = ecies()

        # for chain code install
        tran_prop_req_in = create_tx_prop_req(prop_type=CC_INSTALL,
                                              cc_path=CC_PATH,
                                              cc_type=CC_TYPE_GOLANG,
                                              cc_name=CC_NAME,
                                              cc_version=CC_VERSION)

        # install chain code
        tx_context_in = create_tx_context(org1_admin, crypto, tran_prop_req_in)

        # for chain code deploy
        args = ['a', '100', 'b', '40']
        tran_prop_req_dep = create_tx_prop_req(prop_type=CC_INSTANTIATE,
                                               cc_type=CC_TYPE_GOLANG,
                                               cc_name=CC_NAME,
                                               cc_version=CC_VERSION,
                                               args=args,
                                               fcn='init')

        # deploy the chain code
        tx_context_dep = create_tx_context(org1_admin, crypto,
                                           tran_prop_req_dep)

        # create a channel
        request = build_channel_request(self.client, self.channel_tx,
                                        self.channel_name)

        self.client._create_channel(request)

        # join channel
        join_req = build_join_channel_req(org1, channel, self.client)
        channel.join_channel(join_req)

        self.client.send_install_proposal(tx_context_in, [peer])

        # send the transaction to the channel
        res = channel.send_instantiate_proposal(tx_context_dep, [peer])
        tran_req = build_tx_req(res)

        tx_context = create_tx_context(org1_admin, crypto, TXProposalRequest())
        response = send_transaction(channel.orderers, tran_req, tx_context)

        self.assertEqual(response[0].status, 200)
Esempio n. 13
0
    def test_install_chaincode_success(self):
        """
        Test a chaincode installation success.
        :return:
        """

        opts = (('grpc.ssl_target_name_override',
                 self.peer0_org1_tls_hostname), )
        peer0_org1 = create_peer(endpoint=self.peer0_org1_endpoint,
                                 tls_cacerts=self.peer0_org1_tls_certs,
                                 opts=opts)
        org1_admin = get_peer_org_user('org1.example.com', "Admin",
                                       self.client.state_store)

        crypto = ecies()
        tran_prop_req = create_tx_prop_req(CC_INSTALL, CC_PATH, CC_TYPE_GOLANG,
                                           CC_NAME, CC_VERSION)
        tx_context = create_tx_context(org1_admin, crypto, tran_prop_req)

        queue = Queue(1)

        sleep(5)
        response = self.client.send_install_proposal(tx_context, [peer0_org1])

        response.subscribe(on_next=lambda x: queue.put(x),
                           on_error=lambda x: queue.put(x))

        res = queue.get(timeout=5)
        proposal_response, _ = res[0][0]
        self.assertEqual(proposal_response.response.status, 200)
Esempio n. 14
0
    def cc_invoke(self, args, cc_name, fcn, cc_version, queryonly=False):
        loop = asyncio.get_event_loop()
        crypto = ecies()

        endorses = self._get_endorsers(queryonly)

        tran_prop_req = create_tx_prop_req(
            prop_type=CC_INVOKE,
            cc_type=CC_TYPE_GOLANG, cc_name=cc_name, fcn=fcn,
            cc_version=cc_version, args=args)

        tx_context = create_tx_context(self.user, crypto, tran_prop_req)

        responses, proposal, header = self.channel.send_tx_proposal(
            tx_context, endorses.values())

        res = loop.run_until_complete(asyncio.gather(*responses))

        if queryonly:
            return res

        tran_req = build_tx_req((res, proposal, header))

        tx_context_tx = create_tx_context(self.user,
                                          crypto,
                                          TXProposalRequest())

        responses = loop.run_until_complete(base.get_stream_result(
            send_transaction(self.client.orderers, tran_req, tx_context_tx)))

        logger.info('Tx response: {0}'.format(responses))

        return responses
Esempio n. 15
0
    def test_query_installed_chaincodes_sucess(self):

        self.invoke_chaincode()

        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())
        response = self.channel.query_info(tx_context, [self.org1_peer])
        self.assertEqual(response[0][0].response.status, 200)
Esempio n. 16
0
    def test_ecies_secp384r1_sha3(self):
        """Test case for security level 384, hash SHA3."""
        ecies384 = ecies(CURVE_P_384_Size, SHA3)
        private_key = ecies384.generate_private_key()
        cipher_text = ecies384.encrypt(private_key.public_key(),
                                       self.plain_text)

        self.assertEqual(ecies384.decrypt(private_key, cipher_text),
                         self.plain_text)
Esempio n. 17
0
    def test_ecies_secp256r1_sha2(self):
        """Test case for security level 256, hash SHA2."""
        ecies256 = ecies(CURVE_P_256_Size, SHA2)
        private_key = ecies256.generate_private_key()
        cipher_text = ecies256.encrypt(private_key.public_key(),
                                       self.plain_text)

        self.assertEqual(ecies256.decrypt(private_key, cipher_text),
                         self.plain_text)
Esempio n. 18
0
    def test_instantiate_chaincode(self):

        peer_config = test_network['org1.example.com']['peers']['peer0']
        tls_cacerts = peer_config['tls_cacerts']
        endpoint = peer_config['grpc_request_endpoint']

        opts = (('grpc.ssl_target_name_override',
                 peer_config['server_hostname']), )

        peer = create_peer(endpoint=endpoint,
                           tls_cacerts=tls_cacerts,
                           opts=opts)

        tran_prop_req_in = create_tx_prop_req(prop_type=CC_INSTALL,
                                              cc_path=CC_PATH,
                                              cc_type=CC_TYPE_GOLANG,
                                              cc_name=CC_NAME,
                                              cc_version=CC_VERSION)
        args = ['a', '100', 'b', '40']
        tran_prop_req_dep = create_tx_prop_req(prop_type=CC_INSTANTIATE,
                                               cc_type=CC_TYPE_GOLANG,
                                               cc_name=CC_NAME,
                                               cc_version=CC_VERSION,
                                               fcn='init',
                                               args=args)

        org1 = 'org1.example.com'
        crypto = ecies()
        org1_admin = get_peer_org_user(org1, 'Admin', self.client.state_store)
        tx_context_in = create_tx_context(org1_admin, crypto, tran_prop_req_in)

        request = build_channel_request(self.client, self.channel_tx,
                                        self.channel_name)

        res = self.client._create_channel(request)
        q = Queue(1)
        res.subscribe(on_next=lambda x: q.put(x), on_error=lambda x: q.put(x))
        status, _ = q.get(timeout=5)
        if status.status == 200:
            logger.info("create channel successfully")

        time.sleep(5)
        channel = self.client.new_channel(self.channel_name)
        join_req = build_join_channel_req(org1, channel, self.client)
        channel.join_channel(join_req)

        res = self.client.send_install_proposal(tx_context_in, [peer])
        res.subscribe(on_next=lambda x: q.put(x), on_error=lambda x: q.put(x))
        status, _ = q.get(timeout=5)[0][0]
        if status.response.status == 200:
            logger.info("chaincode installed successfully")

        time.sleep(5)
        tx_context_dep = create_tx_context(org1_admin, crypto,
                                           tran_prop_req_dep)
        res = channel.send_instantiate_proposal(tx_context_dep, [peer])
        assert (res)
Esempio n. 19
0
 def test_ecies_generate_csr(self):
     """Test case for generate certificate signing request."""
     ecies256 = ecies()
     private_key = ecies256.generate_private_key()
     csr = ecies256.generate_csr(
         private_key,
         x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"test")]))
     csr_pem = csr.public_bytes(Encoding.PEM)
     self.assertTrue(
         csr_pem.startswith(b"-----BEGIN CERTIFICATE REQUEST-----"))
Esempio n. 20
0
    def test_secp256r1_check_malleability_and_check_prevent_malleability(self):
        """Test case for check_malleability and prevent_malleability."""
        ecies256 = ecies(CURVE_P_256_Size, SHA2)
        private_key = ecies256.generate_private_key()
        signature = ecies256.sign(private_key, self.plain_text)

        self.assertEqual(ecies256._check_malleability(signature), True)

        self.assertEqual(
            ecies256._check_malleability(
                ecies256._prevent_malleability(signature)), True)
Esempio n. 21
0
    def test_query_transaction_id_success(self):
        tx_id = self.invoke_chaincode()
        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())

        response = self.channel.query_transaction(tx_context, [self.org1_peer],
                                                  tx_id)
        q = Queue(1)
        response.subscribe(on_next=lambda x: q.put(x),
                           on_error=lambda x: q.put(x))
        res = q.get(timeout=5)
        self.assertEqual(res[0][0][0].response.status, 200)
    def test_query_chain_info(self):
        loop = asyncio.get_event_loop()

        loop.run_until_complete(self.invoke_chaincode())

        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())
        responses, proposal, header = self.channel.query_info(
            tx_context, [self.peer])
        res = loop.run_until_complete(asyncio.gather(*responses))

        self.assertEqual(res[0].response.status, 200)
Esempio n. 23
0
    def query_channels(self, requestor, peer_names, request_channel='mychannel', timeout=10):
        """
        Queries channel name joined by a peer

        :param requestor: User role who issue the request
        :param peer_names: Names of the peers to install
        :param request_channel: Name of the channel that the query sent to
        :return: A `ChannelQueryResponse`
        """

        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        request = create_tx_prop_req(
            prop_type=CC_QUERY,
            fcn='GetChannels',
            cc_name='cscc',
            cc_type=CC_TYPE_GOLANG,
            args=[]
        )

        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())
        tx_context.tx_prop_req = request

        response = Channel(request_channel, self).send_tx_proposal(
            tx_context, peers)

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        try:
            res = queue.get(timeout=timeout)
            _logger.debug(res)
            response = res[0][0][0]
            if response.response:
                query_trans = query_pb2.ChannelQueryResponse()
                query_trans.ParseFromString(res[0][0][0].response.payload)
                for ch in query_trans.channels:
                    _logger.debug('channel id {}'.format(
                        ch.channel_id))
                return query_trans
            return response

        except Exception:
            _logger.error(
                "Failed to query channel: {}", sys.exc_info()[0])
            raise
Esempio n. 24
0
    def test_ecies_secp384r1_sha2_sign_verify(self):
        """Test case for security level 256, hash SHA2."""
        ecies384 = ecies(CURVE_P_384_Size, SHA2)
        private_key = ecies384.generate_private_key()
        signature = ecies384.sign(private_key, self.plain_text)

        self.assertEqual(
            ecies384.verify(private_key.public_key(), self.plain_text,
                            signature), True)

        self.assertEqual(
            ecies384.verify(private_key.public_key(), self.plain_text + b'!',
                            signature), False)
Esempio n. 25
0
def ca_service(target=DEFAULT_CA_ENDPOINT,
               ca_certs_path=None,
               crypto=ecies(),
               ca_name=""):
    """Create ca service

    :param target: url (Default value = DEFAULT_CA_ENDPOINT)
    :param ca_certs_path: certs path (Default value = None)
    :param crypto: crypto (Default value = ecies())
    :param ca_name: CA name
    :return: ca service instance (Default value = "")
    """
    return CAService(target, ca_certs_path, crypto, ca_name)
Esempio n. 26
0
def certificate_request(name, save_path):
    ecies256 = ecies()
    private_key = ecies256.generate_private_key()
    csr = ecies256.generate_csr(private_key, x509.Name(
        [x509.NameAttribute(NameOID.COMMON_NAME, name)]))  # test02@app0001202004161020152918451
    csr_pem = csr.public_bytes(Encoding.PEM)
    sk_pem = private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, serialization.NoEncryption())
    with open(save_path, mode='wb') as f:
        f.write(sk_pem)

    # with open('pub.csr', mode='wb') as f:
    #     f.write(csr_pem)
    return csr_pem, save_path
Esempio n. 27
0
    def query_installed_chaincodes(self, requestor, peer_names, channel_name='mychannel', timeout=10):
        """
        Queries installed chaincode, returns all chaincodes installed on a peer

        :param requestor: User role who issue the request
        :param peer_names: Names of the peers to query
        :param channel_name: Name of the channel to send query to
        :return: A `ChaincodeQueryResponse`
        """
        peers = []
        for peer_name in peer_names:
            peer = self.get_peer(peer_name)
            peers.append(peer)

        request = create_tx_prop_req(
            prop_type=CC_QUERY,
            fcn='getinstalledchaincodes',
            cc_name='lscc',
            cc_type=CC_TYPE_GOLANG,
            args=[]
        )

        tx_context = create_tx_context(requestor, ecies(), TXProposalRequest())
        tx_context.tx_prop_req = request

        response = Channel(channel_name, self).send_tx_proposal(
            tx_context, peers)

        queue = Queue(1)
        response.subscribe(
            on_next=lambda x: queue.put(x),
            on_error=lambda x: queue.put(x)
        )

        try:
            res = queue.get(timeout=timeout)
            _logger.debug(res)
            response = res[0][0][0]
            if response.response:
                query_trans = query_pb2.ChaincodeQueryResponse()
                query_trans.ParseFromString(res[0][0][0].response.payload)
                for cc in query_trans.chaincodes:
                    _logger.debug('cc name {}, version {}, path {}'.format(
                                  cc.name, cc.version, cc.path))
                return query_trans
            return response

        except Exception:
            _logger.error(
                "Failed to query installed chaincodes: {}", sys.exc_info()[0])
            raise
Esempio n. 28
0
    def test_query_block_success(self):

        block_hash = self.invoke_chaincode()
        sleep(5)
        tx_context = create_tx_context(self.org1_admin, ecies(),
                                       TXProposalRequest())
        response = self.channel.query_block_by_hash(tx_context,
                                                    [self.org1_peer],
                                                    block_hash)
        q = Queue(1)
        response.subscribe(on_next=lambda x: q.put(x),
                           on_error=lambda x: q.put(x))
        res = q.get(timeout=5)
        self.assertEqual(res[0][0][0].response.status, 200)
Esempio n. 29
0
def ca_service(target=DEFAULT_CA_ENDPOINT,
               ca_certs_path=None, crypto=ecies(), ca_name=""):
    """Create ca service

    Args:
        target: url
        ca_certs_path: certs path
        crypto: crypto
        ca_name: CA name

    Returns: ca service instance

    """
    return CAService(target, ca_certs_path, crypto, ca_name)
Esempio n. 30
0
    def cc_invoke(self, args, cc_name, fcn, cc_version, queryonly=False):
        """
        Invoke a chaincode method.

        Parameters:
        args       JSON RPC serialized data used as the
                   sole parameter to invoke the chaincode
        cc_name    chaincode name
        fcn        chaincode function name to be invoked
        cc_version chaincode version to be used
        queryonly  If the invocation does not result in ledger change,
                   queryonly should be set to True.
                   If the invocation does result in ledger change, it should
                   be set to False.
        """
        if queryonly:
            return self.cc_query(args, cc_name, fcn)

        loop = asyncio.get_event_loop()
        crypto = ecies()

        endorses = self._get_endorsers(queryonly)

        tran_prop_req = create_tx_prop_req(prop_type=CC_INVOKE,
                                           cc_type=CC_TYPE_GOLANG,
                                           cc_name=cc_name,
                                           fcn=fcn,
                                           cc_version=cc_version,
                                           args=args)

        tx_context = create_tx_context(self.user, crypto, tran_prop_req)

        responses, proposal, header = self.channel.send_tx_proposal(
            tx_context, endorses.values())

        res = loop.run_until_complete(asyncio.gather(*responses))

        tran_req = build_tx_req((res, proposal, header))

        tx_context_tx = create_tx_context(self.user, crypto,
                                          TXProposalRequest())

        responses = loop.run_until_complete(
            base.get_stream_result(
                send_transaction(self.client.orderers, tran_req,
                                 tx_context_tx)))

        logger.info('Tx response: {}'.format(responses))
        return responses