def block_listener(host): iroha_api = iroha.Iroha("admin@test") net = IrohaGrpc(host) query = iroha_api.blocks_query() ic.sign_query(query, ADMIN_PRIVATE_KEY) print("Listeting blocks") for block in net.send_blocks_stream_query(query): BLOCKS.add(block.block_response.block.block_v1.payload.height) hashes = block.block_response.block.block_v1.payload.rejected_transactions_hashes txs = block.block_response.block.block_v1.payload.transactions for tx in txs: hashes.append(ascii_hash(tx)) for hash in hashes: if hash not in TXS.keys(): continue start_time = TXS[hash] COMMITTED.add(hash) del TXS[hash] total_time = int((time.time() - start_time) * 1000) try: events.request_success.fire(request_type="grpc", name='send_tx_wait', response_time=total_time, response_length=0, tx_hash=hash, sent=start_time, committed=time.time()) except Exception as e: print(e)
def __init__(self, creator_account, private_key, iroha_host): self.creator_account = creator_account self.iroha = Iroha(creator_account) self.ic = ic self.permissions = iroha_primitive self.user_private_key = private_key self.net = IrohaGrpc(iroha_host, timeout=60)
def __init__(self, sawmills, l): self.domain_name = "trade" self.admin_private_key = ADMIN_PRIVATE_KEY self.iroha = Iroha(ADMIN_ACCOUNT_ID) self.net = IrohaGrpc('{}:{}'.format(IROHA_HOST_ADDR, IROHA_PORT)) self.sawmills = sawmills self.woods = list(map(config.to_lower_case_only_letters, config.woods)) # uses as assets self.commands = [ self.iroha.command('CreateDomain', domain_id=self.domain_name, default_role='user'), *[ self.iroha.command('CreateAsset', asset_name=wood, domain_id=self.domain_name, precision=0) for wood in self.woods ] ] tx = IrohaCrypto.sign_transaction( self.iroha.transaction(self.commands), self.admin_private_key) print(self.send_transaction_and_log_status(tx)) self.get_admin_details() tx = self.iroha.transaction([ self.iroha.command('AddAssetQuantity', asset_id=f'{wood}#{self.domain_name}', amount=str(10000 // l)) for wood in self.woods ]) IrohaCrypto.sign_transaction(tx, self.admin_private_key) print(self.send_transaction_and_log_status(tx)) self.get_admin_details()
def __init__(self, creator_account, iroha_host_addr, iroha_port): self.creator_account = creator_account self.iroha = Iroha(creator_account) self.permissions = iroha_primitive #change to local encrypted storage self.private_key_file = creator_account + '.priv' self.user_private_key = open(self.private_key_file, 'rb+').read() self.net = IrohaGrpc(f'{iroha_host_addr}:{iroha_port}', timeout=30)
def send_query_print_status_and_return_result(iroha_host_addr, iroha_port, transaction): hex_hash = binascii.hexlify(ic.hash(transaction)) print(f"Transaction hash = {hex_hash}") net = IrohaGrpc(f"{iroha_host_addr}:{iroha_port}", timeout=60) response = net.send_query(transaction) data = MessageToJson(response) return data
def __init__(self, private_key, name, domain, ip, public_info): self.public_key = IrohaCrypto.derive_public_key(private_key) self.name = name self.domain = domain self.domain.name = domain.name ip_address = ip + ':50051' self.network = IrohaGrpc(ip_address) if domain.name == 'public': self.public_info = public_info
def __init__(self, user, port="50051", host="localhost"): self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '192.168.88.202') #andrey # self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '192.168.88.62') #sergey # self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', host) self.IROHA_PORT = os.getenv('IROHA_PORT', port) self.admin_private_key = 'f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70' self.iroha = Iroha(user.Name) self.net = IrohaGrpc( '{}:{}'.format(self.IROHA_HOST_ADDR, self.IROHA_PORT), 1000)
def __init__(self): # self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '192.168.88.62') self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '192.168.88.202') # self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', 'localhost') self.IROHA_PORT = os.getenv('IROHA_PORT', '50051') self.admin_private_key = 'f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70' self.iroha = Iroha('admin@test') self.net = IrohaGrpc('{}:{}'.format(self.IROHA_HOST_ADDR, self.IROHA_PORT)) self.txAmount = 0 self.CreateDomainAsset() self.AddAdminCoin()
def __init__(self, socketio, sessionid, iroha_dic, socketIoValidator): self.moduleName = "IrohaConnector" self.iroha_dic = iroha_dic self.socketIoValidator = socketIoValidator self.net = IrohaGrpc('localhost:50051') self.iroha = Iroha('admin@test') self.admin_priv_key = 'f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70' #Private Key of user decided at previous line self.latestNumOfBlocks = 0 self.isMonitoring = False print(f"##{self.moduleName}.__init__")
def send_transaction_print_status_and_return_result(iroha_host_addr, iroha_port, transaction): net = IrohaGrpc(f"{iroha_host_addr}:{iroha_port}", timeout=60) hex_hash = binascii.hexlify(ic.hash(transaction)) print("Transaction hash = {}, \n creator = {}".format( hex_hash, transaction.payload.reduced_payload.creator_account_id)) net.send_tx(transaction) tx_result = [] for status in net.tx_status_stream(transaction): tx_result.append(status) print(status) tx_result.append(hex_hash) return tx_result
class TransactionBuilder(object): def __init__(self, admin_account, admin_private_key, port): self.admin_account = admin_account self.admin_private_key = admin_private_key self.port = port self.iroha = Iroha(self.admin_account) self.net = IrohaGrpc(self.port) def __send_transaction_and_print_status(self, transaction): hex_hash = binascii.hexlify(IrohaCrypto.hash(transaction)) print('Transaction hash = {}, creator = {}'.format( hex_hash, transaction.payload.reduced_payload.creator_account_id)) self.net.send_tx(transaction) for status in self.net.tx_status_stream(transaction): print(status) for status in self.net.tx_status_stream(transaction): if status == ('COMMITTED', 5, 0): return "COMMITTED" def create_client(self, client_name): user_private_key = IrohaCrypto.private_key() user_public_key = IrohaCrypto.derive_public_key(user_private_key) commands = [ self.iroha.command('CreateAccount', account_name=client_name, domain_id="test", public_key=user_public_key), ] transaction = self.iroha.transaction(commands) IrohaCrypto.sign_transaction(transaction, self.admin_private_key) self.__send_transaction_and_print_status(transaction) tx = self.iroha.transaction([ self.iroha.command('GrantPermission', account_id='admin@test', permission=primitive_pb2.can_set_my_account_detail) ]) IrohaCrypto.sign_transaction(tx, user_private_key) if self.__send_transaction_and_print_status(transaction) == "COMMITTED": return "Your key: " + user_private_key, 201 else: return 'Internal Error', 500 def add_coin_to_client(self, number, private_key): tx = self.iroha.transaction([ self.iroha.command('AddAssetQuantity', asset_id='coin#test', amount=str(number) + '.00') ]) IrohaCrypto.sign_transaction(tx, private_key) if self.__send_transaction_and_print_status(tx) == "COMMITTED": return "Added " + str(number), 201 else: return 'Internal Error', 500
def __getattribute__(self, name): func = IrohaGrpc.__getattribute__(self, name) if hasattr(func, '__call__'): def wrapper(*args, **kwargs): start_time = time.time() try: result = func(*args, **kwargs) except grpc.RpcError as e: total_time = int((time.time() - start_time) * 1000) events.request_failure.fire(request_type="grpc", name=name, response_time=total_time, exception=e) else: total_time = int((time.time() - start_time) * 1000) events.request_success.fire(request_type="grpc", name=name, response_time=total_time, response_length=0) # In this example, I've hardcoded response_length=0. If we would want the response length to be # reported correctly in the statistics, we would probably need to hook in at a lower level return result return wrapper else: return func
def set_detail_to_node(sender, receiver, private_key, detail_key, detail_value, domain, ip): """ This function can be use when the User object is no available. The sender must have permission to write in the details of the receiver. In federated learning the details are in JSON format and contains the address (location) where the weight is stored if the weight is small enough it can be embedded to the block if needed) :Example: >>> set_detail_to_node('David', 'Juan', 'private key of david', 'detail key of Juan', 'detail value', 'domain' \ 'ip') :param str sender: Name of the node sending the information :param str receiver: Name of the node receiving the information :param str private_key: Private key of the user :param str detail_key: Name of the detail we want to set :param str detail_value: Value of the detail :param str domain: Name of the domain :param str ip: address for connecting to the BSMD """ account = sender + '@' + domain iroha = Iroha(account) account_id = receiver + '@' + domain ip_address = ip + ':50051' network = IrohaGrpc(ip_address) tx = iroha.transaction([ iroha.command('SetAccountDetail', account_id=account_id, key=detail_key, value=detail_value) ]) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx, network)
class TestIroha: def __init__(self, user, port="50051", host="localhost"): self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '192.168.88.202') #andrey # self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '192.168.88.62') #sergey # self.IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', host) self.IROHA_PORT = os.getenv('IROHA_PORT', port) self.admin_private_key = 'f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70' self.iroha = Iroha(user.Name) self.net = IrohaGrpc( '{}:{}'.format(self.IROHA_HOST_ADDR, self.IROHA_PORT), 1000) def SendTx(self, transaction): hex_hash = binascii.hexlify(IrohaCrypto.hash(transaction)) print('Transaction hash = {}, creator = {}'.format( hex_hash, transaction.payload.reduced_payload.creator_account_id)) self.net.send_tx(transaction) exit_status = list() # for status in self.net.tx_status_stream(transaction): # print(status) return exit_status def SignTx(self, from_user, to_user): tx = self.iroha.transaction([ self.iroha.command('TransferAsset', src_account_id=from_user.Name, dest_account_id=to_user.Name, asset_id='coin#domain', description='sending', amount='0.01') ]) IrohaCrypto.sign_transaction(tx, from_user.PrivKey) transactions.append(tx) def GetTxsStatus(self): txsChecked = 0 print("Starting checking") for transaction in transactions: txsChecked += 1 for status in self.net.tx_status_stream(transaction): txsStatus.append(status) if txsChecked % 10 == 0: print(txsChecked, " transaction checked")
async def get_account_assets(self, event): event_node = event.get("node") event_user = event.get("user") event_host, event_port = self.get_node_settings(event_node) event_user_account, event_user_priv = self.get_user_settings( event_user) if event_host and event_port and event_user_account and event_user_priv: event_account_id = event.get("account_id") try: logger.debug( f"Calling event {event.get('action')} - host:port {event_host}:{event_port}" ) iroha = Iroha(event_user_account) net = IrohaGrpc("{}:{}".format(event_host, event_port)) query = iroha.query( "GetAccountAssets", account_id=event_account_id, ) IrohaCrypto.sign_query(query, event_user_priv) response = net.send_query(query) data = response.account_assets_response.account_assets for asset in data: logger.debug( "Event {}: asset id = {}, balance = {}".format( event.get("action"), asset.asset_id, asset.balance)) except Exception as ex: logger.debug( f"Could not make event transaction {event.get('action')} - exception {ex}" ) else: logger.debug( f"Event {event.get('action')} error - missing fields event_host, event_port, event_user_account, event_user_priv" ) logger.debug( f"Check if event {event.get('action')} contains correct node {event.get('node')} and user {event.get('user')}" )
def send_transaction_return_result(iroha_host_addr, iroha_port, transaction): net = IrohaGrpc(f"{iroha_host_addr}:{iroha_port}", timeout=60) hex_hash = binascii.hexlify(ic.hash(transaction)) tx_result = {} try: net.send_tx(transaction) tx_status = [] for status in net.tx_status_stream(transaction): tx_status.append(status) tx_result = { "tx_hash": hex_hash, "tx_statuses": tx_status, "tx_result": tx_status[-1][0], } except Exception as error: print(error) tx_result = { "tx_hash": hex_hash, "tx_statuses": [], "tx_result": "REJECTED", } return tx_result
def get_a_detail_written_by(name, writer, private_key, detail_key, domain, ip): """ This function can be use when the User object is no available. Consult a details of the node writen by other node :Example: >>> juan_detail = get_a_detail_written_by('David', 'Juan', 'private key of david', 'detail_key of Juan', 'domain', \ 'ip') >>> print(juan_detail) { "nodeA@domain":{ "Age":"35" } :param str name: Name of the node consulting the information :param str writer: Name of the node who write the detail :param str private_key: Private key of the user :param str detail_key: Name of the detail we want to consult :param str domain: Name of the domain :param str ip: Address for connecting to the BSMD :return: returns the detail writen by "the writer" :rtype: json """ account_id = name + '@' + domain user_id = writer + '@' + domain iroha = Iroha(account_id) ip_address = ip + ':50051' network = IrohaGrpc(ip_address) query = iroha.query('GetAccountDetail', account_id=account_id, key=detail_key, writer=user_id) IrohaCrypto.sign_query(query, private_key) response = network.send_query(query) data = response.account_detail_response print('Account id = {}, details = {}'.format(account_id, data.detail)) return data.detail
def get_account(account: str, port: str): """Health check function""" # setup of iroha client address host = "127.0.0.1" net = IrohaGrpc(f"{host}:{port}") query = iroha_user.query("GetAccount", account_id=account) try: with open('/opt/iroha_data/[email protected]', 'r') as file: admin_private_key = file.read().strip() except Exception as e: print("Unable to read admin private key! Reason:", e) sys.exit(1) IrohaCrypto.sign_query(query, admin_private_key) response = net.send_query(query) # health check passes when response contains value of account parameter if response.account_response.account.account_id == user_account: print("Success!") sys.exit(0) # health check fails when response does not contain "admin@test" else: print( f"Successful connection, but account '{account}' does not exist!") sys.exit(1)
async def transfer_asset(self, event): event_node = event.get("node") event_user = event.get("user") event_host, event_port = self.get_node_settings(event_node) event_user_account, event_user_priv = self.get_user_settings( event_user) if event_host and event_port and event_user_account and event_user_priv: event_asset_id = event.get("asset_id") event_asset_amount = event.get("asset_amount") event_src_account_id = event.get("src_account_id") event_dest_account_id = event.get("dest_account_id") event_description = event.get("description") try: logger.debug( f"Calling event {event.get('action')} - host:port {event_host}:{event_port}" ) iroha = Iroha(event_user_account) net = IrohaGrpc("{}:{}".format(event_host, event_port)) commands = [ iroha.command( "TransferAsset", src_account_id=event_src_account_id, dest_account_id=event_dest_account_id, asset_id=event_asset_id, description=event_description, amount=event_asset_amount, ), ] tx = IrohaCrypto.sign_transaction(iroha.transaction(commands), event_user_priv) coro_send_transaction = self.send_transaction( event.get("action"), net, tx) asyncio.create_task(coro_send_transaction) except Exception as ex: logger.debug( f"Could not make event transaction {event.get('action')} - exception {ex}" ) else: logger.debug( f"Event {event.get('action')} error - missing fields event_host, event_port, event_user_account, event_user_priv" ) logger.debug( f"Check if event {event.get('action')} contains correct node {event.get('node')} and user {event.get('user')}" )
async def grant_permission(self, event): event_node = event.get("node") event_user = event.get("user") event_host, event_port = self.get_node_settings(event_node) event_user_account, event_user_priv = self.get_user_settings( event_user) if event_host and event_port and event_user_account and event_user_priv: event_account_id = event.get("account_id") event_permission = event.get("permission") event_account = event.get("account") try: logger.debug( f"Calling event {event.get('action')} - host:port {event_host}:{event_port}" ) iroha = Iroha(event_user_account) net = IrohaGrpc("{}:{}".format(event_host, event_port)) commands = [ iroha.command( "GrantPermission", account_id=event_account_id, permission=IrohaEvents.PERMISSIONS.get( event_permission, None), ), ] tx = IrohaCrypto.sign_transaction( iroha.transaction(commands, creator_account=event_account), event_user_priv, ) coro_send_transaction = self.send_transaction( event.get("action"), net, tx) asyncio.create_task(coro_send_transaction) except Exception as ex: logger.debug( f"Could not make event transaction {event.get('action')} - exception {ex}" ) else: logger.debug( f"Event {event.get('action')} error - missing fields event_host, event_port, event_user_account, event_user_priv" ) logger.debug( f"Check if event {event.get('action')} contains correct node {event.get('node')} and user {event.get('user')}" )
class IrohaClient(): def __init__(self, creator_account, iroha_host_addr, iroha_port): self.creator_account = creator_account self.iroha = Iroha(creator_account) self.permissions = iroha_primitive #change to local encrypted storage self.private_key_file = creator_account + '.priv' self.user_private_key = open(self.private_key_file, 'rb+').read() self.net = IrohaGrpc(f'{iroha_host_addr}:{iroha_port}', timeout=30) def send_transaction_and_print_status(self, transaction): hex_hash = binascii.hexlify(ic.hash(transaction)) print('Transaction hash = {}, creator = {}'.format( hex_hash, transaction.payload.reduced_payload.creator_account_id)) self.net.send_tx(transaction) for status in self.net.tx_status_stream(transaction): print(status) return hex_hash def send_batch_and_print_status(self, transactions): self.net.send_txs(transactions) for tx in transactions: hex_hash = binascii.hexlify(ic.hash(tx)) print('\t' + '-' * 20) print('Transaction hash = {}, creator = {}'.format( hex_hash, tx.payload.reduced_payload.creator_account_id)) for status in self.net.tx_status_stream(tx): print(status) def send_batch_and_return_status(self, *transactions): self.net.send_txs(transactions) for tx in transactions: hex_hash = binascii.hexlify(ic.hash(tx)) print('\t' + '-' * 20) print('Transaction hash = {}, creator = {}'.format( hex_hash, tx.payload.reduced_payload.creator_account_id)) tx_result = [] for status in self.net.tx_status_stream(transactions): tx_result.append(status) return tx_result def send_transaction_print_status_and_return_result(self, transaction): hex_hash = binascii.hexlify(ic.hash(transaction)) print('Transaction hash = {}, \n creator = {}'.format( hex_hash, transaction.payload.reduced_payload.creator_account_id)) self.net.send_tx(transaction) tx_result = [] for status in self.net.tx_status_stream(transaction): tx_result.append(status) print(status) tx_result.append(hex_hash) return tx_result def sign_and_submit_admin_tx(self, transction): new_tx = self.iroha.transaction([]) tx = ParseDict(transction, new_tx) print(tx) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def check_pending_txs(self): query = self.iroha.query('GetPendingTransactions') ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToJson(response) return data def get_tx_history(self, account_id, total): """ List total number of tx details for specified user@domain """ query = self.iroha.query('GetTransactions', account_id=account_id, page_size=total) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToDict(response) return data #Accounts def get_account_assets(self, account_id): query = self.iroha.query('GetAccountAssets', account_id=account_id) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToJson(response) return data def get_asset_info(self, account_id, asset_id): query = self.iroha.query('GetAssetInfo', asset_id=asset_id) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToJson(response) return data def get_acc_tx_history(self, account_id, total): """ List total number of tx details for specified user@domain """ query = self.iroha.query('GetAccountTransactions', account_id=account_id, page_size=total) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToDict(response) return data def get_asset_tx_history(self, account_id, total): """ List Asset tx details for specified user@domain """ query = self.iroha.query('GetAccountAssetTransactions', account_id=account_id, page_size=total) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToDict(response) return data def get_roles(self): """ List Roles """ query = self.iroha.query('GetRoles') ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToDict(response) return data def get_role_permissions(self, role_id): """ List Role Permissions for specified Role """ query = self.iroha.query('GetRolePermissions', role_id=role_id) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToDict(response) return data def stream_blocks(self): """ Start incomming stream for new blocks """ #add height query = self.iroha.blocks_query() ic.sign_query(query, self.user_private_key) for block in self.net.send_blocks_stream_query(query): pprint('The next block arrived: {}'.format(MessageToDict(block)), indent=1) def get_signatories(self, account_id): """ List signatories by public key for specified user@domain """ query = self.iroha.query('GetSignatories', account_id=account_id) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToDict(response) return data def get_account(self, account_id): """ List Account user@domain """ query = self.iroha.query('GetAccount', account_id=account_id) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = MessageToDict(response) return data def get_account_details(self, account_id, writer=None, key=None): """ List Account details for user@domain """ query = self.iroha.query('GetAccountDetail', account_id=account_id, writer=writer, key=key) ic.sign_query(query, self.user_private_key) response = self.net.send_query(query) data = json.loads(response.account_detail_response.detail) return data def create_new_account(self, account_name, domain, public_key): """ register new user """ tx = self.iroha.transaction([ self.iroha.command('CreateAccount', account_name=account_name, domain_id=domain, public_key=public_key) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def set_account_detail(self, account_id, key, value): tx = self.iroha.transaction([ self.iroha.command('SetAccountDetail', account_id=account_id, key=key, value=value) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def create_domain(self, domain_id, default_role): """ register non existing/new domain on network """ tx = self.iroha.transaction([ self.iroha.command('CreateDomain', domain_id=domain_id, default_role='user') ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def grant_account_write_permission(self, account_id): """ grand permission write permission for AccountDetails """ tx = self.iroha.transaction([ self.iroha.command( 'GrantPermission', account_id=account_id, permission=self.permissions.can_set_my_account_detail) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def grant_account_read_permission(self, account_id): tx = self.iroha.transaction([ self.iroha.command( 'GrantPermission', account_id=account_id, permission=self.permissions.can_get_my_acc_detail) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) #add signatory #remove signatory #find peer and remove peer has been added in v1.1 def add_peer(self, ip_address, peer_key): peer = self.permissions.Peer() peer.address = ip_address peer.peer_key = peer_key tx = self.iroha.transaction([self.iroha.command('AddPeer', peer=peer)]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def grant_asset_tx_history_permission(self, account_id): tx = self.iroha.transaction([ self.iroha.command('GrantPermission', account_id=account_id, permission=can_get_my_acc_ast_txs) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def grant_account_tx_history_permission(self, account_id): tx = self.iroha.transaction([ self.iroha.command('GrantPermission', account_id=account_id, permission=can_get_my_acc_txs) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def create_new_asset(self, asset, domain, precision): tx = self.iroha.transaction([ self.iroha.command('CreateAsset', asset_name=asset, domain_id=domain, precision=precision) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def transfer_asset(self, account_id, recipient, asset_id, description, qty): tx = self.iroha.transaction([ self.iroha.command('TransferAsset', src_account_id=account_id, dest_account_id=recipient, asset_id=asset_id, description=description, amount=qty) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def add_asset_qty(self, asset_id, qty): """ Add asset supply """ tx = self.iroha.transaction([ self.iroha.command('AddAssetQuantity', asset_id=asset_id, amount=qty) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx) def subtract_asset_qty(self, asset_id, qty): """ Subtract asset supply """ tx = self.iroha.transaction([ self.iroha.command('SubtractAssetQuantity', asset_id=asset_id, amount=qty) ]) ic.sign_transaction(tx, self.user_private_key) self.send_transaction_print_status_and_return_result(tx)
import sys import binascii from pprint import * #import click import os from iroha import IrohaCrypto as ic from iroha import Iroha, IrohaGrpc from iroha.primitive_pb2 import * import json from google.protobuf.json_format import MessageToJson, MessageToDict IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '127.0.0.1') IROHA_PORT = os.getenv('IROHA_PORT', '50051') net = IrohaGrpc('{}:{}'.format(IROHA_HOST_ADDR, IROHA_PORT), timeout=30) creator_account = os.getenv('IROHA_ACCOUNT_ID', default='admin@test') iroha = Iroha(creator_account) private_key_file = creator_account + '.priv' user_private_key = open(private_key_file, 'rb+').read() def generate_keypair(): private_key = ic.private_key() public_key = ic.derive_public_key(private_key) return public_key, private_key def save_keys_to_file(account_id): private_key = ic.private_key() public_key = ic.derive_public_key(private_key) private_key_file = account_id + '.priv' public_key_file = account_id + '.pub'
if sys.version_info[0] < 3: raise Exception('Python 3 or more updated version is required.') # Iroha peer 1 IROHA_HOST_ADDR_1 = os.getenv('IROHA_HOST_ADDR_1', '172.29.101.121') IROHA_PORT_1 = os.getenv('IROHA_PORT_1', '50051') # Iroha peer 2 IROHA_HOST_ADDR_2 = os.getenv('IROHA_HOST_ADDR_2', '172.29.101.122') IROHA_PORT_2 = os.getenv('IROHA_PORT_2', '50052') # Iroha peer 3 IROHA_HOST_ADDR_3 = os.getenv('IROHA_HOST_ADDR_2', '172.29.101.123') IROHA_PORT_3 = os.getenv('IROHA_PORT_3', '50053') # IrohaGrpc net for peer 1, 2, 3 net_1 = IrohaGrpc('{}:{}'.format(IROHA_HOST_ADDR_1, IROHA_PORT_1)) net_2 = IrohaGrpc('{}:{}'.format(IROHA_HOST_ADDR_2, IROHA_PORT_2)) net_3 = IrohaGrpc('{}:{}'.format(IROHA_HOST_ADDR_3, IROHA_PORT_3)) # Admin Account loading with Admin's private key ADMIN_PRIVATE_KEY = os.getenv( 'ADMIN_PRIVATE_KEY', 'f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70') # Admin's account ADMIN_ACCOUNT_ID = os.getenv('ADMIN_ACCOUNT_ID', 'admin@test') iroha_admin = Iroha(ADMIN_ACCOUNT_ID) # Satoshi's crypto material generation satoshi_private_key = IrohaCrypto.private_key() satoshi_public_key = IrohaCrypto.derive_public_key(satoshi_private_key) # Satoshi's account
format='%(message)s', level=logging.INFO) # Slave node slave_private_key = '7a3a8efe3fbfac57af55e8d2a4b20e27b19444c4d240924dd1bd57701a5a0731' slave_public_key = IrohaCrypto.derive_public_key(slave_private_key) slave_name = 'slave1' domain_id = 'choice' slave_account_id = slave_name + '@' + domain_id iroha_slave = Iroha('slave1@choice') # set the ip of one node in the iroha blockchain asset_id = 'choicecoin#choice' ################################## # Set corresponding IP network = IrohaGrpc('18.216.92.47:50051') ################################## def model(beta_car, beta_cost, beta_tt): """ This function run the model using private observations :param beta_car: beta parameter of the car :param beta_cost: beta parameter of the cost :param beta_tt: beta parameter of the travel time :return: """ models = [] with open('data_one.csv') as file: reader = csv.reader(file) next(reader)
import integration_helpers if sys.version_info[0] < 3: raise Exception("Python 3 or a more recent version is required.") # Here is the information about the environment and admin account information: IROHA_HOST_ADDR = os.getenv("IROHA_HOST_ADDR", "127.0.0.1") IROHA_PORT = os.getenv("IROHA_PORT", "50051") ADMIN_ACCOUNT_ID = os.getenv("ADMIN_ACCOUNT_ID", "admin@test") ADMIN_PRIVATE_KEY = os.getenv( "ADMIN_PRIVATE_KEY", "f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70", ) iroha = Iroha(ADMIN_ACCOUNT_ID) net = IrohaGrpc("{}:{}".format(IROHA_HOST_ADDR, IROHA_PORT)) test_private_key = IrohaCrypto.private_key() test_public_key = IrohaCrypto.derive_public_key(test_private_key).decode( "utf-8") @integration_helpers.trace def create_contract(): bytecode = "608060405234801561001057600080fd5b5073a6abc17819738299b3b2c1ce46d55c74f04e290c6000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061081d806100746000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c8063094d1a1614610046578063d4e804ab14610076578063f5496cc514610094575b600080fd5b610060600480360381019061005b919061042e565b6100c4565b60405161006d91906105a1565b60405180910390f35b61007e610233565b60405161008b9190610586565b60405180910390f35b6100ae60048036038101906100a9919061042e565b610257565b6040516100bb91906105a1565b60405180910390f35b6060600083836040516024016100db9291906105c3565b6040516020818303038152906040527f094d1a16000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050905060008060008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16836040516101a2919061056f565b600060405180830381855af49150503d80600081146101dd576040519150601f19603f3d011682016040523d82523d6000602084013e6101e2565b606091505b509150915081610227576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161021e906105fa565b60405180910390fd5b80935050505092915050565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60606000838360405160240161026e9291906105c3565b6040516020818303038152906040527ff5496cc5000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050905060008060008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1683604051610335919061056f565b600060405180830381855af49150503d8060008114610370576040519150601f19603f3d011682016040523d82523d6000602084013e610375565b606091505b5091509150816103ba576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016103b1906105fa565b60405180910390fd5b80935050505092915050565b60006103d96103d48461063f565b61061a565b9050828152602081018484840111156103f157600080fd5b6103fc8482856106e5565b509392505050565b600082601f83011261041557600080fd5b81356104258482602086016103c6565b91505092915050565b6000806040838503121561044157600080fd5b600083013567ffffffffffffffff81111561045b57600080fd5b61046785828601610404565b925050602083013567ffffffffffffffff81111561048457600080fd5b61049085828601610404565b9150509250929050565b6104a3816106b3565b82525050565b60006104b482610670565b6104be8185610686565b93506104ce8185602086016106f4565b6104d781610787565b840191505092915050565b60006104ed82610670565b6104f78185610697565b93506105078185602086016106f4565b80840191505092915050565b600061051e8261067b565b61052881856106a2565b93506105388185602086016106f4565b61054181610787565b840191505092915050565b60006105596027836106a2565b915061056482610798565b604082019050919050565b600061057b82846104e2565b915081905092915050565b600060208201905061059b600083018461049a565b92915050565b600060208201905081810360008301526105bb81846104a9565b905092915050565b600060408201905081810360008301526105dd8185610513565b905081810360208301526105f18184610513565b90509392505050565b600060208201905081810360008301526106138161054c565b9050919050565b6000610624610635565b90506106308282610727565b919050565b6000604051905090565b600067ffffffffffffffff82111561065a57610659610758565b5b61066382610787565b9050602081019050919050565b600081519050919050565b600081519050919050565b600082825260208201905092915050565b600081905092915050565b600082825260208201905092915050565b60006106be826106c5565b9050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b82818337600083830152505050565b60005b838110156107125780820151818401526020810190506106f7565b83811115610721576000848401525b50505050565b61073082610787565b810181811067ffffffffffffffff8211171561074f5761074e610758565b5b80604052505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6000601f19601f8301169050919050565b7f4572726f722063616c6c696e67207365727669636520636f6e7472616374206660008201527f756e6374696f6e0000000000000000000000000000000000000000000000000060208201525056fea2646970667358221220f8ebb31c12325b11cf148ed6694599909f6786dc0811e364f572a6b5098f59dc64736f6c63430008040033" """Bytecode was generated using remix editor https://remix.ethereum.org/ from file role.sol. """ tx = iroha.transaction( [iroha.command("CallEngine", caller=ADMIN_ACCOUNT_ID, input=bytecode)]) IrohaCrypto.sign_transaction(tx, ADMIN_PRIVATE_KEY) net.send_tx(tx) hex_hash = binascii.hexlify(IrohaCrypto.hash(tx))
root_public_key = "313a07e6384776ed95447710d15e59148473ccfc052a681317a72a69f2a49910" bob_account = "bob@sorakh" bob_private_key = "14266dfe9f3905a014cb2ed7c251eebf8ff88651a17584be8acfde25281a7d67" bob_public_key = "0801713ce823ad9d25245f14c90873c3863dee84dd70bf2ec8edf0a99cb1cbd5" alice_account = "alice@sorakh" alice_private_key = "ca65c781d9cf93632576c90d3323956cc2a05f75521511418c3d84f468b2aa38" alice_public_key = "8892e1667a9b779e3a554296a9bfafcc8e800ec16c7d48512c74e851677d4a70" # Avialable Assets usd_asset = "usd#sorakh" khr_asset = "khr#sorakh" # Initialize Iroha Network Connection network = IrohaGrpc("127.0.0.1:50052") # Get Asset Information def get_asset_info(account_id): iroha = Iroha(root_account) query = iroha.query("GetAccountAssets", account_id = account_id) IrohaCrypto.sign_query(query, root_private_key) response = network.send_query(query) return response # Transfer Asset def transfer_asset(initializer, private_key, sender, receiver, currency, amount): iroha = Iroha(initializer) command = iroha.transaction( [ iroha.command(
# imports import sqlite3, yaml from db_functions import * # own script import pandas as pd from iroha import Iroha, IrohaGrpc, IrohaCrypto from iroha.primitive_pb2 import can_set_my_account_detail import hashlib, binascii import warnings, re # configuration (per Iroha example guide for now) admin_private_key = 'f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70' # user_private_key = IrohaCrypto.private_key() # user_public_key = IrohaCrypto.derive_public_key(user_private_key) iroha = Iroha('admin@test') net = IrohaGrpc() dbcfg = yaml.load(open('../config/db_config.yaml'), Loader=yaml.SafeLoader) dltcfg = yaml.load(open('dltcfg.yaml'), Loader=yaml.SafeLoader) conn = sqlite3.connect('../config/{}'.format(dbcfg['DB_NAME'])) UID_PAT = '[a-z0-9]+@[a-z0-9]+' LEDGER_ASSET = '{}#{}'.format(dltcfg['ASSET_NAME'], dltcfg['IROHA_DOMAIN']) # functions def get_iroha_user_info(userid): ''' Queries Iroha blockchain for info about userid. ''' qry = iroha.query('GetAccount', account_id=userid)
# Federated learner configuration ################################## BATCH_SIZE = 16 EPOCHS = 3 INTERVAL_STEPS = 1 # Steps between averages WAIT_TIME = 3 # How many seconds to wait for new workers to connect CHIEF_PUBLIC_IP = 'localhost:7777' # Public IP of the chief worker CHIEF_PRIVATE_IP = 'localhost:7777' # Private IP of the chief worker # BSMD configuration ###################### asset_id = 'fedcoin#federated' # Replace localhost with an IP address of a node running the blockchain network = IrohaGrpc('18.191.46.178:50051') domain_id = 'federated' admin_private_key = 'f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70' iroha = Iroha('admin@test') default_role = 'user' asset_name = 'fedcoin' asset_precision = 2 # chief node ###################### chief_private_key = '054e294d86bedf9a43cf20542cade6e57addfd4294a276042be4ba83c73f8d9e' chief_public_key = IrohaCrypto.derive_public_key(chief_private_key) chief_name = 'chief' chief_account_id = chief_name + '@' + domain_id iroha_chief = Iroha('chief@federated')
# import binascii from iroha import IrohaCrypto as ic from iroha import Iroha, IrohaGrpc from iroha.primitive_pb2 import can_set_my_account_detail, can_transfer_my_assets, can_set_my_quorum import os import sys if sys.version_info[0] < 3: raise Exception('Python 3 or a more recent version is required.') IROHA_HOST_ADDR = os.getenv('IROHA_HOST_ADDR', '127.0.0.1') IROHA_PORT = os.getenv('IROHA_PORT', '50051') net = IrohaGrpc('{}:{}'.format(IROHA_HOST_ADDR, IROHA_PORT)) # Define necessary constants we will need throughout the app ADMIN_ACCOUNT_ID = os.getenv('ADMIN_ACCOUNT_ID', 'admin@test') ADMIN_PRIVATE_KEY = os.getenv( 'ADMIN_PRIVATE_KEY', '72a9eb49c0cd469ed64f653e33ffc6dde475a6b9fd8be615086bce7c44b5a8f8') ADMIN_PUBLIC_KEY = ic.derive_public_key(ADMIN_PRIVATE_KEY) GAME_ACCOUNT_ID = 'match@games' GAME_PRIVATE_KEY = '9b965ebbd194dc538735310740e6667cb8222811c5e4e8e917a6fbe77deeb6dc' GAME_PUBLIC_KEY = ic.derive_public_key(GAME_PRIVATE_KEY) ALICE_ACCOUNT_ID = 'alice@games' ALICE_PRIVATE_KEY = '7384819f00d820e291f0dc9f1fce827d9f94ad508bf5252fb310916465b94f17'
def __init__(self, creator_account_details): self.creator_account_details = creator_account_details self.iroha = Iroha( f"{self.creator_account_details.gov_id}@afyamkononi") self.net = IrohaGrpc(f"{self.IROHA_HOST_ADDR}:{self.IROHA_PORT}")