def QueryClient():
    loop = asyncio.get_event_loop()

    cli = Client(net_profile="../connection-profile/network.json")
    org1_admin = cli.get_user('org1.example.com', 'Admin')
    org2_admin = cli.get_user('org2.example.com', 'Admin')

    # Make the client know there is a channel in the network
    cli.new_channel('modbuschannel')

    # Install Example Chaincode to Peers
    # GOPATH setting is only needed to use the example chaincode inside sdk
    gopath_bak = os.environ.get('GOPATH', '')
    gopath = os.path.normpath(
        os.path.join(os.path.dirname(os.path.realpath('__file__')),
                     '../chaincode'))
    os.environ['GOPATH'] = os.path.abspath(gopath)

    # Query a chaincode
    args = ["server"]
    # The response should be true if succeed#
    response = loop.run_until_complete(
        cli.chaincode_query(requestor=org1_admin,
                            channel_name='modbuschannel',
                            peers=['peer0.org1.example.com'],
                            args=args,
                            cc_name='registration_cc_v2'))

    response = json.loads(response)

    return (response)
Exemple #2
0
class FabricInitializer:
    """This provides the proper fabric client wrapper
    """
    def __init__(self,
                 net_profile=None,
                 channel_name=None,
                 cc_name=None,
                 cc_version=None,
                 org_name=None,
                 user_name=None,
                 peer_name=None):
        self.client = Client(net_profile=net_profile)
        assert self.client
        print("---client---")
        print(self.client.orderers)
        print(self.client.peers)
        print("---client---")

        self.channel_name = channel_name
        self.channel = self.client.new_channel(channel_name)
        print("---channel---")
        print("client channels: ", self.client._channels)
        print("channel: ", self.client.get_channel(channel_name))
        print("channel name: ", self.client.get_channel(channel_name).name)
        print("channel peers: ", self.client.get_channel(channel_name).peers)
        print("channel orderers: ",
              self.client.get_channel(channel_name).orderers)
        print("---channel---")
        assert self.channel

        self.cc_name = cc_name
        self.cc_version = cc_version

        self.user = self.client.get_user(org_name, user_name)
        assert self.user

        self.peers = [self.client.get_peer(peer_name)]
        assert self.peers
        print("---parameters---")
        print("User: "******"Peers: ", self.peers)
        print("cc name:", self.cc_name)
        print("---parameters---")

        self.hub = None
        self.reg_nub = None

    async def get_height(self):
        info = await self.client.query_info(self.user, self.channel_name,
                                            self.peers)
        return info.height
async def main():
    cli = Client(net_profile=os.path.join(dir_path, '../network.json'))
    admin_owkin = cli.get_user('owkin', 'admin')

    cli.new_channel('mychannel')
    peer = cli.get_peer('peer1-owkin')

    events = cli.get_events(admin_owkin,
                            peer,
                            'mychannel',
                            start=0,
                            filtered=True)

    async for v in cli.getEvents(events):
        print(v)
Exemple #4
0
def requestGetEntity(net_profile, organization, user, channel, peer, chaincode, function, arg0):
    loop = asyncio.get_event_loop()
    cli = Client(net_profile=net_profile)
    org1_admin = cli.get_user(organization, user)
    cli.new_channel(channel)
    gopath = os.path.normpath(os.path.join(os.path.dirname(
        os.path.realpath('__file__')), '../chaincode'))
    os.environ['GOPATH'] = os.path.abspath(gopath)
    args = [arg0]
    response = loop.run_until_complete(cli.chaincode_invoke(
        requestor=org1_admin,
        channel_name=channel,
        peers=[peer],
        args=args,
        cc_name=chaincode,
        transient_map=None,
        wait_for_event=True,
        fcn=function,
    ))
    return response
Exemple #5
0
def InvokeServer():
    loop = asyncio.get_event_loop()
    cli = Client(net_profile="../connection-profile/network.json")
    org1_admin = cli.get_user('org1.example.com', 'Admin')
    org2_admin = cli.get_user('org2.example.com', 'Admin')

    # Make the client know there is a channel in the network
    cli.new_channel('modbuschannel')

    # Install Example Chaincode to Peers
    # GOPATH setting is only needed to use the example chaincode inside sdk#
    gopath_bak = os.environ.get('GOPATH', '')
    gopath = os.path.normpath(os.path.join(
        os.path.dirname(os.path.realpath('__file__')),
        '../chaincode'
    ))
    os.environ['GOPATH'] = os.path.abspath(gopath)

# Invoke a chaincode
#args = ["client", "Qmeq4hW6k34a5dbpE2vc7FjSX1xmn1tphg2hGrHFGxqk16"]

    host_ip = socket.gethostbyname(socket.gethostname())
    name=host_ip.encode("utf-8")
    arg2=base64.b64encode(hashlib.sha256(name).digest())
    args = ["server", arg2]

    # The response should be true if succeed
    response = loop.run_until_complete(cli.chaincode_invoke(
        requestor=org2_admin,
        channel_name='modbuschannel',
        peers=['peer0.org2.example.com'],
        args=args,
        cc_name='registration_cc_v2',
        transient_map=None,  # optional, for private data
        # for being sure chaincode invocation has been commited in the ledger, default is on tx event
        wait_for_event=True,
        # cc_pattern='^invoked*' # if you want to wait for chaincode event and you have a `stub.SetEvent("invoked", value)` in your chaincode
    ))
