def teste(): loop = asyncio.get_event_loop() meter_id = "666" measurement = "123" '''instantiate the hyperledger fabric client''' c_hlf = client_fabric(net_profile="ptb-network.json") '''get access to Fabric as Admin user''' admin = c_hlf.get_user('ptb.de', 'Admin') # Query Peer installed chaincodes, make sure the chaincode is installed response = loop.run_until_complete( c_hlf.query_installed_chaincodes(requestor=admin, peers=['peer0.ptb.de'], decode=True)) print(response) '''the Fabric Python SDK do not read the channel configuration, we need to add it mannually''' c_hlf.new_channel('ptb-channel') response = loop.run_until_complete( c_hlf.chaincode_invoke(requestor=admin, channel_name='ptb-channel', peers=['peer0.ptb.de'], args=[meter_id], cc_name='fabmorph', cc_version=cc_version, fcn='queryHistory', cc_pattern=None)) print(response)
def send_transactions(self): """This method implements execution code. It basically collects messages generated randomly and adds these new messages in the ledger. On it transaction, it also collects start and end times, logging them in the statistics vector. Notice that the Fabric invoke chaincode performs a transcation in two steps. First, the transaction is sent to a endorser peer. This call blocks the client (i.e., the client waits by the endorser response until a default timeout). After, the client sends the endorsed transaction to the orderer service, but do not wait by a response anymore. All these steps are encapsulated by the Fabric SDK. """ # creates a loop object to manage async transactions loop = asyncio.new_event_loop() # configures the event loop of the current thread asyncio.set_event_loop(loop) # The function that starts the Fabric SDK does not support concurrency, # so we need the locker to synchronize the multithread access. self.c_lock.acquire(1) # we also creates a control to try again just in case the access to the SDK fails stop = False while not stop: try: # instantiate the Fabric SDK client (ptb-network-tls.json is our network profile) c_hlf = client_fabric(net_profile="ptb-network-tls.json") stop = True except: stop = False # now we can release the locker... self.c_lock.release() # get access to Fabric as Admin user admin = c_hlf.get_user('ptb.de', 'Admin') # the Fabric Python SDK do not read the channel configuration, we need to add it manually c_hlf.new_channel('ptb-channel') # we will change the meter_id within an offset to reduce the probability of key collision id_offset = 0 max_offset = 100 # the thread runs until the main program requests its stop while not self._stopevent.isSet(): try: # generates a random message value between 1 and 99 message = str(random.randint(1, maxrand)) # modify the meter_id value meter_id_temp = str(int(self.meter_id) + id_offset) # test if priv_key is valid if self.priv_key is None: print("Invalid Private Key -- Meter ID: " + meter_id_temp + " Message: " + message) # signs the message using the private key and converts it to base64 encoding signature = priv_key.sign(message.encode(), hashfunc=hashlib.sha256, sigencode=sigencode_der) b64sig = base64.b64encode(signature) # giving the signature feedback print("Continuing with the information...\nmessage:", message, "\nsignature:", b64sig) # take time message to generate statistics start = time.time() # the transaction calls chaincode 'checkSignature'. It uses the meter ID and # signs the message using the private key and converts it to base64 encoding. # inserting the new message. Admin is used. response = loop.run_until_complete( c_hlf.chaincode_invoke(requestor=admin, channel_name='ptb-channel', peers=['peer0.ptb.de'], cc_name='fabpki', cc_version='1.0', fcn='checkSignature', args=[meter_id_temp, str(message), b64sig], cc_pattern=None )) # the signature checking returned... (true or false) print("The signature verification returned:\n", response) # take time message to generate statistics end = time.time() # append statistics to the respective list self.statistics.append([start, end]) else: print("Valid Private Key -- Meter ID: " + meter_id_temp + " Message: " + message) # signs the message using the private key and converts it to base64 encoding signature = priv_key.sign(message.encode(), hashfunc=hashlib.sha256, sigencode=sigencode_der) b64sig = base64.b64encode(signature) # giving the signature feedback print("Continuing with the information...\nmessage:", message, "\nsignature:", b64sig) # take time message to generate statistics start = time.time() # the transaction calls chaincode 'checkSignature'. It uses the meter ID and # signs the message using the private key and converts it to base64 encoding. # inserting the new message. Admin is used. response = loop.run_until_complete( c_hlf.chaincode_invoke(requestor=admin, channel_name='ptb-channel', peers=['peer0.ptb.de'], cc_name='fabpki', cc_version='1.0', fcn='checkSignature', args=[meter_id_temp, str(message), b64sig], cc_pattern=None )) # the signature checking returned... (true or false) print("The signature verification returned:\n", response) # take time message to generate statistics end = time.time() # append statistics to the respective list self.statistics.append([start, end]) # increments id_offset, reseting it when it is equal or greater than max_offset id_offset = (id_offset + 1) % max_offset # each thread generates 1 tsp... so it is time to sleep a little :-) # if not id_offset % 5: time.sleep(1) # so far, so good print("Insertion OK, getting next message...") except: # exceptions probably occur when the transaction fails. In this case, we # need to adjust the id_offset, so the thread has high chances of continue # executing with the next meter ID. id_offset = (id_offset + 1) % max_offset # self.c_lock.release() print("We are having problems with the exceptions...")
def send_transactions(self): """This method implements the thread execution code. It basically collects measurements from a UPCUA server and adds these new measurements to the consumption value in the ledger. If the meter_id has a pair of Paillier keys, it sends a encrypted measurement by invoking insertMeasurement chaincode. Otherwise, it sends a plaintext measurement by invoking insertPlaintextMeasurement chaincode. On it transaction, it collects start and end times, logging them in the statistics vector. Notice that the Fabric chaincode invoke performs a transcation in two steps. First, the transaction is sent to a endorser peer. That call blocks the client (i.e., the client waits by the endorser response until the default timeout). After, the client sends the endorsed transaction to the orderer service, but do not wait by a response anymore. All these steps are encapsulated by the Fabric SDK. """ #The function that starts the Fabric SDK does not support concurrency, # so we need the locker to synchronize the multithread access. c_lock.acquire(1) #instantiate the Fabric SDK client (ptb-network.json is our network profile) c_hlf = client_fabric(net_profile="ptb-network.json") #now we can release the locker... c_lock.release() #instantiate the opcua client c_opcua = client_opcua("opc.tcp://localhost:4840/freeopcua/server/") try: #get access to Fabric as Admin user admin = c_hlf.get_user('ptb.de', 'Admin') #the Fabric Python SDK do not read the channel configuration, we need to add it mannually c_hlf.new_channel('ptb-channel') #connect to the opcua server c_opcua.connect() #opcua client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects root = c_opcua.get_root_node() #print shows what is happening #print("OPC-UA Objects node is: ", root) while not self._stopevent.isSet(): #waits a little (we define our sampling rate) #time.sleep(5) #gets the measurement sample from opcua server sample = root.get_child( ["0:Objects", "2:MyObject", "2:System Load"]) #print shows what is happening #print("Sampled measurement: ", sample.get_value()) #inserts the individual measurement into var param measurement = int(sample.get_value() * 10) #test if pub_key is valid if pub_key is None: #invoke the LR chaincode... print("insertPlainTextMeasurement:(t=" + str(self.id) + ",m=" + str(measurement) + ")") #take time measurement for generating statistics start = time.time() #the transaction calls chaincode 'insertPlainTextMeasurement'. It uses the meter ID for #inserting the new measurement. Admin is used. response = c_hlf.chaincode_invoke( requestor=admin, channel_name='ptb-channel', peer_names=['peer0.ptb.de'], args=[meter_id, str(measurement)], cc_name='fabmorph', cc_version=cc_version, fcn='insertPlainTextMeasurement') #take time measurement for generating statistics end = time.time() #append statistics to the respective list self.statistics.append([start, end]) else: #encrypts measurement using pub_key encrypted = str(pub_key.raw_encrypt(measurement)) #invoke the LR chaincode... print("insertMeasurement:(t=" + str(self.id) + ",m=" + encrypted + ")") #take time measurement for generating statistics start = time.time() #the transaction calls chaincode 'insertMeasurement'. It uses the meter ID for #inserting the new measurement. Admin is used. response = c_hlf.chaincode_invoke( requestor=admin, channel_name='ptb-channel', peer_names=['peer0.ptb.de'], args=[meter_id, encrypted], cc_name='fabmorph', cc_version=cc_version, fcn='insertMeasurement') #take time measurement for generating statistics end = time.time() #append statistics to the respective list self.statistics.append([start, end]) #let's see what we did get... print(response) #so far, so good #print("Insertion OK, getting next measurement...") finally: #only opcua client need to be disconnected c_opcua.disconnect()
def send_transactions(self): """This method implements the thralso ead execution code. It basically collects measurements from a UPCUA server also and adds these new measurements to the consumption value in the ledger. also If the meter_id has a pair of Paillier keys, it sends a encrypted measurement also by invoking insertMeasurement chaincode. Otherwise, it sends a plaintext malso easurement by invoking insertPlaintextMeasurement chaincode. On it transaction, it also collects start and end times, logging them in the statistics vector. Notice that the Fabric invoke chaincode performs a transcation in two steps. First, the transaction is sent to a endorser peer. This call blocks the client (i.e., the client waits by the endorser response until a default timeout). After, the client sends the endorsed transaction to the orderer service, but do not wait by a response anymore. All these steps are encapsulated by the Fabric SDK. """ #The function that starts the Fabric SDK does not support concurrency, # so we need the locker to synchronize the multithread access. self.c_lock.acquire(1) #we also creates a control to try again just in case the access to the SDK fails stop = False while not stop: try: #instantiate the Fabric SDK client (ptb-network.json is our network profile) c_hlf = client_fabric(net_profile="ptb-network.json") stop = True except: stop = False #now we can release the locker... self.c_lock.release() #get access to Fabric as Admin user admin = c_hlf.get_user('ptb.de', 'Admin') #the Fabric Python SDK do not read the channel configuration, we need to add it mannually c_hlf.new_channel('ptb-channel') #we will change the meter_id within an offset to reduce the probability of key collision id_offset = 0 max_offset = 100 encrypted = "" #the thread runs until the main program requests its stop while not self._stopevent.isSet(): try: #generates a random measurement value between 1 and 99 measurement = random.randint(1, maxrand) #modify the meter_id value meter_id_temp = str(int(self.meter_id) + id_offset) #test if pub_key is valid if self.pub_key is None: #invoke the LR chaincode... print("insertPlainTextMeasurement:(t=" + meter_id_temp + ",m=" + str(measurement) + ")") #take time measurement to generate statistics start = time.time() #the transaction calls chaincode 'insertPlainTextMeasurement'. It uses the meter ID for #inserting the new measurement. Admin is used. c_hlf.chaincode_invoke( requestor=admin, channel_name='ptb-channel', peer_names=['peer0.ptb.de'], args=[meter_id_temp, str(measurement)], cc_name='fabmorph', cc_version=cc_version, fcn='insertPlainTextMeasurement', mode=self.mode) #take time measurement to generate statistics end = time.time() #append statistics to the respective list self.statistics.append([start, end]) else: #get previously encrypted value encrypted = encrypted_values[measurement] #invoke the LR chaincode... print("insertMeasurement:(t=" + meter_id_temp + ",m=" + encrypted + ")") #take time measurement to generate statistics start = time.time() #the transaction calls chaincode 'insertMeasurement'. It uses the meter ID for #inserting the new measurement. Admin is used. c_hlf.chaincode_invoke(requestor=admin, channel_name='ptb-channel', peer_names=['peer0.ptb.de'], args=[meter_id_temp, encrypted], cc_name='fabmorph', cc_version=cc_version, fcn='insertMeasurement', mode=self.mode) #take time measurement to generate statistics end = time.time() #append statistics to the respective list self.statistics.append([start, end]) #increments id_offset, reseting it when it is equal or greater than max_offset id_offset = (id_offset + 1) % max_offset #each thread generates 1 tsp... so it is time to sleep a little :-) #if not id_offset % 5: time.sleep(1) #so far, so good #print("Insertion OK, getting next measurement...") except: #exceptions probably occur when the transaction fails. In this case, we #need to adjust the id_offset, so the thread has high chances of continue #executing with the next meter ID. id_offset = (id_offset + 1) % max_offset #self.c_lock.release() print("We are having problems with the exceptions...")
#try to retrieve the public key try: with open(pub_key_file, 'r') as file: pub_key = file.read() except: print("I could not find a valid public key to the meter", meter_id) exit(1) #shows the meter public key print("Continuing with the public key:\n", pub_key) #creates a loop object to manage async transactions loop = asyncio.get_event_loop() #instantiate the hyperledeger fabric client c_hlf = client_fabric(net_profile="ptb-network-tls.json") #get access to Fabric as Admin user admin = c_hlf.get_user('ptb.de', 'Admin') #query peer installed chaincodes, make sure the chaincode is installed print("Checking if the chaincode fabpki is properly installed:") response = loop.run_until_complete( c_hlf.query_installed_chaincodes(requestor=admin, peers=['peer0.ptb.de'])) print(response) #the Fabric Python SDK do not read the channel configuration, we need to add it mannually''' c_hlf.new_channel('ptb-channel') #invoke the chaincode to register the meter
# log(str(traceback.format_exc())) # traceback.print_exc(file=sys.stdout) # print(e) if __name__ == "__main__": #test if the fuction received no parameters if len(sys.argv) != 1: print("Usage only:", sys.argv[0], " ") exit(1) #creates a loop object to manage async transactions loop = asyncio.get_event_loop() #instantiate the hyperledeger fabric client c_hlf = client_fabric(net_profile=(domain + ".json")) #get access to Fabric as Admin user admin = c_hlf.get_user(domain, 'Admin') callpeer = "peer0." + domain #the Fabric Python SDK do not read the channel configuration, we need to add it mannually c_hlf.new_channel(channel_name) #open the AIS file arquivo_log = open('saida_ais.out.txt', 'r') estacao = ("pi") linhas = arquivo_log.readlines()