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 create_domain(self, domain, private_key): """ Creates a domain for personal use. You can create a domain for a particular process, e.g., Federated Learning :Example: >>> import json >>> from utils.administrator import Domain >>> x = { "age": 30, "city": "New York" } >>> account_information = json.dumps(x) >>> domain = Domain('name', 'default_role') >>> user = User('private_key', 'My Name', 'My domain', '123.456.789', account_information) >>> user.create_domain(domain, 'private_key') :param Domain domain: domain to be created :param str private_key: key to sign the transaction """ account_id = self.name + '@' + self.domain.name iroha = Iroha(account_id) tx = iroha.transaction( [iroha.command('CreateDomain', domain_id=domain.name, default_role=domain.default_role)]) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx, self.network)
def create_account(self, private_key): """ Create a personal account in the BSMD. In the public domain all your public information is automatically populated :Example: >>> import json >>> from utils.administrator import Domain >>> x = { "age": 30, "city": "New York" } >>> account_information = json.dumps(x) >>> public = Domain('public', 'default_role') >>> user = User('private_key','David', public, '123.456.789', account_information) >>> user.create_account('private_key') :param str private_key: The private key of the user """ account_id = self.name + '@' + self.domain.name iroha = Iroha(account_id) tx = iroha.transaction( [iroha.command('CreateAccount', account_name=self.name, domain_id=self.domain, public_key=self.public_key)]) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx, self.network) if self.domain == 'public': self.set_detail('public', self.public_info, private_key)
def revoke_access_set_details_to(self, user, private_key): """ Revoke permission to a node to set details on your identification :Example: >>> import json >>> from utils.administrator import Domain >>> x = { "age": 30, "city": "New York" } >>> account_information = json.dumps(x) >>> x = { "age": 34, "city": "Mexico" } >>> account_information_juan = json.dumps(x) >>> domain = Domain('name', 'default_role') >>> user = User('private_key','David',domain, account_information) >>> juan = User('private_key_juan','Juan',domain, account_information_juan) >>> user.revoke_access_set_details_to(juan, 'private_key') :param User user: User you want to revoke permissions to set details on your behalf :param str private_key: Key to sign the transaction """ my_id_account = self.name + '@' + self.domain.name grant_account_id = user.name + '@' + user.domain iroha = Iroha(my_id_account) tx = iroha.transaction([ iroha.command('RevokePermission', account_id=grant_account_id, permission=can_set_my_account_detail) ], creator_account=my_id_account) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx, self.network)
def set_detail_to(self, user, detail_key, detail_value, private_key): """ Set a detail to a node. The details can be stored in JSON format with limit of 4096 characters per detail. You must have the permission from the node to set information on his identification :Example: >>> import json >>> from utils.administrator import Domain >>> x = { "age": 30, "city": "New York" } >>> account_information = json.dumps(x) >>> x = { "age": 34, "city": "Mexico" } >>> account_information_juan = json.dumps(x) >>> domain = Domain('name', 'default_role') >>> user = User('private_key','David',domain, account_information) >>> juan = User('private_key_juan','Juan',domain, account_information_juan) >>> user.set_detail_to(juan, 'Job', 'Bartender', 'private_key') :param User user: user you want to set the details :param str detail_key: Name of the detail we want to set :param str detail_value: Value of the detail :param str private_key: key to sign the transaction """ account = self.name + '@' + self.domain.name iroha = Iroha(account) account_id = user.name + '@' + user.domain 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, self.network)
def set_detail(self, detail_key, detail_value, private_key): """ Set a detail in my account. The details can be stored in JSON format with limit of 4096 characters per detail :Example: >>> import json >>> from utils.administrator import Domain >>> x = { "gender": 30, "address": "123 Tennis" } >>> account_information = json.dumps(x) >>> domain = Domain('name', 'default_role') >>> user = User('private_key','David', domain, account_information) >>> user.set_detail('personal information', account_information, 'private_key') :param str detail_key: Name of the detail we want to set :param json detail_value: Value of the detail :param str private_key: Key to sign the transaction """ account_id = self.name + '@' + self.domain.name iroha = Iroha(account_id) 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, self.network)
def transfer_assets(domain, name, private_key, to_name, asset_name, quantity, description): """ Transfer assets from one account to another :param domain: (str) name of the domain from where the node is sending the assets :param name: (str) name of the node who is sending the assets :param private_key: (str) pk of the the sender :param to_name: (str) name of the node receiving the assets :param asset_name: (str) name of the asset to be transferred :param quantity: (float) Number of assets we want to transfer :param description: (str) Small message to the receiver of assets :return: Example: transfer_assets('individuals','Dante', 'key', 'Toro', 'coin', '2', 'Shut up and take my money') """ account_id = name + '@' + domain iroha = Iroha(account_id) destination_account = to_name + '@' + domain asset_id = asset_name + '#' + domain tx = iroha.transaction([ iroha.command('TransferAsset', src_account_id=account_id, dest_account_id=destination_account, asset_id=asset_id, description=description, amount=quantity) ]) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx)
class Trade: def __init__(self, account_name, domain, ledger): self.account_name = account_name self.domain = domain self.full_name = f"{self.account_name}@{self.domain}" self.__private_key = IrohaCrypto.private_key() self.public_key = IrohaCrypto.derive_public_key(self.__private_key) self.iroha = Iroha(self.full_name) self.ledger = ledger def get_woods_balance(self): query = self.iroha.query('GetAccountAssets', account_id=self.full_name) IrohaCrypto.sign_query(query, self.__private_key) response = self.ledger.net.send_query(query) data = response.account_assets_response.account_assets return {asset.asset_id.split('#')[0]: asset.balance for asset in data} def transfer_wood(self, name_to, wood, amount): reciever = f"{name_to}@{self.domain}" tx = self.iroha.transaction([ self.ledger.iroha.command( "TransferAsset", src_account_id=self.full_name, dest_account_id=reciever, asset_id=f"{wood}#{self.domain}", description="transfer", amount=str(amount), ) ]) IrohaCrypto.sign_transaction(tx, self.__private_key) return self.ledger.send_transaction_and_log_status(tx)
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)
def transfer_asset(initializer, private_key, sender, receiver, currency, amount): iroha = Iroha(initializer) command = iroha.transaction( [ iroha.command( 'TransferAsset', src_account_id = sender, dest_account_id = receiver, asset_id = currency, amount = amount ) ] ) IrohaCrypto.sign_transaction(command, private_key) network.send_tx(command) # TEST: =============================================================== # Get Asset Information: Account[BOB] # print(get_asset_info(bob_account)) # Transfer Asset: Sender[BOB], Receiver[ROOT] # transfer_asset( # initializer = bob_account, # private_key = bob_private_key, # sender = bob_account, # receiver = root_account, # currency = usd_asset, # amount = "10" # )
def configure_game_account(): game_iroha = Iroha(GAME_ACCOUNT_ID) game_cmds = [ game_iroha.command('AddSignatory', account_id=GAME_ACCOUNT_ID, public_key=ADMIN_PUBLIC_KEY), game_iroha.command('AddSignatory', account_id=GAME_ACCOUNT_ID, public_key=ALICE_PUBLIC_KEY), game_iroha.command('AddSignatory', account_id=GAME_ACCOUNT_ID, public_key=BOB_PUBLIC_KEY), game_iroha.command('GrantPermission', account_id='admin@test', permission=can_set_my_account_detail), game_iroha.command('GrantPermission', account_id='admin@test', permission=can_set_my_quorum), game_iroha.command('GrantPermission', account_id='alice@games', permission=can_set_my_account_detail), game_iroha.command('GrantPermission', account_id='alice@games', permission=can_transfer_my_assets), game_iroha.command('GrantPermission', account_id='bob@games', permission=can_set_my_account_detail), game_iroha.command('GrantPermission', account_id='bob@games', permission=can_transfer_my_assets) ] game_tx = game_iroha.transaction(game_cmds) ic.sign_transaction(game_tx, GAME_PRIVATE_KEY) send_transaction_and_print_status(game_tx)
def set_detail_to_node(domain, name, private_key, to_domain, to_name, detail_key, detail_value): """ Set the details of a node. The details can be stored in JSON format with limit of 4096 characters per detail :param domain: (str) domain of the signer :param name: (str) name signer :param private_key: (str) Private key of the signer :param to_domain: (str) domain of the receptor :param to_name: (str) name of the receptor :param detail_key: (str) Name of the detail we want to set :param detail_value: (str) Value of the detail :return: null: Usage example: set_detail('vehicle'),'Ford fiesta', 'key', 'age', '33') """ account = name + '@' + domain iroha = Iroha(account) account_id = to_name + '@' + to_domain 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)
def make_move(account_id, privateKey, new_state): iroha = Iroha(account_id) cmds = [ iroha.command('SetAccountDetail', account_id=GAME_ACCOUNT_ID, key='state', value=new_state) ] tx = iroha.transaction(cmds, creator_account=GAME_ACCOUNT_ID, quorum=2) ic.sign_transaction(tx, privateKey) send_transaction_and_print_status(tx)
def setup_group_account(): iroha = Iroha(group['account']) cmds = [ iroha.command('AddSignatory', account_id=group['account'], public_key=ADMIN_PUBLIC_KEY), iroha.command('AddSignatory', account_id=group['account'], public_key=alice['public_key']), iroha.command('AddSignatory', account_id=group['account'], public_key=bob['public_key']), iroha.command('GrantPermission', account_id='admin@test', permission=can_set_my_quorum), ] tx = iroha.transaction(cmds) IrohaCrypto.sign_transaction(tx, group['private_key']) send_transaction_and_print_status(tx)
def transfer_coin_from_group(dest_id, asset_id, amount, creator_id, creator_private_key): """ Transfer from the group account to another account. This transaction requires 2 sigs to proceed. After the creator has signed, it will be pending. """ src_account_id = group['account'] iroha2 = Iroha(creator_id) tx = iroha2.transaction([ iroha2.command('TransferAsset', src_account_id=src_account_id, dest_account_id=dest_id, asset_id=asset_id, description='transfer', amount=amount) ], creator_account=src_account_id, quorum=2) IrohaCrypto.sign_transaction(tx, creator_private_key) send_transaction_and_print_status(tx)
def submit_json_tx(self, account_id: str, transaction): iroha = Iroha(account_id) new_tx = iroha.transaction([]) iroha_host_addr = "127.0.0.1" iroha_port = "50051" try: transaction = ParseDict(transaction, new_tx) print(transaction) result = self.send_transaction_return_result( iroha_host_addr, iroha_port, transaction) return result except Exception as e: print(e)
def configure_players_accounts(): alice_iroha = Iroha('alice@games') alice_cmds = [ alice_iroha.command('SetAccountDetail', account_id='alice@games', key='symbol', value='X') ] alice_tx = alice_iroha.transaction(alice_cmds) ic.sign_transaction(alice_tx, ALICE_PRIVATE_KEY) send_transaction_and_print_status(alice_tx) bob_iroha = Iroha('bob@games') bob_cmds = [ bob_iroha.command('SetAccountDetail', account_id='bob@games', key='symbol', value='O') ] bob_tx = bob_iroha.transaction(bob_cmds) ic.sign_transaction(bob_tx, BOB_PRIVATE_KEY) send_transaction_and_print_status(bob_tx)
def send_tx(self): iroha = Iroha('admin@test') tx = iroha.transaction([ iroha.command('TransferAsset', src_account_id='admin@test', dest_account_id='test@test', asset_id='coin#test', amount='0.01', description=HOSTNAME) ]) ic.sign_transaction(tx, ADMIN_PRIVATE_KEY) self.client.send_tx_await(tx)
def create_account(self, private_key): """ Create a broker account in the BSMD. Brokers are automatically created in the public domain. This function works in two steps #. The broker account in created in the public domain #. Set the public details of the broker :Example: >>> import json >>> from admin.administrator import Domain >>> x = { "address": "123 Street, City", "type": "broker" } >>> public_info = json.dumps(x) >>> broker = Broker('private_key','broker', '123.456.789', public_info) >>> broker.create_account('private_key') :param str private_key: The private key of the user """ account_id = self.name + '@public' iroha = Iroha(account_id) tx = iroha.transaction([ iroha.command('CreateAccount', account_name=self.name, domain_id='public', public_key=self.public_key) ]) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx, self.network) tx = iroha.transaction([ iroha.command('SetAccountDetail', account_id=account_id, key='public information', value=self.public_info) ]) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx, self.network)
def add_keys_and_set_quorum(): alice_iroha = Iroha('alice@test') alice_cmds = [ alice_iroha.command('AddSignatory', account_id='alice@test', public_key=alice_public_keys[1]), alice_iroha.command('SetAccountQuorum', account_id='alice@test', quorum=2) ] alice_tx = alice_iroha.transaction(alice_cmds) ic.sign_transaction(alice_tx, alice_private_keys[0]) send_transaction_and_print_status(alice_tx) bob_iroha = Iroha('bob@test') bob_cmds = [ bob_iroha.command('AddSignatory', account_id='bob@test', public_key=bob_public_keys[1]), bob_iroha.command('SetAccountQuorum', account_id='bob@test', quorum=2) ] bob_tx = bob_iroha.transaction(bob_cmds) ic.sign_transaction(bob_tx, bob_private_keys[0]) send_transaction_and_print_status(bob_tx)
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')}" )
def get_account_details(contract_address: str, user_account: str): iroha_user = Iroha(user_account) params = integration_helpers.get_first_four_bytes_of_keccak( b"getAccountDetail()") no_of_param = 0 tx = iroha_user.transaction([ iroha_user.command("CallEngine", caller=user_account, callee=contract_address, input=params) ]) IrohaCrypto.sign_transaction(tx, user_private_key) response = net.send_tx(tx) for status in net.tx_status_stream(tx): print(status) hex_hash = binascii.hexlify(IrohaCrypto.hash(tx)) return hex_hash
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")
def grants_access_to_set_details(your_domain, your_name, private_key, grant_domain, grant_account): """ Grant node to set details on your profile :param your_domain: (str) your domain. Domain of the granter :param your_name: (str) you name. Name of the granter :param private_key: (str) private key for signing. Private key of the granter :param grant_domain: (str) domain of the node how will have access permissions :param grant_account: (str) name of the node how will have access permissions :return: """ my_id_account = your_name + '@' + your_domain grant_account_id = grant_account + '@' + grant_domain iroha = Iroha(my_id_account) tx = iroha.transaction([ iroha.command('GrantPermission', account_id=grant_account_id, permission=can_set_my_account_detail) ], creator_account=my_id_account) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx)
def transfer_assets_to(self, user, asset_name, quantity, description, private_key): """ Transfer assets from one account to another. Both users must be in the same domain. :Example: >>> import json >>> from utils.administrator import Domain >>> x = { "age": 30, "city": "New York" } >>> account_information = json.dumps(x) >>> x = { "age": 34, "city": "Mexico" } >>> account_information_dante = json.dumps(x) >>> domain = Domain('name', 'default_role') >>> user = User('private_key','David',domain, account_information) >>> dante = User('dante_private_key','Dante',domain, account_information_dante) >>> user.transfer_assets_to(dante, 'coin', '2', 'Shut up and take my money') :param User user: User you want to transfer the assets :param str asset_name: Name of the asset to be transferred :param float quantity: Number of assets we want to transfer :param str description: Small message to the receiver of assets :param str private_key: Key to sign the transaction """ account_id = self.name + '@' + self.domain.name iroha = Iroha(account_id) destination_account = user.name + '@' + self.domain.name asset_id = asset_name + '#' + self.domain.name tx = iroha.transaction([ iroha.command('TransferAsset', src_account_id=account_id, dest_account_id=destination_account, asset_id=asset_id, description=description, amount=quantity) ]) IrohaCrypto.sign_transaction(tx, private_key) send_transaction_and_print_status(tx, self.network)
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)
class IrohaBlockchain: IROHA_HOST_ADDR = env("IROHA_HOST_ADDR", "127.0.0.1") IROHA_PORT = env("IROHA_PORT", "50051") 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}") def send_transaction_and_return_status(self, transaction): """ Sends a transaction to the blockchain """ self.net.send_tx(transaction) stati = [] for status in self.net.tx_status_stream(transaction): stati.append(status) return stati def create_account(self, user): """ Creates a user account """ tx = self.iroha.transaction([ self.iroha.command( "CreateAccount", account_name=user.gov_id, domain_id="afyamkononi", public_key=user.public_key, ) ]) IrohaCrypto.sign_transaction(tx, self.creator_account_details.private_key) return self.send_transaction_and_return_status(tx) def append_role(self, user): """ Appends a role to a user """ tx = self.iroha.transaction( [ self.iroha.command( "AppendRole", account_id=f"{user.gov_id}@afyamkononi", role_name=user.type, ) ], creator_account= f"{self.creator_account_details.gov_id}@afyamkononi", ) IrohaCrypto.sign_transaction(tx, self.creator_account_details.private_key) return self.send_transaction_and_return_status(tx) def set_account_details(self, user): """ Set account details """ tx = self.iroha.transaction([ self.iroha.command( "SetAccountDetail", account_id=f"{user.gov_id}@afyamkononi", key="gov_id", value=f"{user.gov_id}", ), self.iroha.command( "SetAccountDetail", account_id=f"{user.gov_id}@afyamkononi", key="name", value=f"{user.name}", ), self.iroha.command( "SetAccountDetail", account_id=f"{user.gov_id}@afyamkononi", key="email", value=f"{user.email}", ), self.iroha.command( "SetAccountDetail", account_id=f"{user.gov_id}@afyamkononi", key="phone_number", value=f"{user.phone_number}", ), ]) IrohaCrypto.sign_transaction(tx, self.creator_account_details.private_key) return self.send_transaction_and_return_status(tx) def get_account_details(self, gov_id, data_key=None): """ Get all the kv-storage entries for a user """ if data_key == None: query = self.iroha.query("GetAccountDetail", account_id=f"{gov_id}@afyamkononi") else: query = self.iroha.query("GetAccountDetail", account_id=f"{gov_id}@afyamkononi", key=data_key) IrohaCrypto.sign_query(query, self.creator_account_details.private_key) response = self.net.send_query(query) return response.account_detail_response def grant_set_account_detail_perms(self, user): """ Make creator account able to set detail to account """ tx = self.iroha.transaction( [ self.iroha.command( "GrantPermission", account_id= f"{self.creator_account_details.gov_id}@afyamkononi", permission=can_set_my_account_detail, ) ], creator_account=f"{user.gov_id}@afyamkononi", ) IrohaCrypto.sign_transaction(tx, user.private_key) return self.send_transaction_and_return_status(tx) def revoke_set_account_detail_perms(self, user): """ Revoke creator account able to set detail to account """ tx = self.iroha.transaction( [ self.iroha.command( "RevokePermission", account_id= f"{self.creator_account_details.gov_id}@afyamkononi", permission=can_set_my_account_detail, ) ], creator_account=f"{user.gov_id}@afyamkononi", ) IrohaCrypto.sign_transaction(tx, user.private_key) return self.send_transaction_and_return_status(tx) def set_patient_record(self, patient, history_update): """ Set patient records """ history_update = (json.dumps(history_update)).replace('"', '\\"') tx = self.iroha.transaction([ self.iroha.command( "SetAccountDetail", account_id=f"{patient.gov_id}@afyamkononi", key="gov_id", value=f"{patient.gov_id}", ), self.iroha.command( "SetAccountDetail", account_id=f"{patient.gov_id}@afyamkononi", key="name", value=f"{patient.name}", ), self.iroha.command( "SetAccountDetail", account_id=f"{patient.gov_id}@afyamkononi", key="email", value=f"{patient.email}", ), self.iroha.command( "SetAccountDetail", account_id=f"{patient.gov_id}@afyamkononi", key="phone_number", value=f"{patient.phone_number}", ), self.iroha.command( "SetAccountDetail", account_id=f"{patient.gov_id}@afyamkononi", key="medical_data", value=history_update, ) ]) IrohaCrypto.sign_transaction(tx, self.creator_account_details.private_key) return self.send_transaction_and_return_status(tx) def get_all_account_transactions(self, gov_id): query = self.iroha.query("GetAccountTransactions", account_id=f"{gov_id}@afyamkononi", page_size=30) IrohaCrypto.sign_query(query, self.creator_account_details.private_key) return self.net.send_query(query) def get_all_roles(self): query = self.iroha.query( "GetRoles", creator_account= f"{self.creator_account_details.gov_id}@afyamkononi", ) query = IrohaCrypto.sign_query( query, self.creator_account_details.private_key) return self.net.send_query(query) def get_role_permissions(self, role): query = self.iroha.query("GetRolePermissions", role_id=role) query = IrohaCrypto.sign_query( query, self.creator_account_details.private_key) return self.net.send_query(query) def grant_edit_permissions(self, subject): tx = self.iroha.transaction( [ self.iroha.command( "GrantPermission", account_id=f"{subject.gov_id}@afyamkononi", permission=can_set_my_account_detail, ) ], creator_account= f"{self.creator_account_details.gov_id}@afyamkononi", ) IrohaCrypto.sign_transaction(tx, self.creator_account_details.private_key) return self.send_transaction_and_return_status(tx) def revoke_edit_permissions(self, subject): tx = self.iroha.transaction( [ self.iroha.command( "RevokePermission", account_id=f"{subject.gov_id}@afyamkononi", permission=can_set_my_account_detail, ) ], creator_account= f"{self.creator_account_details.gov_id}@afyamkononi", ) IrohaCrypto.sign_transaction(tx, self.creator_account_details.private_key) return self.send_transaction_and_return_status(tx)
import os import sys from iroha import Iroha, IrohaCrypto, IrohaGrpc # Iroha torii url url = sys.argv[1] # Iroha admin account that will send the transaction admin_account = sys.argv[2] # Iroha admin account private key path admin_priv_path = sys.argv[3] # Iroha asset asset = sys.argv[4] # Amount to be added to the account amount = sys.argv[5] iroha = Iroha(admin_account) net = IrohaGrpc(url) admin_key = open(admin_priv_path, "r").read() tx = iroha.transaction( [iroha.command("AddAssetQuantity", asset_id=asset, amount=amount)]) IrohaCrypto.sign_transaction(tx, admin_key) net.send_tx(tx) for status in net.tx_status_stream(tx): print(status)
class IrohaClient: def __init__(self, creator_account, iroha_host): self.creator_account = creator_account self.iroha = Iroha(creator_account) self.permissions = iroha_primitive self.user_private_key = os.getenv("UBAIN_API_SECRET") self.net = IrohaGrpc(f"{iroha_host}", timeout=60) 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 ## Important Function def sign_and_submit_tx(self, transaction): new_tx = self.iroha.transaction([]) tx = ParseDict(transaction, 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 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) ### Dev Batch Functions def init_test_balance_batch(self, account_id): # Add Dummy Asset Supply For Demo qty = "10.00000000" description = "Welcome To Ubuntu Exchange" currencies = ["BTC", "LTC", "ETH", "XLM", "XMR"] tx = self.iroha.transaction([ self.iroha.command("AddAssetQuantity", asset_id="btc#iroha", amount=qty), self.iroha.command("AddAssetQuantity", asset_id="ltc#iroha", amount=qty), self.iroha.command("AddAssetQuantity", asset_id="eth#iroha", amount=qty), self.iroha.command("AddAssetQuantity", asset_id="xlm#iroha", amount=qty), self.iroha.command("AddAssetQuantity", asset_id="xmr#iroha", amount=qty), self.iroha.command( "TransferAsset", description=description, src_account_id="admin@iroha", dest_account_id=account_id, asset_id="btc#iroha", amount=qty, ), self.iroha.command( "TransferAsset", description=description, src_account_id="admin@iroha", dest_account_id=account_id, asset_id="ltc#iroha", amount=qty, ), self.iroha.command( "TransferAsset", description=description, src_account_id="admin@iroha", dest_account_id=account_id, asset_id="eth#iroha", amount=qty, ), self.iroha.command( "TransferAsset", description=description, src_account_id="admin@iroha", dest_account_id=account_id, asset_id="xlm#iroha", amount=qty, ), self.iroha.command( "TransferAsset", description=description, src_account_id="admin@iroha", dest_account_id=account_id, asset_id="xmr#iroha", amount=qty, ), ]) 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) 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=self.permissions.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=self.permissions.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)