Exemple #6
0
class FabricILStateManager(LocalILStateManger):
    def __init__(self,
                 net_profile: Path,
                 channel_name: str,
                 cc_name: str,
                 cc_version: str,
                 org_name: str,
                 user_name: str,
                 peer_name: str) -> None:

        self.entries_ready = [] # to store list of json objects
        self.entries_responded = [] # to store list of json objects

        self.client = Client(net_profile=net_profile)
        if not self.client:
            raise ValueError("Invalid network profile.")

        self.channel_name = channel_name
        self.channel = self.client.new_channel(channel_name)
        print(f'HF state manager - channel: {self.channel}')

        self.cc_name = cc_name
        self.cc_version = cc_version

        self.user = self.client.get_user(org_name, user_name)
        print(f'HF state manager - orgs: {self.client.organizations}')
        print(self.client.organizations['Org1MSP']._users)
        print(f'HF state manager - user: {self.user}')

        self.peers = [self.client.get_peer(peer_name)]
        print(f'HF state manager - peers: {self.peers}')

        self.hub = None
        self.reg_num = None
        self.events = []

    async def get_height(self):
        info = await self.client.query_info(self.user, self.channel_name, self.peers)
        return info.height

    async def create_entry(self,
                           id: str,
                           transfer: Transfer) -> bool:

        payload = transfer.payload
        nonce, data = payload.nonce, payload.data

        try:
            await self.client.chaincode_invoke(
                requestor=self.user,
                peers=self.peers,
                channel_name=self.channel_name,
                cc_name=self.cc_name,
                cc_version=self.cc_version,
                fcn="createTransferEntry",
                args=[nonce, data],
                wait_for_event=True)
            return True

        except Exception as e:
            print(e)
            return False

    async def signal_send_acceptance(self,
                                     id: str,
                                     signal_acceptance: bool = True) -> bool:
        try:
            await self.client.chaincode_invoke(
                requestor=self.user,
                peers=self.peers,
                channel_name=self.channel_name,
                cc_name=self.cc_name,
                cc_version=self.cc_version,
                fcn="updateTransferEntry",
                args=[id, TransferStatus.READY, signal_acceptance])
            return True

        except Exception as e:
            print(e)
            return False

    async def update_entry(self,
                           id: str,
                           status: TransferStatus,
                           transfer: Transfer = None) -> bool:

        signal_acceptance, result = transfer.send_accepted, transfer.result

        try:
            await self.client.chaincode_invoke(
                requestor=self.user,
                peers=self.peers,
                channel_name=self.channel_name,
                cc_name=self.cc_name,
                cc_version=self.cc_version,
                fcn="updateTransferEntry",
                args=[id, status, signal_acceptance, result])
            return True

        except Exception as e:
            print(e)
            return False

    async def receive_entry_events(self,
                                   event: TransferStatus) -> None:

        self.hub = self.channel.newChannelEventHub(self.peers[0], self.user)
        self.reg_num = self.hub.registerBlockEvent(
            onEvent=self._event_handler)

        if not self.height:
            self.height = await self.get_height()

        stream = self.hub.connect(filtered=False, start=self.height)
        try:
            await asyncio.wait_for(stream, timeout=1)
        except asyncio.TimeoutError:
            pass

        self.height = await self.get_height()

        if event == TransferStatus.READY:
            self.transfers_ready = self._buffer_data(self.entries_ready)
        if event == TransferStatus.RESPONDED:
            self.transfers_responded = self._buffer_data(self.entries_responded)

        # clean up
        self.hub.disconnect()
        self.hub.unregisterBlockEvent(self.reg_num)

    def _event_handler(self, event_obj):
        d = event_obj['data']['data']
        actions = d[0]['payload']['data']['actions']
        action = actions[0]

        event = action['payload']['action']['proposal_response_payload']['extension']['events']
        event_name = event['event_name']

        if event_name == "transferReady":
            self.entries_ready.append(event)
        if event_name == "transferResponded":
            self.entries_responded.append(event)


    def _buffer_data(self, events):

        res = []
        for event in events:
            transfer = Transfer()

            json_str = event['payload']
            t_obj = json.loads(json_str)
            
            transfer.status, = t_obj['status']
            transfer.payload = t_obj['payload']

            if transfer.status == TransferStatus.RESPONDED:
                transfer.send_accepted = t_obj['sendAcceptance']
                transfer.result = json.loads(t_obj['result'])   

            res.append(transfer)

        return res
Exemple #7
0
import asyncio
from hfc.fabric import Client

loop = asyncio.get_event_loop()

cli = Client(
    net_profile=
    "/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json"
)
org1_admin = cli.get_user('org1.dz', 'Admin')

org1_admin = cli.get_user(org_name='org1.dz', name='Admin')
# Make the client know there is a channel in the network
cli.new_channel('secondchannel')

# Instantiate Chaincode in Channel, the response should be true if succeed
args = ['a', '200', 'b', '300']

# policy, see https://hyperledger-fabric.readthedocs.io/en/release-1.4/endorsement-policies.html

