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 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 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 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 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 get_balance(self, private_key): """ Get the balance of my account. Use the private key of the user to get his current balance. The function will return a dictionary with the id of the asset, the account id and the balance. :Example: >>> import json >>> x = { "age": 30, "city": "New York" } >>> account_information = json.dumps(x) >>> user = User('private_key', 'My Name', 'My domain', '123.456.789', account_information) >>> balance = user.get_balance('private_key') >>> print(balance) {asset_id: "fedcoin#federated", account_id: "generator@federated", balance: "1000"} :param str private_key: key to sign the transaction :return: A a dictionary with the id of the asset, the account id and the balance :rtype: dict """ account_id = self.name + '@' + self.domain.name iroha = Iroha(account_id) query = iroha.query('GetAccountAssets', account_id=account_id) IrohaCrypto.sign_query(query, private_key) response = self.network.send_query(query) data = response.account_assets_response.account_assets for asset in data: print('Asset id = {}, balance = {}'.format(asset.asset_id, asset.balance)) return data
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)
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 __init__(self, account_name, domain): 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)
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 get_all_details_from_generator(domain, name, private_key, generator_domain, generator_name): """ Consult all the details generated by some node :param domain: (str) name of the domain :param name: (str) name of the node :param private_key: (str) Private key of the user :param generator_domain: (str) domain of the user who create de detail :param generator_name: (str) name of the user who create de detail :return: data: (json) solicited details of the user Usage example: get_detail_from_generator('vehicle', 'Ford Fiesta', key, 'individual', 'david' ) Return example: { "nodeA@domain":{ "Age":"35", "Name":"Quetzacolatl" } } """ account_id = name + '@' + domain generator_id = generator_name + '@' + generator_domain iroha = Iroha(account_id) query = iroha.query('GetAccountDetail', account_id=account_id, writer=generator_id) IrohaCrypto.sign_query(query, private_key) response = iroha_config.NETWORK.send_query(query) data = response.account_detail_response print('Account id = {}, details = {}'.format(account_id, data.detail)) return data.detail
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 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 __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 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 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 __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 __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, 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 __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 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 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 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)
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')}" )
def fit(self, parameters, config): """ Locally train the model and send the model to chief for average. This function also send a transaction request to blockchain (not yet implemented) :param parameters: :param config: :return: """ self.model.set_weights(parameters) self.model.fit(self.x_train, self.y_train, epochs=1, batch_size=32, steps_per_epoch=5) print("Send request to blockchain") # set_detail_to_node(iroha, account_id, private_key, detail_key, detail_value): key_pairs = pd.read_csv("../iroha_keys/keypairs.csv") # i is equal to the index for the worker. For instance if name=worker1 then i=1 p_key = key_pairs['private_key'][i] name = self.name domain = iroha_config.domain_id net = self.name + "@" + domain # this function will send a transaction to the blockchain iroha_functions.set_detail_to_node(Iroha(net), net, p_key, 'model_round_n', 'file_model_round_n') return self.model.get_weights(), len(self.x_train), {}
def genesis_tx(): test_permissions = [primitive_pb2.can_remove_peer] genesis_commands = commons.genesis_block(admin, alice, test_permissions) genesis_commands.append(Iroha.command('AddPeer', peer=peer)) tx = iroha.transaction(genesis_commands) IrohaCrypto.sign_transaction(tx, admin['key']) return tx
def get_pending_transactions(): global net query = IrohaCrypto.sign_query(Iroha(group['account']).query('GetPendingTransactions'), ADMIN_PRIVATE_KEY) pending_transactions = net.send_query(query) print(len(pending_transactions.transactions_response.transactions)) for tx in pending_transactions.transactions_response.transactions: print('creator: {}'.format(tx.payload.reduced_payload.creator_account_id))
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
def get_all_details_written_by(self, user, private_key): """ Consult all details writen by some other node :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) >>> details = user.get_all_details_written_by(juan, 'private_key') >>> print(details) { "user@domain":{ "FederatingParam":"35.242553", "Loop":"3" }, "user@domain":{ "sa_param":"44", "Loop":"3" } } :param str private_key: key to sign the transaction :param User user: user who write information on your identification :return: solicited details of the user :rtype: json """ account_id = self.name + '@' + self.domain.name user_id = user.name + '@' + user.domain iroha = Iroha(account_id) query = iroha.query('GetAccountDetail', account_id=account_id, writer=user_id) IrohaCrypto.sign_query(query, private_key) response = self.network.send_query(query) data = response.account_detail_response print('Account id = {}, details = {}'.format(account_id, data.detail)) return data.detail