async def get_block_info(org_name: str, user_name: str, user_password: str, channel_name: str = constants.channel_name) -> str: """ Fetches the blockchain state of the given channel Args: org_name: Name of the submitting user's organization user_name: Username of the submitter user_password: Password of the submitting user channel_name: Name of the channel on which to connect client Returns: String of blockchain info """ # Setup a HF network client hf_client = Client(net_profile=constants.config_path) # Connect to the given channel hf_client.new_channel(channel_name) # Gather information about the network network_info = hf_client.get_net_info() # For queries, we only need a single peer # Here we will randomly select one from our org peers = network_info['organizations'][org_name]['peers'] random_peer = random.choice(peers) user = enroll_user(hf_client, org_name, user_name, user_password) response = await hf_client.query_info(requestor=user, channel_name=channel_name, peers=[random_peer]) return str(response)
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)
async def invoke(org_name: str, user_name: str, user_password: str, channel_name: str, function: str, args: List[str]) -> str: """ Submits a blockchain transaction invocation to all the peers in the network. Args: org_name: Name of the submitting user's organization user_name: Username of the submitter user_password: Password of the submitting user channel_name: Name of the channel on which to connect client function: Name of the chaincode function to invoke args: A list of string arguments passed to the chaincode Returns: Response string from the *first* peer that responded with confirmation of the execution. """ # Setup a HF network client hf_client = Client(net_profile=constants.config_path) # Connect to the given channel hf_client.new_channel(channel_name) # Gather information about the network network_info = hf_client.get_net_info() # Invocations require read/write sets from as many peers # as specified in the endorsement policy. Here we will # go ahead and request endorsement from ALL peers. # If your policy requires only a subset, you may wish to # alter this section peers = [] for org in network_info['organizations'].keys(): if 'peers' in network_info['organizations'][org]: for peer in network_info['organizations'][org]['peers']: peers.append(peer) # Enroll the user that will be invoking the query user = enroll_user(hf_client, org_name, user_name, user_password) # Submit the query to the peers and await a response response = await hf_client.chaincode_invoke( requestor=user, channel_name=channel_name, peers=peers, fcn=function, args=args, cc_name=constants.chaincode_name, transient_map=None, # optional, for private data wait_for_event= True, # for being sure chaincode invocation has been commited in the ledger, default is on tx event ) if not response: raise ValueError( f'Failure to invoke chaincode function {function} with response: {response}' ) return response
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)
async def get_instantiated_chaincodes( org_name: str, user_name: str, user_password: str, channel_name: str = constants.channel_name) -> List[Dict[str, str]]: """ Fetches the blockchain state of the given channel Args: org_name: Name of the submitting user's organization user_name: Username of the submitter user_password: Password of the submitting user channel_name: Name of the channel on which to connect client Returns: List of instantiated chaincodes, each of which contains: 'Name': Chaincode name, 'Version': Chaincode version, 'Path': GOPATH relative chaincode location """ # Setup a HF network client hf_client = Client(net_profile=constants.config_path) # Connect to the given channel hf_client.new_channel(channel_name) # Gather information about the network network_info = hf_client.get_net_info() # For queries, we only need a single peer # Here we will randomly select one from our org peers = network_info['organizations'][org_name]['peers'] random_peer = random.choice(peers) user = enroll_user(hf_client, org_name, user_name, user_password) response = await hf_client.query_instantiated_chaincodes( requestor=user, channel_name=channel_name, peers=[random_peer]) chaincodes = [] for chaincode in response[0].chaincodes: code = { 'Name': chaincode.name, 'Version': chaincode.version, 'Path': chaincode.path } chaincodes.append(code) return chaincodes
async def query(org_name: str, user_name: str, user_password: str, channel_name: str, function: str, args: List[str]) -> str: """ Submits a ledger query to a single peer within the specified org. Note that queries will NOT submit any changes to the ledger state, even if an invocation query function is invoked. Args: org_name: Name of the submitting user's organization user_name: Username of the submitter user_password: Password of the submitting user channel_name: Name of the channel on which to connect client function: Name of the chaincode function to invoke args: A list of string arguments passed to the chaincode Returns: Response string from the given peer """ # Setup a HF network client hf_client = Client(net_profile=constants.config_path) # Connect to the given channel hf_client.new_channel(channel_name) # Gather information about the network network_info = hf_client.get_net_info() # For queries, we only need a single peer # Here we will randomly select one from our org peers = network_info['organizations'][org_name]['peers'] random_peer = random.choice(peers) # Enroll the user that will be invoking the query user = enroll_user(hf_client, org_name, user_name, user_password) # Submit the query to the selected peer and await a response response = await hf_client.chaincode_query( requestor=user, channel_name=channel_name, fcn=function, peers=[random_peer], args=args, cc_name=constants.chaincode_name) if not response: raise ValueError( f'Failure to query chaincode function {function} with response: {response}' ) return response
def wait(): with get_event_loop() as loop: channel_name = LEDGER['channel_name'] chaincode_name = LEDGER['chaincode_name'] peer = LEDGER['peer'] peer_port = peer["port"][os.environ.get('BACKEND_PEER_PORT', 'external')] client = Client() channel = client.new_channel(channel_name) target_peer = Peer(name=peer['name']) requestor_config = LEDGER['client'] target_peer.init_with_bundle({ 'url': f'{peer["host"]}:{peer_port}', 'grpcOptions': peer['grpcOptions'], 'tlsCACerts': { 'path': peer['tlsCACerts'] }, 'clientKey': { 'path': peer['clientKey'] }, 'clientCert': { 'path': peer['clientCert'] }, }) try: # can fail requestor = create_user( name=requestor_config['name'] + '_events', org=requestor_config['org'], state_store=FileKeyValueStore(requestor_config['state_store']), msp_id=requestor_config['msp_id'], key_path=glob.glob(requestor_config['key_path'])[0], cert_path=requestor_config['cert_path']) except BaseException: pass else: channel_event_hub = channel.newChannelEventHub( target_peer, requestor) # use chaincode event # uncomment this line if you want to replay blocks from the beginning for debugging purposes # stream = channel_event_hub.connect(start=0, filtered=False) stream = channel_event_hub.connect(filtered=False) channel_event_hub.registerChaincodeEvent(chaincode_name, 'tuples-updated', onEvent=on_tuples) loop.run_until_complete(stream)
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
async def register_user(org_name: str, request: constants.RegisterUserRequest) -> str: """ Registers a user to the Org's Fabric CA Server Args: org_name: Organization's name request: RegisterUserRequest object containing registration information Returns: Pre-generated user secret """ # Create/Open a wallet on a temp path including the org name # Org name must be included, otherwise usernames must be unique # over all orgs wallet_path = os.path.join(os.getcwd(), 'tmp', 'hfc-kvs', org_name) cred_wallet = wallet.FileSystenWallet(path=wallet_path) # [sic] # Setup a HF network client hf_client = Client(net_profile=constants.config_path) hf_client.new_channel(constants.channel_name) # Extract CA info network_info = hf_client.get_net_info() org_info = network_info['organizations'][org_name] ca_name = org_info['certificateAuthorities'][0] ca_info = network_info['certificateAuthorities'][ca_name] # if user already exists, pull ID from storage if cred_wallet.exists(request.user_name): return None casvc = ca_service(target=ca_info['url']) admin_enrollment = casvc.enroll(request.admin_user_name, request.admin_password) secret = admin_enrollment.register(enrollmentID=request.user_name, enrollmentSecret=request.user_password, role=request.role, affiliation=request.affiliation, attrs=[dict(x) for x in request.attrs]) return secret
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
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 ))
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('firstchannel') # Install Example Chaincode to Peers # The response should be true if succeed responses = loop.run_until_complete( cli.chaincode_install(requestor=org1_admin, peers=[ 'peer0.org1.dz', 'peer1.org1.dz', 'peer2.org1.dz', 'peer3.org1.dz' ], cc_path='chaincodes', cc_name='first_chaincode', cc_version='v1.0')) print(responses)
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 }]
# your policy policy = { "identities": [{ "role": { "name": "member", "mspId": "PeerOrg1MSP" } }], "policy": { "1-of": [{ "signed-by": 0 }] }, } cli.new_channel("firstchannel") cli.new_channel("secondchannel") # Creating the two channels response = loop.run_until_complete( cli.channel_create( orderer="orderer1.org1.dz", channel_name="firstchannel", requestor=org1_admin, config_yaml="/*****************YOUR_PATH*****************/", channel_profile="firstchannel", )) response = loop.run_until_complete( cli.channel_create( orderer="orderer1.org1.dz",
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 response = cli.get_channel(name="businesschannel") print("Channel named `businesschannel`: ", response) # previously created channel must be declared with new_channel() for future using response = cli.new_channel(name="businesschannel") print("New add channel: ", response) response = cli.get_channel(name="businesschannel") print("Channel named `businesschannel`: ", response) # query channel info of a given channel named "businesschannel" response = loop.run_until_complete( cli.query_info(requestor=org1_admin, channel_name="businesschannel", peers=['peer0.org1.example.com'])) print("Channels: ", response) # Get channel config response = loop.run_until_complete( cli.get_channel_config(requestor=org1_admin, channel_name='businesschannel',
def get_hfc_client(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) client = Client() # Add peer from backend ledger config file peer = Peer(name=LEDGER['peer']['name']) peer.init_with_bundle({ 'url': f'{LEDGER["peer"]["host"]}:{PEER_PORT}', 'grpcOptions': LEDGER['peer']['grpcOptions'], 'tlsCACerts': { 'path': LEDGER['peer']['tlsCACerts'] }, 'clientKey': { 'path': LEDGER['peer']['clientKey'] }, 'clientCert': { 'path': LEDGER['peer']['clientCert'] }, }) client._peers[LEDGER['peer']['name']] = peer # Check peer has joined channel response = loop.run_until_complete( client.query_channels(requestor=LEDGER['requestor'], peers=[peer], decode=True)) channels = [ch.channel_id for ch in response.channels] if not LEDGER['channel_name'] in channels: raise Exception( f'Peer has not joined channel: {LEDGER["channel_name"]}') channel = client.new_channel(LEDGER['channel_name']) # Check chaincode is instantiated in the channel responses = loop.run_until_complete( client.query_instantiated_chaincodes( requestor=LEDGER['requestor'], channel_name=LEDGER['channel_name'], peers=[peer], decode=True)) chaincodes = [cc.name for resp in responses for cc in resp.chaincodes] if not LEDGER['chaincode_name'] in chaincodes: raise Exception( f'Chaincode : {LEDGER["chaincode_name"]}' f' is not instantiated in the channel : {LEDGER["channel_name"]}') # Discover orderers and peers from channel discovery results = loop.run_until_complete( channel._discovery(LEDGER['requestor'], peer, config=True, local=False, interests=[{ 'chaincodes': [{ 'name': LEDGER['chaincode_name'] }] }])) results = deserialize_discovery(results) update_client_with_discovery(client, results) return loop, client
def wait(channel_name): def on_channel_event(cc_event, block_number, tx_id, tx_status): on_event(channel_name, cc_event, block_number, tx_id, tx_status) with get_event_loop() as loop: client = Client() channel = client.new_channel(channel_name) target_peer = Peer(name=settings.LEDGER_PEER_NAME) target_peer.init_with_bundle({ 'url': f'{settings.LEDGER_PEER_HOST}:{settings.LEDGER_PEER_PORT}', 'grpcOptions': ledger_grpc_options(settings.LEDGER_PEER_HOST), 'tlsCACerts': { 'path': settings.LEDGER_PEER_TLS_CA_CERTS }, 'clientKey': { 'path': settings.LEDGER_PEER_TLS_CLIENT_KEY }, 'clientCert': { 'path': settings.LEDGER_PEER_TLS_CLIENT_CERT }, }) try: # can fail requestor = create_user(name=f'{settings.LEDGER_USER_NAME}_events', org=settings.ORG_NAME, state_store=FileKeyValueStore( settings.LEDGER_CLIENT_STATE_STORE), msp_id=settings.LEDGER_MSP_ID, key_path=glob.glob( settings.LEDGER_CLIENT_KEY_PATH)[0], cert_path=settings.LEDGER_CLIENT_CERT_PATH) except BaseException: pass else: # Note: # We do a loop to connect to the channel event hub because grpc may disconnect and create an exception # Since we're in a django app of backend, an exception here will not crash the server (if the "ready" # method has already returned "true"). # It makes it difficult to reconnect automatically because we need to kill the server # to trigger the connexion. # So we catch this exception (RPC error) and retry to connect to the event loop. while True: # use chaincode event channel_event_hub = channel.newChannelEventHub( target_peer, requestor) try: # We want to replay blocks from the beginning (start=0) if channel event hub was disconnected during # events emission stream = channel_event_hub.connect(start=0, filtered=False) channel_event_hub.registerChaincodeEvent( settings.LEDGER_CHANNELS[channel_name]['chaincode'] ['name'], 'chaincode-updates', onEvent=on_channel_event) logger.info( f'Connect to Channel Event Hub ({channel_name})') loop.run_until_complete(stream) except Exception as e: logger.error( f'Channel Event Hub failed for {channel_name} ({type(e)}): {e} re-connecting in 5s' ) time.sleep(5)
from hfc.fabric.transaction.tx_proposal_request import create_tx_prop_req, CC_INVOKE, CC_TYPE_NODE, CC_INSTANTIATE, CC_INSTALL, TXProposalRequest loop = asyncio.get_event_loop() cli = Client(net_profile="connection-profile.json") # NlClient = cli.get_user('netherlands.nl', 'user1Nl') fs_wallet = wallet.FileSystenWallet( "./tmp/hfc-kvs") # Opens wallet at ./tmp/hfc-kvs user1Nl = fs_wallet.create_user( "user1Nl", "Netherlands", "NetherlandsMSP" ) # Returns an instance of the user object with the newly created credentials # Make the client know there is a channel in the network cli.new_channel('common') # Invoke a chaincode args = [] # The response should be true if succeed response = loop.run_until_complete( cli.chaincode_invoke( requestor=user1Nl, channel_name='common', peers=['peer0.netherlands.nl'], args=args, cc_name='access-chaincode', cc_type=CC_TYPE_NODE, wait_for_event_timeout=3000, transient_map=None, # optional, for private data
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('channel1') # 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) print("gopath", gopath) # The response should be true if succeed responses = loop.run_until_complete( cli.chaincode_install(requestor=org1_admin, peers=['peer0.org1.example.com'], cc_path='github.com/usecase_cc', cc_name='usecase_cc', cc_version='v1.0'))
import asyncio from hfc.fabric import Client import os import json loop = asyncio.get_event_loop() dir_path = os.path.dirname(os.path.abspath(__file__)) cli = Client(net_profile=os.path.join(dir_path, "example_server_network.json")) # Make the client know there is a channel in the network cli.new_channel('mychannel') class OperateChaincode(): """ Initialize common parameters: requestor, channel_name, peers, cc_name requestor: user role who issue the request channel_name: the name of the channel to send tx proposal peers: list of peer name and/or peer to install cc_name: chaincode name """ def __init__(self, requestor, channel_name, peers, cc_name): self.requestor = requestor self.channel_name = channel_name self.peers = peers self.cc_name = cc_name #Call python SDK for query def query(self, args): return loop.run_until_complete( cli.chaincode_query(requestor=self.requestor, channel_name=self.channel_name,
import asyncio import random from hfc.fabric import Client import middleware.constants as constants import middleware.operations as operations from middleware.access_utils import enroll_user org_name = 'appdevorg.beatchain.com' 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,
def _get_hfc(channel_name): global user loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if not user: with user_lock: # Only call `create_user` once in the lifetime of the application. # Calling `create_user` twice breaks thread-safety (bug in fabric-sdk-py) user = create_user(name=settings.LEDGER_USER_NAME, org=settings.ORG_NAME, state_store=FileKeyValueStore( settings.LEDGER_CLIENT_STATE_STORE), msp_id=settings.LEDGER_MSP_ID, key_path=glob.glob( settings.LEDGER_CLIENT_KEY_PATH)[0], cert_path=settings.LEDGER_CLIENT_CERT_PATH) client = Client() # Add peer from backend ledger config file peer = Peer(name=settings.LEDGER_PEER_NAME) peer.init_with_bundle({ 'url': f'{settings.LEDGER_PEER_HOST}:{settings.LEDGER_PEER_PORT}', 'grpcOptions': ledger_grpc_options(settings.LEDGER_PEER_HOST), 'tlsCACerts': { 'path': settings.LEDGER_PEER_TLS_CA_CERTS }, 'clientKey': { 'path': settings.LEDGER_PEER_TLS_CLIENT_KEY }, 'clientCert': { 'path': settings.LEDGER_PEER_TLS_CLIENT_CERT }, }) client._peers[settings.LEDGER_PEER_NAME] = peer # Check peer has joined channel response = loop.run_until_complete( client.query_channels(requestor=user, peers=[peer], decode=True)) channels = [ch.channel_id for ch in response.channels] if channel_name not in channels: raise Exception(f'Peer has not joined channel: {channel_name}') channel = client.new_channel(channel_name) # This part is commented because `query_committed_chaincodes` is not implemented in # the last version of fabric-sdk-py # chaincode_name = settings.LEDGER_CHANNELS[channel_name]['chaincode']['name'] # /!\ New chaincode lifecycle. # Check chaincode is committed in the channel # responses = loop.run_until_complete( # client.query_committed_chaincodes( # requestor=user, # channel_name=channel_name, # peers=[peer], # decode=True # ) # ) # chaincodes = [cc.name # for resp in responses # for cc in resp.chaincode_definitions] # if chaincode_name not in chaincodes: # raise Exception(f'Chaincode : {chaincode_name}' # f' is not committed in the channel : {channel_name}') # Discover orderers and peers from channel discovery results = loop.run_until_complete( channel._discovery(user, peer, config=True, local=False, interests=[{ 'chaincodes': [{ 'name': "_lifecycle" }] }])) results = _deserialize_discovery(results) _validate_channels(channel_name, results) _update_client_with_discovery(client, results) return loop, client, user
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
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')
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'))
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