policy = {
    "identities": [{
        "role": {
            "name": "member",
            "mspId": "PeerOrg1MSP"
        }
    }],
    "policy": {
        "1-of": [{
            "signed-by": 0
        }]
Exemple #8
0
import os
import time
import asyncio
from hfc.fabric import Client

CONNECTION_PROFILE_PATH = 'test/fixtures/network.json'
CONFIG_YAML_PATH = 'test/fixtures/e2e_cli/'
CHAINCODE_PATH = 'test/fixtures/chaincode'

if __name__ == "__main__":
    loop = asyncio.get_event_loop()

    cli = Client(net_profile=CONNECTION_PROFILE_PATH)

    # get the admin user from local path
    org1_admin = cli.get_user(org_name='org1.example.com', name='User1')

    # Query Peer installed chaincodes
    response = loop.run_until_complete(
        cli.query_installed_chaincodes(requestor=org1_admin,
                                       peers=['peer0.org1.example.com']))
    print("Query installed chaincode.")
    print(response)

    # query channels joined in by given peers
    response = loop.run_until_complete(
        cli.query_channels(requestor=org1_admin,
                           peers=['peer0.org1.example.com']))
    print("Channels: ", response)

    # check if channel named "businesschannel" is already exists
Exemple #9
0
class FabricEvents:
    def __init__(self):
        self._configtx_dir = None
        self._chaincode_dir = None
        self._config_sdk = None
        self._cli = None
        self._settings = None

    def config(self, settings, configsdk, chaincode, configtx):
        self._settings = settings
        self._configtx_dir = configtx
        self._chaincode_dir = chaincode
        self._config_sdk = configsdk
        if all([settings, configsdk, chaincode, configtx]):
            logger.info("FabricEvents configs OK")
            logger.info(
                "configsdk %s, chaincode %s, configtx %s",
                configsdk,
                chaincode,
                configtx,
            )

            self.config_gopath()
            self.build_cli()
            return True
        else:
            logger.info("FabricEvents configs FAILED")
            return False

    def config_gopath(self):
        gopath = os.path.normpath(os.path.join(self._chaincode_dir))
        os.environ["GOPATH"] = os.path.abspath(gopath)

    def build_cli(self):
        pathlist = [
            "$HOME/hl/bin",
        ]  # TODO set dynamic config path for configtxgen bin
        os.environ["PATH"] += os.pathsep + os.pathsep.join(pathlist)

        self._cli = Client(net_profile=self._config_sdk)
        logger.debug("Fabric Orgs %s", self._cli.organizations)
        logger.debug("Fabric Peers %s", self._cli.peers)
        logger.debug("Fabric Orderers %s", self._cli.orderers)
        logger.debug("Fabric CAs %s", self._cli.CAs)
        logger.info("Fabric Client SDK CLI Started")

    def schedule(self, events):
        evs_sched = {}

        for event in events:
            ev_id = event.get("id")
            ev_data = event.get("event")
            action_call = self.create_call(ev_data)
            if action_call:
                evs_sched[ev_id] = (action_call, event.get("schedule"))
            else:
                logger.info(
                    f"Could not schedule fabric event task call for event {event}"
                )

        return evs_sched

    def create_call(self, event):
        task = None
        action = event.get("action")

        if action == "info_network":
            task = self.event_info_network(event)
        if action == "create_channel":
            task = self.event_create_channel(event)
        if action == "join_channel":
            task = self.event_join_channel(event)
        if action == "info_channels":
            task = self.event_info_channels(event)
        if action == "info_channel":
            task = self.event_info_channel(event)
        if action == "info_channel_config":
            task = self.event_info_channel_config(event)
        if action == "info_channel_chaincodes":
            task = self.event_info_channel_chaincodes(event)
        if action == "chaincode_install":
            task = self.event_chaincode_install(event)
        if action == "chaincode_instantiate":
            task = self.event_chaincode_instantiate(event)
        if action == "chaincode_invoke":
            task = self.event_chaincode_invoke(event)
        if action == "chaincode_query":
            task = self.event_chaincode_query(event)

        if task:
            return task
        else:
            logger.info("Unkown task for event %s", event)
            return None

    async def event_create_channel(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        orderer_name = ev.get("orderer")
        channel = ev.get("channel")
        profile = ev.get("profile")

        orderer = self._settings.get("orderers").get(orderer_name)
        orderer_fqdn = orderer.get("orderer_fqdn")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        if org_fqdn and orderer_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.channel_create(
                orderer=orderer_fqdn,
                channel_name=channel,
                requestor=org_user,
                config_yaml=self._configtx_dir,
                channel_profile=profile,
            )
            logger.info("FABRIC_EV:create_channel: Create channel response %s",
                        response)
            return response

        logger.info("unknown orderer %s and org %s", orderer_name, org_name)
        return None

    async def event_join_channel(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        orderer_name = ev.get("orderer")
        channel = ev.get("channel")
        peers_names = ev.get("peers")

        orderer = self._settings.get("orderers").get(orderer_name)
        orderer_fqdn = orderer.get("orderer_fqdn")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        if org_fqdn and orderer_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            peers = org.get("peers")
            peers_fqdn = [
                peer.get("peer_fqdn") for peer in peers.values()
                if peer.get("name") in peers_names
            ]

            response = await self._cli.channel_join(
                requestor=org_user,
                channel_name=channel,
                peers=peers_fqdn,
                orderer=orderer_fqdn,
            )
            logger.info("FABRIC_EV:join_channel: Join channel response %s",
                        response)
            return response

        logger.info("unknown orderer %s and org %s", orderer_name, org_name)
        return None

    async def event_info_channel(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        channel = ev.get("channel")
        peers_names = ev.get("peers")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.query_info(requestor=org_user,
                                                  channel_name=channel,
                                                  peers=peers_fqdn,
                                                  decode=True)
            logger.info("FABRIC_EV:info_channel: Info channel response %s",
                        response)
            return response

        logger.info("unknown org %s and/org peers %s", org_name, peers_names)
        return None

    async def event_info_channels(self, ev):
        logger.info("Event fabric: info_channels")
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.query_channels(requestor=org_user,
                                                      peers=peers_fqdn,
                                                      decode=True)
            logger.info("FABRIC_EV:info_channels: Info channels response %s",
                        response)
            return response

        logger.info("unknown org %s and/org peers %s", org_name, peers_names)
        return None

    async def event_info_channel_config(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        channel = ev.get("channel")
        peers_names = ev.get("peers")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.get_channel_config(requestor=org_user,
                                                          channel_name=channel,
                                                          peers=peers_fqdn,
                                                          decode=True)
            logger.info(
                "FABRIC_EV:info_channel_config: Info channel config response %s",
                response,
            )
            return response

        logger.info("unknown org %s and/org peers %s", org_name, peers_names)
        return None

    async def event_info_channel_chaincodes(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.query_installed_chaincodes(
                requestor=org_user, peers=peers_fqdn, decode=True)
            logger.info(
                "FABRIC_EV:info_channel_chaincodes: Info channel chaincodes response %s",
                response,
            )
            return response

        logger.info("unknown org %s and/org peers %s", org_name, peers_names)
        return None

    async def event_info_network(self, ev):
        orderer_name = ev.get("orderer")
        orderer = self._settings.get("orderers").get(orderer_name)
        orderer_fqdn = orderer.get("orderer_fqdn")

        if orderer_fqdn:
            response = self._cli.get_net_info("organizations", orderer_fqdn,
                                              "mspid")
            logger.info("Info network response %s", response)
            return response

        logger.info("unknown orderer %s", orderer_name)
        return None

    async def event_chaincode_install(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")
        chaincode_name = ev.get("chaincode_name")
        chaincode_path = ev.get("chaincode_path")
        chaincode_version = ev.get("chaincode_version")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.chaincode_install(
                requestor=org_user,
                peers=peers_fqdn,
                cc_path=chaincode_path,
                cc_name=chaincode_name,
                cc_version=chaincode_version,
            )
            logger.info(
                "FABRIC_EV:chaincode_install: Chaincode install response %s",
                response)
            return response

        logger.info("unknown org %s and/or peers %s", org_name, peers_names)
        return None

    async def event_chaincode_instantiate(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")
        channel = ev.get("channel")
        chaincode_args = ev.get("chaincode_args")
        chaincode_name = ev.get("chaincode_name")
        chaincode_version = ev.get("chaincode_version")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.chaincode_instantiate(
                requestor=org_user,
                channel_name=channel,
                peers=peers_fqdn,
                args=chaincode_args,
                cc_name=chaincode_name,
                cc_version=chaincode_version,
            )
            logger.info(
                "FABRIC_EV:chaincode_instantiate: Chaincode instantiate response %s",
                response,
            )
            return response

        logger.info("unknown org %s and/or peers %s", org_name, peers_names)
        return None

    async def event_chaincode_invoke(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")
        channel = ev.get("channel")
        chaincode_args = ev.get("chaincode_args")
        chaincode_name = ev.get("chaincode_name")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.chaincode_invoke(
                requestor=org_user,
                channel_name=channel,
                peers=peers_fqdn,
                args=chaincode_args,
                cc_name=chaincode_name,
            )
            logger.info(
                "FABRIC_EV:chaincode_invoke: Chaincode invoke response %s",
                response)
            return response

        logger.info("unknown org %s and/or peers %s", org_name, peers_names)
        return None

    async def event_chaincode_query(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")
        channel = ev.get("channel")
        chaincode_args = ev.get("chaincode_args")
        chaincode_name = ev.get("chaincode_name")

        org = self._settings.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.chaincode_query(
                requestor=org_user,
                channel_name=channel,
                peers=peers_fqdn,
                args=chaincode_args,
                cc_name=chaincode_name,
            )
            logger.info(
                "FABRIC_EV:chaincode_query: Chaincode query response %s",
                response)
            return response

        logger.info("unknown org %s and/or peers %s", org_name, peers_names)
        return None
Exemple #10
0
class Smartmeter():
    '''A class define what each noeud can do in the consenus process'''

    def __init__(self, me):
        '''Initialisation some attributes'''
        self.me = me  # id of smart meter
        self.users = 12  # number of smart meters in the network
        # list_reputation = []
        self.peers = 4  # number of peers (P% best nodes)

    def get_list_from_bloc(self):

        ''' Get the reputation list from the last bloc in the blockchain '''

        self.loop = asyncio.get_event_loop()
        self.cli = Client(
            net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")
        self.org1_admin = self.cli.get_user('org1.dz', 'Admin')
        self.cli.new_channel("firstchannel")

        # first get the hash by calling 'query_info'
        self.response = self.loop.run_until_complete(self.cli.query_info(
            requestor=self.org1_admin,
            channel_name='firstchannel',
            peers=['peer0.org1.dz'],
            decode=True
        ))

        self.test_hash = self.response.currentBlockHash

        self.response = self.loop.run_until_complete(self.cli.query_block_by_hash(
            requestor=self.org1_admin,
            channel_name='firstchannel',
            peers=['peer0.org1.dz'],
            block_hash=self.test_hash,
            decode=True
        ))

        self.List_rep_bloc_byte = \
            self.response.get('data').get('data')[0].get('payload').get('data').get('actions')[0].get('payload').get(
                'action').get(
                'proposal_response_payload').get('extension').get('results').get('ns_rwset')[0].get('rwset').get(
                'writes')[
                0].get('value')
        self.List_rep_bloc_str = self.List_rep_bloc_byte.decode("UTF-8")  # convert byte to string
        self.List_rep_bloc_dic = ast.literal_eval(self.List_rep_bloc_str)  # convert dictionary string to dictionary
        
        for self.k, self.v in self.List_rep_bloc_dic.items():
            if self.k == 'Liste des reputations':
                self.List_rep_bloc = ast.literal_eval(self.v) # convert list from str -> list
        #str to int
        #for self.i in range(0, len(self.List_rep_bloc)):
         #   self.List_rep_bloc[self.i] = int(self.List_rep_bloc[self.i])

        return self.List_rep_bloc


    def get_leader_and_p(self, reputation_list_bloc):
        ''' return the leader and the P% nodes based on the reputation list in the last bloc in the blockchain '''
        self.list_reputation_slice = reputation_list_bloc[:]
        self.leader_id = self.list_reputation_slice.index(
            max(self.list_reputation_slice))  # 1er min id of node -leader- (men les P%) that has max reputation.
        self.list_p = []
        self.list_p.append(self.leader_id)
        self.list_reputation_slice[self.leader_id] = 0

        for i in range(0, self.peers - 1):
            self.p_id = self.list_reputation_slice.index(max(
                self.list_reputation_slice))  # p_1 i.e P%_1 - premier noeud du p% - (# 2eme min id of node (men les P%) that has max reputation.)
            self.list_p.append(self.p_id)  # list_p contient le id du leader et les id des P%.
            self.list_reputation_slice[self.p_id] = 0

        return self.list_p

    def send_mesure_to_p(self, user, list_p):
        '''Send data to all P% -normalment to all nodes-'''

        self.loop = asyncio.get_event_loop()

        self.cli = Client(
            net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")
        self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
        # Make the client know there is a channel in the network
        self.cli.new_channel('secondchannel')

        self.my_data = str(random.randint(2, 22)) + "kw"  # data consumed by the SM
        # my_reputation = str(list_reputation[Me])   #reputation of this SM.  On envoi pas la reputation.

        for i in range(0, self.peers):
            '''Send data consumed by this SM
                To all the peers in the network (P%)
                car c eux qui font la verification du bloc
                '''

            self.args = ['SM' + str(list_p[i]), str(self.me), str(self.my_data)]

            # The response should be true if succeed
            self.response = self.loop.run_until_complete(
                self.cli.chaincode_invoke(
                    requestor=self.org1_admin,
                    channel_name='secondchannel',
                    peers=['peer' + str(i) + '.org1.dz'],
                    args=self.args,
                    fcn='NewData',
                    cc_name='test_cc2',
                    transient_map=None,  # optional, for private data
                    wait_for_event=True,
                )
            )

    def retrieve_merkle_data(self, user, list_p):
        self.ret = ""
        self.loop = asyncio.get_event_loop()

        self.cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")

        self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
        # Make the client know there is a channel in the network
        self.cli.new_channel('secondchannel')

        self.list_pp = list_p[:]
        self.list_data_retrived = []
        #del self.list_pp[0]
        if 1 == 1:
#            self.list_data_retrived = []
            self.args = ['SM' + str(self.list_pp[0])]
            self.lead_me = '0' # l'id du peer qui est relier avec le leader
            for i in range(0, 2):
                # The response should be true if succeed
                self.response = self.loop.run_until_complete(self.cli.chaincode_query(
                    requestor=self.org1_admin,
                    fcn="GetData",
                    channel_name='secondchannel',
                    peers=['peer' + self.lead_me + '.org1.dz'],
                    args=self.args,
                    cc_name='test_cc2'
                ))
                self.response = json.loads(self.response)
                self.list_data_retrived.append(self.response)
                if self.me == self.list_pp[0] or self.me not in self.list_pp:
                    break
                self.args = ['SM' + str(self.me)]
                self.lead_me = str(self.list_pp.index(self.me))  # mon id in str to use it in cli.chaincode_query "peers"


                #self.response = json.loads(self.response)
#
                #self.list_data_retrived.append(self.response)
#
           # print(self.list_data_retrived)
            

            if self.me in self.list_pp and self.me != self.list_pp[0]:
                if (self.list_data_retrived[0]['MerklerootDATA'] == self.list_data_retrived[1]['MerklerootDATA']):
                    self.ret = "true"
                else:
                    self.ret = "false"

        return (self.list_data_retrived[0]['Consommations'], self.list_data_retrived[0]['MerklerootDATA'], self.list_data_retrived[0]['Timestamp'], self.ret)


    def send_vote_b1(self, user, list_p, result_comparaison):
        
        ''' every user from P% send votes about the validation of B1 (merkle root local comparer avec merkle root du leader)'''

        self.list_pp = list_p[:]
        del self.list_pp[0]
        
        if self.me in self.list_pp:

            if result_comparaison == "true":
                self.vote = "accepter"
            elif result_comparaison == "false":
                self.vote = "rejeter"


            self.loop = asyncio.get_event_loop()

            self.cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")

            self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
            # Make the client know there is a channel in the network
            self.cli.new_channel('secondchannel')

        
            self.args = ["B1_votes", str(self.me), self.vote]
    
            # The response should be true if succeed
            self.response = self.loop.run_until_complete(self.cli.chaincode_invoke(
                requestor=self.org1_admin,
                fcn='Votes',
                channel_name='secondchannel',
                peers=['peer0.org1.dz'], # the peer of the leader
                args=self.args,
                cc_name='test_cc2',
                transient_map=None, 
                wait_for_event=True,
                ))


    
    def retrieve_vote_b1(self, user):

        '''Every user retrieve the list of validation of B1 that contain the votes of P%, and if B1 is valid or not'''
        
        self.loop = asyncio.get_event_loop()
        self.cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")

        self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
        # Make the client know there is a channel in the network
        self.cli.new_channel('secondchannel')

        self.args = ['B1_votes']
                # The response should be true if succeed
        self.response = self.loop.run_until_complete(self.cli.chaincode_query(
                requestor=self.org1_admin,
                fcn='GetVotes',
                channel_name='secondchannel',
                peers=['peer0.org1.dz'],
                args=self.args,
                cc_name='test_cc2'
                ))

        self.response = ast.literal_eval(self.response)  # convert dictionary string to dictionary
        return self.response["List Votes"]  # return List


    def maj_reputations(self, List, List_vote, leader):
        '''mise a jour de la liste des reputations'''
        self.validation_bloc = List_vote[-1]
        self.List_copy = List[:]
        if self.validation_bloc == 'valide':
            self.List_copy [leader] = self.List_copy [leader] + 10
            for self.i in range(0, len(List_vote)):
                if List_vote[self.i] == 'accepter':
                    self.List_copy[self.i] = self.List_copy[self.i] + 10
                elif List_vote[self.i] == 'rejeter':
                    self.List_copy[self.i] = self.List_copy[self.i] - 10

        if self.validation_bloc == 'notvalide':
            self.List_copy [leader] = self.List_copy [leader] - 10
            for self.i in range(0, len(List_vote)):
                if List_vote[self.i] == 'accepter':
                    self.List_copy[self.i] = self.List_copy[self.i] - 10
                elif List_vote[self.i] == 'rejeter':
                    self.List_copy[self.i] = self.List_copy[self.i] + 10

        for self.i in range(0, len(List)):
            if self.List_copy[self.i] > 100:
                self.List_copy[self.i] = 100
            elif self.List_copy[self.i] < 0:
                self.List_copy[self.i] = 0


        return self.List_copy



    def select_new_leader(self, p_leader, validation_b1, liste_vote_b1):
        '''change leader only if the validation of bloc B1 (validation_b1) is = notvalid '''
        self.new_leader = p_leader[0]
        self.p_leader_new = p_leader[:]
        self.boo = 1
        
        if validation_b1 == 'notvalid':
            while self.boo:
                self.ancien_leader = self.p_leader_new.pop(0)
                self.p_leader_new.append(self.ancien_leader)
                self.new_leader = self.p_leader_new[0]
                if list_vote_b1[self.new_leader] == 'rejeter':
                    self.boo = 0

        return (self.p_leader_new, self.new_leader)



    def calculate_merkle_reputations(self, p_leader_new, list_rep_updated):
        '''Calculer le merkle root de la liste des reputations par chaque noeud des P%'''
        self.liste_maj_rep = list_rep_updated[:]
        self.mt = MerkleTools(hash_type="sha256")
        for self.i in range(0, len(self.liste_maj_rep)):
            self.liste_maj_rep[self.i] = str(self.liste_maj_rep[self.i])
        self.mt.add_leaf(self.liste_maj_rep, True)
        self.mt.make_tree()
        self.is_ready = self.mt.is_ready
       	self.root_value = self.mt.get_merkle_root()
        return self.root_value



    def send_maj_reputations(self, user, p_leader, p_leader_new, liste_maj_rep_hash):
        # mypeer is the peer of the user(node) from the updated list p_leader "p_leader_new".
        '''send the new reputations list to the actual peer of the leader in order to make a merkle root for it'''
        if self.me == p_leader_new[0]:
            self.loop = asyncio.get_event_loop()

            self.cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")

            self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
            # Make the client know there is a channel in the network
            self.cli.new_channel('secondchannel')

            self.mypeer = p_leader.index(p_leader_new[0])
            self.args = ["hash_reputations", liste_maj_rep_hash]

            # The response should be true if succeed
            self.response = self.loop.run_until_complete(self.cli.chaincode_invoke(
                requestor=self.org1_admin,
                fcn='NewRep',
                channel_name='secondchannel',
                peers=['peer'+str(self.mypeer)+'.org1.dz'], # the peer of the leader
                args=self.args,
                cc_name='test_cc2',
                transient_map=None,
                wait_for_event=True,
                ))
        

    def retrieve_merkle_reputations(self, user, p_leader, p_leader_new, local_hash_rep): 
        # l'id du peer qui est relier avec le leader
        '''recuperer le merkle root de la liste de reputations a partir du peer du leader'''
        self.result_comparaison2 = ""
        self.loop = asyncio.get_event_loop()

        self.cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")

        self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
        # Make the client know there is a channel in the network
        self.cli.new_channel('secondchannel')
        self.list_pp = p_leader_new[:]
        del self.list_pp[0]
        if self.me in self.list_pp:
            self.list_data_retrived = []
            self.args = ["hash_reputations"]

            self.peer_leader = p_leader.index(p_leader_new[0])
            # The response should be true if succeed
            self.response = self.loop.run_until_complete(self.cli.chaincode_query(
                requestor=self.org1_admin,
                fcn='GetRep',
                channel_name='secondchannel',
                peers=['peer' + str(self.peer_leader) + '.org1.dz'],
                args=self.args,
                cc_name='test_cc2'
                ))

            #self.lead_me = str(self.list_pp.index(self.me) + 1)  # mon id in str to use it in cli.chaincode_query "peers"


            self.response = json.loads(self.response)
            #print(type(self.response))
            #self.list_data_retrived.append(self.response)
#
#            print(self.list_data_retrived)
            if self.response['MerklerootReputations'] == local_hash_rep:
            	self.result_comparaison2 = "true"
            else:
            	self.result_comparaison2 = "false"
        
        return self.result_comparaison2



    def send_vote_b2(self, user, list_p, result_comparaison):
        
        ''' every user from P% send votes about the validation of B2 (merkle root local comparer avec merkle root du leader)'''

        self.list_pp = list_p[:]
        del self.list_pp[0]
        
        if self.me in self.list_pp:

            if result_comparaison == "true":
                self.vote = "accepter"
            elif result_comparaison == "false":
                self.vote = "rejeter"


            self.loop = asyncio.get_event_loop()

            self.cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")

            self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
            # Make the client know there is a channel in the network
            self.cli.new_channel('secondchannel')

        
            self.args = ["B2_votes", str(self.me), self.vote]
    
            # The response should be true if succeed
            self.response = self.loop.run_until_complete(self.cli.chaincode_invoke(
                requestor=self.org1_admin,
                fcn='Votes',
                channel_name='secondchannel',
                peers=['peer0.org1.dz'], # the peer of the leader "not necessarly"
                args=self.args,
                cc_name='test_cc2',
                transient_map=None, 
                wait_for_event=True,
                ))


    def retrieve_vote_b2(self, user):

        '''Every user retrieve the list of validation of B2 that contain the votes of P%, and if B1 is valid or not'''
        
        self.loop = asyncio.get_event_loop()
        self.cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")

        self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
        # Make the client know there is a channel in the network
        self.cli.new_channel('secondchannel')

        self.args = ["B2_votes"]
                # The response should be true if succeed
        self.response = self.loop.run_until_complete(self.cli.chaincode_query(
                requestor=self.org1_admin,
                fcn='GetVotes',
                channel_name='secondchannel',
                peers=['peer0.org1.dz'],
                args=self.args,
                cc_name='test_cc2',
                ))

        self.response = ast.literal_eval(self.response)  # convert dictionary string to dictionary
        return self.response["List Votes"]  # return List




    def validation_b2(self,user, state_b2, state_b1, p_leader_new, time, data, mr_data, list_reputations, mr_reputations):
        ''' '''
        self.value = ""
        self.k = 0
        if state_b2 == 'notvalide':
            self.value = 'notvalide'
        elif state_b2 == 'valide' and state_b1 == 'valide':
            self.value = 'valide'
            self.k = 1
        elif state_b2 == 'valide' and state_b1 == 'notvalide':
            self.value = 'valide'
            self.k = 1
            for self.i in range(0, len(data)):
                data[self.i] = "0" 
            self.mt = MerkleTools(hash_type="sha256")
            self.mt.add_leaf(data, True)
            self.mt.make_tree()
            mr_data = self.mt.get_merkle_root()
        
        #print(self.value)
        #print(p_leader_new[0])
        if self.k == 1 and self.me == p_leader_new[0]:
            #print(self.value)
            #print(p_leader_new[0])
            self.loop = asyncio.get_event_loop()
            self.cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")
            self.org1_admin = self.cli.get_user('org1.dz', user)  # user = User1 or User2 ...
            # Make the client know there is a channel in the network
            self.cli.new_channel('firstchannel')
            self.args = [str(time), str(data), str(mr_data), str(list_reputations), str(mr_reputations)]
    
           # The response should be true if succeed
            self.response = self.loop.run_until_complete(self.cli.chaincode_invoke(
               	requestor=self.org1_admin,
               	fcn='NewData',
               	channel_name='firstchannel',
               	peers=['peer0.org1.dz'], 
               	args=self.args,
               	cc_name='first_chaincode',
               	transient_map=None, 
               	wait_for_event=True,
	                ))
            #print(self.response)
            #exit()
            
            return self.value
Exemple #11
0
import os
import asyncio
from hfc.fabric import Client

loop = asyncio.get_event_loop()

cli = Client(net_profile="../connection-profile/network.json")
org1_admin = cli.get_user('org1.example.com', 'Admin')
org2_admin = cli.get_user('org2.example.com', 'Admin')

# Make the client know there is a channel in the network
cli.new_channel('modbuschannel')

# Install Example Chaincode to Peers
# GOPATH setting is only needed to use the example chaincode inside sdk
gopath_bak = os.environ.get('GOPATH', '')
gopath = os.path.normpath(
    os.path.join(os.path.dirname(os.path.realpath('__file__')),
                 '../chaincode'))
os.environ['GOPATH'] = os.path.abspath(gopath)

# Query a chaincode
args = ['b']
# The response should be true if succeed
response = loop.run_until_complete(
    cli.chaincode_query(requestor=org1_admin,
                        channel_name='modbuschannel',
                        peers=['peer0.org1.example.com'],
                        args=args,
                        cc_name='example_cc'))
Exemple #12
0
# import modules
import asyncio
import ast
from hfc.fabric import Client
import json
import random
from merkletools import MerkleTools
import time


loop = asyncio.get_event_loop()
cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")

org1_admin = cli.get_user('org1.dz', 'Admin')  # user = User1 or User2 ...
# Make the client know there is a channel in the network
cli.new_channel('secondchannel')


SMs = ['SM0', 'SM1', 'SM2', 'SM3', 'SM4', 'SM5', 'SM6', 'SM7', 'SM8', 'SM9', 'SM10', 'SM11', 'B1_votes', 'B2_votes', 'hash_reputations']



for key in SMs:

    args = [key]
 #   print(args)
    # The response should be true if succeed
    response = loop.run_until_complete(cli.chaincode_invoke(
         requestor=org1_admin,
         fcn='Delete',
import os
import asyncio
import subprocess

from hfc.fabric import Client

from substrabac.settings.common import PROJECT_ROOT

dir_path = os.path.dirname(os.path.realpath(__file__))

cli = Client(net_profile=os.path.join(dir_path, '../network.json'))
admin_owkin = cli.get_user('owkin', 'admin')

cli.new_channel('mychannel')

loop = asyncio.get_event_loop()

from hfc.fabric_ca.caservice import ca_service

cacli = ca_service(target="https://rca-owkin:7054",
                   ca_certs_path='/substra/data/orgs/owkin/ca-cert.pem',
                   ca_name='rca-owkin')

print('Will try to enroll admin')
try:
    admin = cacli.enroll('admin-owkin', 'admin-owkinpw')
except ValueError as e:
    print(e)
except Exception as e:
    print(e)
else:
Exemple #14
0
async def channel_setup(net_profile, channel_name, org_name, user_name):
    """Set up the client, creata channel and join peers into it
    :param net_profile: the network profile, the rest uses static settings other than parameters

    :returns: the client for further interaction
    """
    cli = Client(net_profile=net_profile)

    print(cli.organizations) # orgs in the network
    print(cli.peers) # peers in the network
    print(cli.orderers) # orderers in the network
    print(cli.CAs) # ca nodes in the network

    # get the admin user from local path
    org1_admin = cli.get_user(org_name=org_name, name=user_name)

    orderer = list(cli.orderers)[0] # assumes the first to choose

    # Create a New Channel, the response should be true if succeed
    response = await cli.channel_create(
        orderer=orderer, 
        channel_name=channel_name,
        requestor=org1_admin,
        config_yaml=CONFIG_YAML_PATH,
        channel_profile='TwoOrgsChannel'
    )
    if response:
        print("Create channel successful")
        print("Create channel response:", response)
    else:
        print("Create channel failed")
        print(response)
        exit(-1)

    # Join Peers into Channel, the response should be true if succeed
    peers_org1 = [peer for peer in cli.peers if 'org1' in peer] # assumes peers in org1 are wanted ones

    response = await cli.channel_join(
        requestor=org1_admin,
        channel_name=channel_name,
        peers=peers_org1,
        orderer=orderer)
    if response:
        print("Join channel successful")
    else:
        print("Join channel failed")
        exit(-1)

    # Join peers from a different MSP into Channel
    org2_admin = cli.get_user(org_name='org2.example.com', name=user_name)
    peers_org2 = [peer for peer in cli.peers if 'org2' in peer] # assumes peers in org2 are wanted ones

    response = await cli.channel_join(
        requestor=org2_admin,
        channel_name=channel_name,
        peers=peers_org2,
        orderer=orderer)
    if response:
        print("Join channel successful")
    else:
        print("Join channel failed")
        exit(-1)

    return cli
Exemple #15
0
import asyncio
import ast
from hfc.fabric import Client
import json
loop = asyncio.get_event_loop()
cli = Client(net_profile="/home/Adel/Desktop/PFE/Two_Chain_Network_Template/pfe-project/sdk/MyNetwork.json")
org1_admin = cli.get_user('org1.dz', 'User1')

cli.new_channel("firstchannel")
# first get the hash by calling 'query_info'
response = loop.run_until_complete(cli.query_info(
             requestor=org1_admin,
             channel_name='firstchannel',
             peers=['peer0.org1.dz'],
             decode=True
                       ))

print(response)
test_hash = response.currentBlockHash

response = loop.run_until_complete(cli.query_block_by_hash(
               requestor=org1_admin,
               channel_name='firstchannel',
               peers=['peer0.org1.dz'],
               block_hash=test_hash,
               decode=True
               ))

List_rep_bloc_byte = response.get('data').get('data')[0].get('payload').get('data').get('actions')[0].get('payload').get('action').get('proposal_response_payload').get('extension').get('results').get('ns_rwset')[0].get('rwset').get('writes')[0].get('value')

Exemple #16
0
class Gateway(object):
    """The gateway peer provides the connection point for an application to access the Fabric network.
    It can then be connected to a fabric network using the path to network profile.
    """
    def __init__(self):
        """ Construct Gateway. """
        self.client = None
        self.wallet = None
        self.networks = dict()
        self.options = dict()

    def mergeOptions(self, currentOptions, additionalOptions):
        """Merge additional options to current options

        :param currentOptions: current options
        :param additionalOptions: additional options to be merged
        :return: result
        """
        result = currentOptions
        for prop in additionalOptions:
            if prop in result and isinstance(
                    result[prop], dict) and isinstance(additionalOptions[prop],
                                                       dict):
                self.mergeOptions(result[prop], additionalOptions[prop])
            else:
                result[prop] = additionalOptions[prop]
        return result

    async def connect(self, net_profile, options):
        """
        Connect to the Gateway with a connection profile and connection options.
        :param net_profile: Path to the Connection Profile
        :param options: Options such as wallet identity and user identity
        :return:
        """
        if 'wallet' not in options:
            _logger.error("A wallet must be assigned to a gateway instance")

        if not net_profile:
            self.client = Client()
        else:
            self.client = Client(net_profile=net_profile)

        if 'identity' in options:
            self.current_identity = self.client.get_user(
                org_name=options['identity']['org_name'],
                name=options['identity']['name'])

    def get_current_identity(self):
        """:return: The current identity being used in the gateway."""
        return self.current_identity

    def get_client(self):
        """:return: Client instance."""
        return self.client

    def get_options(self):
        """:return: the options being used."""
        _logger.debug('in get_options')
        return self.options

    def disconnect(self):
        """Clean up and disconnect this Gateway connection"""
        _logger.debug('in disconnect')
        self.networks.clear()

    # TODO : remove requestor and integrate this with wallet and identity
    async def get_network(self, network_name, requestor):
        """
        Returns an object representing a network
        :param Name of the channel
        :param requestor: User role who issue the request
        :return: Network instance
        """
        method = 'get_network'

        existing_network = self.networks.get(network_name)
        if existing_network:
            _logger.debug('%s - returning existing network:%s', method,
                          network_name)
            return existing_network

        new_network = Network(self, network_name)
        await new_network._initialize({'requestor': requestor})
        self.networks[network_name] = new_network
        return new_network
admin_user_name = 'admin'
admin_password = '******'
function = 'ListBankAccounts'
admin_fee_frac = 0.5

hf_client = Client(net_profile=constants.config_path)

hf_client.new_channel(constants.channel_name)

network_info = hf_client.get_net_info()

peers = network_info['organizations'][org_name]['peers']
random_peer = random.choice(peers)

user = enroll_user(hf_client, org_name, user_name, user_password)
user = hf_client.get_user(org_name=org_name, name='Admin')

loop = asyncio.get_event_loop()

response = loop.run_until_complete(
    operations.invoke('appdevorg.beatchain.com',
                      admin_user_name,
                      admin_password,
                      constants.channel_name,
                      function='AddAppDevRecord',
                      args=["afldsfj;ls"]))

# Query Peer installed chaincodes, make sure the chaincode is installed
response = loop.run_until_complete(
    operations.invoke('appdevorg.beatchain.com',
                      admin_user_name,
Exemple #18
0
# use a python shell for your tests

from hfc.fabric import Client
import asyncio

loop = asyncio.get_event_loop()

cli = Client(net_profile=
             "/*****************YOUR_PATH*****************/sdk/MyNetwork.json")

print(cli.organizations)  # orgs in the network
print(cli.peers)  # peers in the network
print(cli.orderers)  # orderers in the network
print(cli.CAs)  # ca nodes in the network

orderer_admin = cli.get_user(org_name="orderer1.org1.dz", name="Admin")
org1_admin = cli.get_user(org_name="org1.dz", name="Admin")
org1_user1 = cli.get_user(org_name="org1.dz", name="User1")

# your policy
policy = {
    "identities": [{
        "role": {
            "name": "member",
            "mspId": "PeerOrg1MSP"
        }
    }],
    "policy": {
        "1-of": [{
            "signed-by": 0
        }]
Exemple #19
0
class FabricEvents:
    def __init__(self):
        self._async_loop = asyncio.get_event_loop()
        self._configtx_dir = None
        self._chaincode_dir = None
        self._config_sdk = None
        self._cli = None
        self._topo = None

    def config(self, topology, configsdk, chaincode, configtx):
        self._topo = topology
        self._configtx_dir = configtx
        self._chaincode_dir = chaincode
        self._config_sdk = configsdk
        if all([topology, configsdk, chaincode, configtx]):
            logger.info("FabricEvents configs OK")
            logger.info("configsdk %s, chaincode %s, configtx %s", configsdk,
                        chaincode, configtx)

            self.config_gopath()
            self.build_cli()
            return True
        else:
            logger.info("FabricEvents configs FAILED")
            return False

    def config_gopath(self):
        gopath = os.path.normpath(os.path.join(self._chaincode_dir))
        os.environ['GOPATH'] = os.path.abspath(gopath)

    def build_cli(self):
        pathlist = [
            os.environ["HOME"] + "/hl/bin",
        ]  # TODO set dynamic config path for configtxgen bin
        os.environ["PATH"] += os.pathsep + os.pathsep.join(pathlist)

        self._cli = Client(net_profile=self._config_sdk)
        logger.debug("FABRIC_CONFIG: Fabric Orgs %s",
                     self._cli.organizations.keys())
        logger.debug("FABRIC_CONFIG: Fabric Peers %s", self._cli.peers.keys())
        logger.debug("FABRIC_CONFIG: Fabric Orderers %s",
                     self._cli.orderers.keys())
        logger.debug("FABRIC_CONFIG: Fabric CAs %s", self._cli.CAs.keys())
        logger.info("Fabric Client SDK CLI Started")

    def schedule(self, events):
        for _id, event in events.items():
            event_category = event.get("category")

            if event_category == "fabric":
                when = event.get("when")
                logger.info("Calling at %s event %s", when,
                            event.get("params").get("action"))
                self.call_at(when, event.get("params"))

    def sched_time(self, when):
        if type(when) is float:
            if when >= time.time():
                rel_when = when - time.time()
            else:
                rel_when = 0
        elif type(when) is str:
            if when == "now":
                rel_when = 0
            else:
                rel_when = float(when)
        else:
            rel_when = 0
        return rel_when

    def call_at(self, when, event):
        rel_when = self.sched_time(when)
        self._async_loop.call_later(max(0, rel_when), self.call, event)

    def run_task(self, task):
        try:
            self._async_loop.create_task(task)
        except asyncio.CancelledError:
            pass
        except Exception:
            logger.error("Exception in Fabric Event Task", exc_info=True)

    def call(self, event):
        task = None
        action = event.get("action")

        if action == "info_network":
            task = self.event_info_network(event)
        if action == "create_channel":
            task = self.event_create_channel(event)
        if action == "join_channel":
            task = self.event_join_channel(event)
        if action == "info_channels":
            task = self.event_info_channels(event)
        if action == "info_channel":
            task = self.event_info_channel(event)
        if action == "info_channel_config":
            task = self.event_info_channel_config(event)
        if action == "info_channel_chaincodes":
            task = self.event_info_channel_chaincodes(event)
        if action == "chaincode_install":
            task = self.event_chaincode_install(event)
        if action == "chaincode_instantiate":
            task = self.event_chaincode_instantiate(event)
        if action == "chaincode_invoke":
            task = self.event_chaincode_invoke(event)
        if action == "chaincode_query":
            task = self.event_chaincode_query(event)

        if task:
            self.run_task(task)
        else:
            logger.info("Unkown task for event %s", event)

    async def event_create_channel(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        orderer_name = ev.get("orderer")
        channel = ev.get("channel")
        profile = ev.get("profile")

        orderer = self._topo.get("orderers").get(orderer_name)
        orderer_fqdn = orderer.get("orderer_fqdn")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        if org_fqdn and orderer_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.channel_create(
                orderer=orderer_fqdn,
                channel_name=channel,
                requestor=org_user,
                config_yaml=self._configtx_dir,
                channel_profile=profile)
            logger.info("FABRIC_EV:create_channel: Create channel response %s",
                        response)
            return response

        logger.info("unknown orderer %s and org %s", orderer_name, org_name)
        return None

    async def event_join_channel(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        orderer_name = ev.get("orderer")
        channel = ev.get("channel")
        peers_names = ev.get("peers")

        orderer = self._topo.get("orderers").get(orderer_name)
        orderer_fqdn = orderer.get("orderer_fqdn")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        if org_fqdn and orderer_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            peers = org.get("peers")
            peers_fqdn = [
                peer.get("peer_fqdn") for peer in peers.values()
                if peer.get("name") in peers_names
            ]

            response = await self._cli.channel_join(requestor=org_user,
                                                    channel_name=channel,
                                                    peers=peers_fqdn,
                                                    orderer=orderer_fqdn)
            logger.info("FABRIC_EV:join_channel: Join channel response %s",
                        response)
            return response

        logger.info("unknown orderer %s and org %s", orderer_name, org_name)
        return None

    async def event_info_channel(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        channel = ev.get("channel")
        peers_names = ev.get("peers")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.query_info(requestor=org_user,
                                                  channel_name=channel,
                                                  peers=peers_fqdn,
                                                  decode=True)
            logger.info("FABRIC_EV:info_channel: Info channel response %s",
                        response)
            return response

        logger.info("unknown org %s and/org peers %s", org_name, peers_names)
        return None

    async def event_info_channels(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.query_channels(requestor=org_user,
                                                      peers=peers_fqdn,
                                                      decode=True)
            logger.info("FABRIC_EV:info_channels: Info channels response %s",
                        response)
            return response

        logger.info("unknown org %s and/org peers %s", org_name, peers_names)
        return None

    async def event_info_channel_config(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        channel = ev.get("channel")
        peers_names = ev.get("peers")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.get_channel_config(requestor=org_user,
                                                          channel_name=channel,
                                                          peers=peers_fqdn,
                                                          decode=True)
            logger.info(
                "FABRIC_EV:info_channel_config: Info channel config response %s",
                response)
            return response

        logger.info("unknown org %s and/org peers %s", org_name, peers_names)
        return None

    async def event_info_channel_chaincodes(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.query_installed_chaincodes(
                requestor=org_user, peers=peers_fqdn, decode=True)
            logger.info(
                "FABRIC_EV:info_channel_chaincodes: Info channel chaincodes response %s",
                response)
            return response

        logger.info("unknown org %s and/org peers %s", org_name, peers_names)
        return None

    async def event_info_network(self, ev):
        orderer_name = ev.get("orderer")
        orderer = self._topo.get("orderers").get(orderer_name)
        orderer_fqdn = orderer.get("orderer_fqdn")

        if orderer_fqdn:
            response = self._cli.get_net_info('organizations', orderer_fqdn,
                                              'mspid')
            logger.info("FABRIC_EV:info_network: Info network response %s",
                        response)
            return response

        logger.info("unknown orderer %s", orderer_name)
        return None

    async def event_chaincode_install(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")
        chaincode_name = ev.get("chaincode_name")
        chaincode_path = ev.get("chaincode_path")
        chaincode_version = ev.get("chaincode_version")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.chaincode_install(
                requestor=org_user,
                peers=peers_fqdn,
                cc_path=chaincode_path,
                cc_name=chaincode_name,
                cc_version=chaincode_version)
            logger.info(
                "FABRIC_EV:chaincode_install: Chaincode install response %s",
                response)
            return response

        logger.info("unknown org %s and/or peers %s", org_name, peers_names)
        return None

    async def event_chaincode_instantiate(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")
        channel = ev.get("channel")
        chaincode_args = ev.get("chaincode_args")
        chaincode_name = ev.get("chaincode_name")
        chaincode_version = ev.get("chaincode_version")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.chaincode_instantiate(
                requestor=org_user,
                channel_name=channel,
                peers=peers_fqdn,
                args=chaincode_args,
                cc_name=chaincode_name,
                cc_version=chaincode_version)
            logger.info(
                "FABRIC_EV:chaincode_instantiate: Chaincode instantiate response %s",
                response)
            return response

        logger.info("unknown org %s and/or peers %s", org_name, peers_names)
        return None

    async def event_chaincode_invoke(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")
        channel = ev.get("channel")
        chaincode_args = ev.get("chaincode_args")
        chaincode_name = ev.get("chaincode_name")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.chaincode_invoke(requestor=org_user,
                                                        channel_name=channel,
                                                        peers=peers_fqdn,
                                                        args=chaincode_args,
                                                        cc_name=chaincode_name)
            logger.info(
                "FABRIC_EV:chaincode_invoke: Chaincode invoke response %s",
                response)
            return response

        logger.info("unknown org %s and/or peers %s", org_name, peers_names)
        return None

    async def event_chaincode_query(self, ev):
        org_name = ev.get("org")
        user_name = ev.get("user")
        peers_names = ev.get("peers")
        channel = ev.get("channel")
        chaincode_args = ev.get("chaincode_args")
        chaincode_name = ev.get("chaincode_name")

        org = self._topo.get("orgs").get(org_name)
        org_fqdn = org.get("org_fqdn")

        peers = org.get("peers")
        peers_fqdn = [
            peer.get("peer_fqdn") for peer in peers.values()
            if peer.get("name") in peers_names
        ]

        if org_fqdn and peers_fqdn:
            org_user = self._cli.get_user(org_name=org_fqdn, name=user_name)

            response = await self._cli.chaincode_query(requestor=org_user,
                                                       channel_name=channel,
                                                       peers=peers_fqdn,
                                                       args=chaincode_args,
                                                       cc_name=chaincode_name)
            logger.info(
                "FABRIC_EV:chaincode_query: Chaincode query response %s",
                response)
            return response

        logger.info("unknown org %s and/or peers %s", org_name, peers_names)
        return None
Exemple #20
0
import asyncio
from hfc.fabric import Client

loop = asyncio.get_event_loop()

cli = Client(net_profile="first-network.json")
org1_admin = cli.get_user('Org1MSP', 'Admin')

# Query a chaincode
args = ['a']
# The response should be true if succeed
response = loop.run_until_complete(
    cli.chaincode_query(requestor=org1_admin,
                        channel_name='mychannel',
                        peers=['peer0.org1.example.com'],
                        args=args,
                        cc_name='mycc'))
print(response)
CONNECTION_PROFILE_PATH = 'test/fixtures/network.json'
CONFIG_YAML_PATH = 'test/fixtures/e2e_cli/'
CHAINCODE_PATH = 'test/fixtures/chaincode'

if __name__ == "__main__":
    loop = asyncio.get_event_loop()

    cli = Client(net_profile=CONNECTION_PROFILE_PATH)

    print(cli.organizations)  # orgs in the network
    print(cli.peers)  # peers in the network
    print(cli.orderers)  # orderers in the network
    print(cli.CAs)  # ca nodes in the network, TODO

    # get the admin user from local path
    org1_admin = cli.get_user(org_name='org1.example.com', name='Admin')

    # Create a New Channel, the response should be true if succeed
    response = loop.run_until_complete(
        cli.channel_create(orderer='orderer.example.com',
                           channel_name='businesschannel',
                           requestor=org1_admin,
                           config_yaml=CONFIG_YAML_PATH,
                           channel_profile='TwoOrgsChannel'))
    if response:
        print("Create channel successful")
    else:
        print("Create channel failed")
        print(response)
        exit(-1)
Exemple #22
0
    :author: Jason Liu
"""
from hfc.fabric import Client
import asyncio
import time

loop = asyncio.get_event_loop()
cli = Client(net_profile="./network.json")

print(cli.organizations)  # orgs in the network
print(cli.peers)  # peers in the network
print(cli.orderers)  # orderers in the network
print(cli.CAs)  # ca nodes in the network
cli.new_channel('mychannel')
org1_admin = cli.get_user(org_name='org1.example.com', name='Admin') # get the admin user from local path
args = ["212344", "red", "202", "Jack"]
#args2 = ["GetBlockByTxID", "mychannel", "64caff9786483d0d56f6d7ba738ece33328c2559b7b4093547018bcd22e42986"]
# The response should be true if succeed
response = loop.run_until_complete(cli.query_instantiated_chaincodes(
               requestor=org1_admin,
               channel_name='mychannel',
               peers=['peer0.org1.example.com'],
               decode=True
               ))
"""
# This part is used to check the channel information
response = loop.run_until_complete(cli.query_peers(
               requestor=org1_admin,
               peer='peer0.org1.example.com',
               channel='mychannel',