def create_address_for_agent(agent): address = None if hasattr(settings, 'NEW_FAIRCOIN_ADDRESSES_FILE'): address = create_address_from_file( entity_id = agent.nick.encode('ascii','ignore'), entity = agent.agent_type.name, ) return address if efn.is_connected(): try: address = efn.new_fair_address( entity_id = agent.nick.encode('ascii','ignore'), entity = agent.agent_type.name, ) except Exception: _, e, _ = sys.exc_info() logger.critical("an exception occurred in creating a FairCoin address: {0}".format(e)) if (address is not None) and (address != 'ERROR'): used = EconomicResource.objects.filter(faircoin_address__address=address) if used.count(): msg = " ".join(["address already existent! (count[0]=", str(used[0]), ") when creating new address for", agent.name]) logger.critical(msg) return None #create_address_for_agent(agent) elif address == 'ERROR': msg = " ".join(["address string is ERROR. None returned. agent:", agent.name]) logger.critical(msg) return None return address
def create_requested_addresses(): try: requests = EconomicResource.objects.filter( faircoin_address__address="address_requested") msg = " ".join( ["new FairCoin address requests count:", str(requests.count())]) logger.debug(msg) except Exception: _, e, _ = sys.exc_info() logger.critical( "an exception occurred in retrieving FairCoin address requests: {0}" .format(e)) return "failed to get FairCoin address requests" if requests: if efn.is_connected(): for resource in requests: result = create_address_for_resource(resource) msg = " ".join( ["created", str(requests.count()), "new faircoin addresses."]) else: msg = "No new faircoin address requests to process." return msg
def faircoin_history(request, resource_id): resource = get_object_or_404(EconomicResource, id=resource_id) agent = get_agent(request) wallet = faircoin_utils.is_connected() confirmed_balance = None unconfirmed_balance = None if wallet: if resource.is_wallet_address(): exchange_service = ExchangeService.get() exchange_service.include_blockchain_tx_as_event( resource.owner(), resource) try: balances = faircoin_utils.get_address_balance( resource.faircoin_address.address) confirmed_balance = Decimal(balances[0]) / FAIRCOIN_DIVISOR unconfirmed_balance = Decimal(balances[0] + balances[1]) / FAIRCOIN_DIVISOR unconfirmed_balance += resource.balance_in_tx_state_new() except: confirmed_balance = "Not accessible now" unconfirmed_balance = "Not accessible now" else: wallet = False event_list = resource.events.all() init = { "quantity": resource.quantity, } unit = resource.resource_type.unit paginator = Paginator(event_list, 25) page = request.GET.get('page') try: events = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. events = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. events = paginator.page(paginator.num_pages) if resource.owner() == agent or resource.owner() in agent.managed_projects( ) or agent.is_staff(): return render( request, "faircoin/faircoin_history.html", { "resource": resource, "agent": agent, "confirmed_balance": confirmed_balance, "unconfirmed_balance": unconfirmed_balance, "unit": unit, "events": events, "wallet": wallet, }) else: return render(request, 'work/no_permission.html')
def faircoin_history(request, resource_id): resource = get_object_or_404(EconomicResource, id=resource_id) agent = get_agent(request) wallet = faircoin_utils.is_connected() confirmed_balance = None unconfirmed_balance = None if wallet: if resource.is_wallet_address(): exchange_service = ExchangeService.get() exchange_service.include_blockchain_tx_as_event(resource.owner(), resource) try: balances = faircoin_utils.get_address_balance(resource.faircoin_address.address) confirmed_balance = Decimal(balances[0]) / FAIRCOIN_DIVISOR unconfirmed_balance = Decimal(balances[0] + balances[1]) / FAIRCOIN_DIVISOR unconfirmed_balance += resource.balance_in_tx_state_new() except: confirmed_balance = "Not accessible now" unconfirmed_balance = "Not accessible now" else: wallet = False event_list = resource.events.all() init = {"quantity": resource.quantity,} unit = resource.resource_type.unit paginator = Paginator(event_list, 25) page = request.GET.get('page') try: events = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. events = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. events = paginator.page(paginator.num_pages) if resource.owner() == agent or resource.owner() in agent.managed_projects() or agent.is_staff(): return render(request, "faircoin/faircoin_history.html", { "resource": resource, "agent": agent, "confirmed_balance": confirmed_balance, "unconfirmed_balance": unconfirmed_balance, "unit": unit, "events": events, "wallet": wallet, }) else: return render(request, 'work/no_permission.html')
def balance(self): wallet = faircoin_utils.is_connected() if wallet: is_wallet_address = faircoin_utils.is_mine(self.address) if is_wallet_address: try: balances = faircoin_utils.get_address_balance(self.address) unconfirmed_balance = Decimal(balances[1]) / FAIRCOIN_DIVISOR unconfirmed_balance += self.resource.balance_in_tx_state_new() confirmed_balance = Decimal(balances[0]) / FAIRCOIN_DIVISOR if unconfirmed_balance < 0: confirmed_balance += unconfirmed_balance elif unconfirmed_balance == 0: unconfirmed_balance = confirmed_balance return confirmed_balance except: pass return None
def create_requested_addresses(): try: requests = EconomicResource.objects.filter(faircoin_address__address="address_requested") msg = " ".join(["new FairCoin address requests count:", str(requests.count())]) logger.debug(msg) except Exception: _, e, _ = sys.exc_info() logger.critical("an exception occurred in retrieving FairCoin address requests: {0}".format(e)) return "failed to get FairCoin address requests" if requests: if efn.is_connected(): for resource in requests: result = create_address_for_resource(resource) msg = " ".join(["created", str(requests.count()), "new faircoin addresses."]) else: msg = "No new faircoin address requests to process." return msg
def create_address_for_agent(agent): address = None used_query_list = FaircoinAddress.objects.values_list('address', flat=True) used_list = list(used_query_list) if efn.is_connected(): try: unused_address = efn.get_unused_addresses() except Exception: _, e, _ = sys.exc_info() logger.critical("Can not get the list of unused addresses from the wallet: {0}".format(e)) for add in unused_address: if add not in used_list: logger.debug("Found unused %s -- %s" %(add, efn.get_address_index(add))) address = add break if (address is None) or (address == 'ERROR'): msg = ("CAN NOT CREATE ADDRESS FOR %s" %(agent.name)) logger.critical(msg) return None return address
def faircoin_history(request, resource_id): resource = get_object_or_404(EconomicResource, id=resource_id) agent = get_agent(request) owner = resource.owner() wallet = faircoin_utils.is_connected() confirmed_balance = None unconfirmed_balance = None if wallet: if resource.is_wallet_address(): exchange_service = ExchangeService.get() exchange_service.include_blockchain_tx_as_event(owner, resource) try: balances = faircoin_utils.get_address_balance( resource.faircoin_address.address) confirmed_balance = Decimal(balances[0]) / FAIRCOIN_DIVISOR unconfirmed_balance = Decimal(balances[0] + balances[1]) / FAIRCOIN_DIVISOR unconfirmed_balance += resource.balance_in_tx_state_new() except: confirmed_balance = "Not accessible now" unconfirmed_balance = "Not accessible now" else: wallet = False event_list = EconomicEvent.objects.filter( Q(resource=resource) | Q(faircoin_transaction__to_address=resource.faircoin_address.address) ).annotate(numev=Count("transfer__events")).exclude( numev__gt=1, event_type__name="Receive") #event_list = resource.events.all() for ev in event_list: if ev.exchange: if ev.to_agent == owner.parent() and not ev.from_agent == owner: print "-- change exchange agent to parent? ev:" + str( ev.id) + " ca:" + str( ev.exchange.context_agent) + " from:" + str( ev.from_agent) + " ex:" + str( ev.exchange.id) + " et:" + str( ev.exchange.exchange_type) logger.debug("-- change exchange agent to parent? ev:" + str(ev.id) + " ca:" + str(ev.exchange.context_agent) + " from:" + str(ev.from_agent) + " ex:" + str(ev.exchange.id) + " et:" + str(ev.exchange.exchange_type)) if ev.from_agent == owner.parent() and not ev.to_agent == owner: print "-- change exchange agent from parent? ev:" + str( ev.id) + " ca:" + str( ev.exchange.context_agent) + " to:" + str( ev.to_agent) + " ex:" + str( ev.exchange.id) + " et:" + str( ev.exchange.exchange_type) logger.debug("-- change exchange agent from parent? ev:" + str(ev.id) + " ca:" + str(ev.exchange.context_agent) + " to:" + str(ev.to_agent) + " ex:" + str(ev.exchange.id) + " et:" + str(ev.exchange.exchange_type)) ev.list_name = ev.show_name(resource.owner()).split(' ')[0] init = { "quantity": resource.quantity, } unit = resource.resource_type.unit paginator = Paginator(event_list, 25) page = request.GET.get('page') try: events = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. events = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. events = paginator.page(paginator.num_pages) if resource.owner() == agent or resource.owner() in agent.managed_projects( ) or agent.is_staff(): return render( request, "faircoin/faircoin_history.html", { "resource": resource, "agent": agent, "confirmed_balance": confirmed_balance, "unconfirmed_balance": unconfirmed_balance, "unit": unit, "events": events, "wallet": wallet, }) else: return render(request, 'work/no_permission.html')
def manage_faircoin_account(request, resource_id): resource = get_object_or_404(EconomicResource, id=resource_id) user_agent = get_agent(request) if not user_agent or not (resource.owner() == user_agent or resource.owner() in user_agent.managed_projects()): raise Http404 send_coins_form = None is_wallet_address = None limit = 0 confirmed_balance = None unconfirmed_balance = None faircoin_account = False payment_due = False share_price = False number_of_shares = False can_pay = False candidate_membership = None wallet = faircoin_utils.is_connected() if wallet: is_wallet_address = faircoin_utils.is_mine( resource.faircoin_address.address) if is_wallet_address: send_coins_form = SendFairCoinsForm(agent=resource.owner()) try: balances = faircoin_utils.get_address_balance( resource.faircoin_address.address) unconfirmed_balance = Decimal(balances[1]) / FAIRCOIN_DIVISOR unconfirmed_balance += resource.balance_in_tx_state_new() confirmed_balance = Decimal(balances[0]) / FAIRCOIN_DIVISOR if unconfirmed_balance < 0: confirmed_balance += unconfirmed_balance elif unconfirmed_balance == 0: unconfirmed_balance = confirmed_balance except: confirmed_balance = "Not accessible now" unconfirmed_balance = "Not accessible now" else: #wallet = False if resource.is_address_requested(): is_wallet_address = True netfee = faircoin_utils.network_fee_fairs() project = jn_req = None pending_amount = 0 for req in resource.owner().project_join_requests.all(): #candidate_membership = resource.owner().candidate_membership(req.project.agent) if req.pending_shares() and req.project.agent.need_faircoins( ): #candidate_membership: obj = req.payment_option() faircoin_account = resource.owner().faircoin_resource() shacct = req.project.shares_account_type() if faircoin_account and wallet and obj and obj[ 'key'] == 'faircoin' and shacct: share = req.project.shares_type( ) #EconomicResourceType.objects.membership_share() #share_price = faircoin_utils.share_price_in_fairs(req) number_of_shares = req.pending_shares( ) #resource.owner().number_of_shares() share_price = Decimal(req.payment_pending_amount() ) #share_price * number_of_shares pending_amount = share_price project = req.project jn_req = req payment_due = True if resource.owner().owns_resource_of_type( shacct) and share_price == 0: payment_due = False if confirmed_balance and confirmed_balance != "Not accessible now": can_pay = round(confirmed_balance, 8) >= round( share_price, 8) if not can_pay: pending_amount = round(share_price - confirmed_balance, 8) break elif request.user.is_superuser and req.project.agent.need_faircoins( ): logger.warning("(debug) pro:" + str(req.project.agent) + " fair_account:" + str(faircoin_account) + " wallet:" + str(wallet) + " obj:" + str(obj) + " shares_account_type:" + str(shacct)) messages.warning( request, "(debug) pro:" + str(req.project.agent) + " fair_account:" + str(faircoin_account) + " wallet:" + str(wallet) + " obj:" + str(obj) + " shares_account_type:" + str(shacct)) return render( request, "faircoin/faircoin_account.html", { "resource": resource, "photo_size": (128, 128), "agent": resource.owner(), "wallet": wallet, "send_coins_form": send_coins_form, "is_wallet_address": is_wallet_address, "confirmed_balance": confirmed_balance, "unconfirmed_balance": unconfirmed_balance, "faircoin_account": faircoin_account, "candidate_membership": candidate_membership, "payment_due": payment_due, "share_price": round(share_price, 8), "pending_amount": round(pending_amount, 8), "number_of_shares": number_of_shares, "can_pay": can_pay, "project": project, "jn_req": jn_req, "help": get_help("faircoin account"), })
def manage_faircoin_account(request, resource_id): resource = get_object_or_404(EconomicResource, id=resource_id) user_agent = get_agent(request) if not user_agent or not (resource.owner() == user_agent or resource.owner() in user_agent.managed_projects()): raise Http404 send_coins_form = None is_wallet_address = None limit = 0 confirmed_balance = None unconfirmed_balance = None faircoin_account = False payment_due = False share_price = False number_of_shares = False can_pay = False wallet = faircoin_utils.is_connected() if wallet: is_wallet_address = faircoin_utils.is_mine( resource.faircoin_address.address) if not is_wallet_address: if resource.is_address_requested(): is_wallet_address = True if is_wallet_address: send_coins_form = SendFairCoinsForm(agent=resource.owner()) try: balances = faircoin_utils.get_address_balance( resource.faircoin_address.address) confirmed_balance = Decimal(balances[0]) / FAIRCOIN_DIVISOR unconfirmed_balance = Decimal(balances[0] + balances[1]) / FAIRCOIN_DIVISOR unconfirmed_balance += resource.balance_in_tx_state_new() fee = Decimal(faircoin_utils.network_fee()) / FAIRCOIN_DIVISOR limit = min(confirmed_balance, unconfirmed_balance) - fee except: confirmed_balance = "Not accessible now" unconfirmed_balance = "Not accessible now" limit = Decimal("0.0") else: wallet = False candidate_membership = resource.owner().candidate_membership() if candidate_membership: faircoin_account = resource.owner().faircoin_resource() if faircoin_account and wallet: share = EconomicResourceType.objects.membership_share() share_price = share.price_per_unit number_of_shares = resource.owner().number_of_shares() share_price = share_price * number_of_shares payment_due = True if resource.owner().owns_resource_of_type(share): payment_due = False if confirmed_balance and confirmed_balance != "Not accessible now": can_pay = confirmed_balance >= share_price return render( request, "faircoin/faircoin_account.html", { "resource": resource, "photo_size": (128, 128), "agent": resource.owner(), "wallet": wallet, "send_coins_form": send_coins_form, "is_wallet_address": is_wallet_address, "confirmed_balance": confirmed_balance, "unconfirmed_balance": unconfirmed_balance, "limit": limit, "faircoin_account": faircoin_account, "candidate_membership": candidate_membership, "payment_due": payment_due, "share_price": share_price, "number_of_shares": number_of_shares, "can_pay": can_pay, "help": get_help("faircoin account"), })
from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.conf import settings from django.contrib import messages from django.db.models import Q, Count from valuenetwork.valueaccounting.models import EconomicResource, EconomicEvent, EconomicResourceType, EconomicAgent, Help from valuenetwork.valueaccounting.forms import EconomicResourceForm from valuenetwork.valueaccounting.service import ExchangeService from faircoin import utils as faircoin_utils from faircoin.forms import SendFairCoinsForm from faircoin.decorators import confirm_password FAIRCOIN_DIVISOR = faircoin_utils.FAIRCOIN_DIVISOR #Decimal("100000000.00") WALLET = faircoin_utils.is_connected() logger = logging.getLogger('ocp') def get_agent(request): agent = None try: au = request.user.agent agent = au.agent except: pass return agent def get_help(page_name):
def broadcast_tx(): try: events1 = EconomicEvent.objects.filter(faircoin_transaction__tx_state="new").order_by('pk') events = events1.filter(Q(event_type__name='Give')|Q(event_type__name='Distribution')) if not events and events1: events2 = events1.filter(Q(event_type__name='Receive')) for ev in events2: mirr = ev.mirror_event() if mirr: if hasattr(mirr, 'faircoin_transaction') and mirr.faircoin_transaction: pass else: if hasattr(ev, 'faircoin_transaction') and ev.faircoin_transaction and mirr.event_type.name == 'Give': tx = ev.faircoin_transaction tx.event = mirr logger.warning("Using a 'Receive' event to link a FairTX!? CHANGED to Give mirror! mi:"+str(mirr.id)+" ev:"+str(ev.id)+" ("+str(ev)+")") print("Using a 'Receive' event to link a FairTX!? CHANGED to Give mirror! mi:"+str(mirr.id)+" ev:"+str(ev.id)+" ("+str(ev)+")") # If you got this warnings in fair_debug.log, you can solve each case by uncommenting the following # 2 lines and let the cron run this function 2 times (minutes?) for each case, and watch each solving # step. Comment again both lines after, to stuck again possible errors warnings. #tx.save() #break msg = " ".join(["new FairCoin event count:", str(events.count())]) logger.debug(msg) except Exception: _, e, _ = sys.exc_info() logger.critical("an exception occurred in retrieving events: {0}".format(e)) logger.warning("releasing lock because of error...") lock.release() logger.debug("released.") return "failed to get events" try: successful_events = 0 failed_events = 0 if events and efn.is_connected(): logger.debug("broadcast_tx ready to process events") for event in events: if event.resource and event.faircoin_transaction: if event.event_type.name=="Give": address_origin = event.resource.faircoin_address.address address_end = event.faircoin_transaction.to_address elif event.event_type.name=="Distribution": address_origin = event.from_agent.faircoin_address() address_end = event.resource.faircoin_address.address fairtx = event.faircoin_transaction amount = float(fairtx.amount) * 1.e8 # In satoshis if amount < 1001: fairtx.tx_state = "broadcast" fairtx.tx_hash = "Null" fairtx.save() continue logger.info("About to build transaction. Amount: %d From: %s To: %s Minus Fee: %s" %(int(amount), address_origin, address_end, fairtx.minus_fee)) tx_hash = None try: tx_hash, fee = efn.make_transaction_from_address(address_origin, address_end, int(amount), fairtx.minus_fee) except Exception: _, e, _ = sys.exc_info() logger.critical("an exception occurred in make_transaction_from_address: {0}".format(e)) if (tx_hash == "ERROR") or (not tx_hash): logger.warning("ERROR tx_hash, make tx failed without raising Exception") failed_events += 1 elif tx_hash: successful_events += 1 if event.event_type.name=="Give": qty = event.quantity qty += Decimal(fee) / Decimal("1.e8") event.quantity = qty event.save() fairtx.tx_state = "broadcast" fairtx.tx_hash = tx_hash fairtx.save() transfer = event.transfer if transfer: revent = transfer.receive_event() if revent: refairtx = revent.faircoin_transaction refairtx.tx_state = "broadcast" refairtx.tx_hash = tx_hash refairtx.save() msg = " ".join([ "Broadcasted tx", tx_hash, "amount", str(amount), "from", address_origin, "to", address_end ]) logger.info(msg) else: failed_events += 1 logger.critical("Event has no 'resource' or 'faircoin_trasaction'! id:"+str(event.id)+" ("+str(event)+")") except Exception: _, e, _ = sys.exc_info() logger.critical("an exception occurred in processing events: {0}".format(e)) return "failed to process events" if events: msg = " ".join(["Broadcast", str(successful_events), "new faircoin tx."]) if failed_events: msg += " ".join([ str(failed_events), "events failed."]) else: msg = "No new faircoin tx to process." return msg
def manage_faircoin_account(request, resource_id): resource = get_object_or_404(EconomicResource, id=resource_id) user_agent = get_agent(request) if not user_agent or not (resource.owner() == user_agent or resource.owner() in user_agent.managed_projects()): raise Http404 send_coins_form = None is_wallet_address = None limit = 0 confirmed_balance = None unconfirmed_balance = None faircoin_account = False payment_due = False share_price = False number_of_shares = False can_pay = False wallet = faircoin_utils.is_connected() if wallet: is_wallet_address = faircoin_utils.is_mine(resource.faircoin_address.address) if is_wallet_address: send_coins_form = SendFairCoinsForm(agent=resource.owner()) try: balances = faircoin_utils.get_address_balance(resource.faircoin_address.address) unconfirmed_balance = Decimal(balances[1]) / FAIRCOIN_DIVISOR unconfirmed_balance += resource.balance_in_tx_state_new() confirmed_balance = Decimal(balances[0]) / FAIRCOIN_DIVISOR if unconfirmed_balance < 0: confirmed_balance += unconfirmed_balance elif unconfirmed_balance == 0: unconfirmed_balance = confirmed_balance except: confirmed_balance = "Not accessible now" unconfirmed_balance = "Not accessible now" else: wallet = False if resource.is_address_requested(): is_wallet_address = True candidate_membership = resource.owner().candidate_membership() if candidate_membership: faircoin_account = resource.owner().faircoin_resource() if faircoin_account and wallet: share = EconomicResourceType.objects.membership_share() share_price = share.price_per_unit number_of_shares = resource.owner().number_of_shares() share_price = share_price * number_of_shares payment_due = True if resource.owner().owns_resource_of_type(share): payment_due = False if confirmed_balance and confirmed_balance != "Not accessible now": can_pay = confirmed_balance >= share_price return render(request, "faircoin/faircoin_account.html", { "resource": resource, "photo_size": (128, 128), "agent": resource.owner(), "wallet": wallet, "send_coins_form": send_coins_form, "is_wallet_address": is_wallet_address, "confirmed_balance": confirmed_balance, "unconfirmed_balance": unconfirmed_balance, "faircoin_account": faircoin_account, "candidate_membership": candidate_membership, "payment_due": payment_due, "share_price": share_price, "number_of_shares": number_of_shares, "can_pay": can_pay, "help": get_help("faircoin account"), })
def broadcast_tx(): try: events = EconomicEvent.objects.filter( faircoin_transaction__tx_state="new").order_by('pk') events = events.filter( Q(event_type__name='Give')|Q(event_type__name='Distribution')) msg = " ".join(["new FairCoin event count:", str(events.count())]) logger.debug(msg) except Exception: _, e, _ = sys.exc_info() logger.critical("an exception occurred in retrieving events: {0}".format(e)) logger.warning("releasing lock because of error...") lock.release() logger.debug("released.") return "failed to get events" try: successful_events = 0 failed_events = 0 if events and efn.is_connected(): logger.debug("broadcast_tx ready to process events") for event in events: if event.resource: if event.event_type.name=="Give": address_origin = event.resource.faircoin_address.address address_end = event.faircoin_transaction.to_address elif event.event_type.name=="Distribution": address_origin = event.from_agent.faircoin_address() address_end = event.resource.faircoin_address.address fairtx = event.faircoin_transaction amount = float(event.quantity) * 1.e8 # In satoshis if amount < 1001: fairtx.tx_state = "broadcast" fairtx.tx_hash = "Null" fairtx.save() continue logger.info("About to build transaction. Amount: %d" %(int(amount))) tx_hash = None try: tx_hash, fee = efn.make_transaction_from_address(address_origin, address_end, int(amount)) except Exception: _, e, _ = sys.exc_info() logger.critical("an exception occurred in make_transaction_from_address: {0}".format(e)) if (tx_hash == "ERROR") or (not tx_hash): logger.warning("ERROR tx_hash, make tx failed without raising Exception") failed_events += 1 elif tx_hash: successful_events += 1 if event.event_type.name=="Give": qty = event.quantity qty += Decimal(fee) / Decimal("1.e8") event.quantity = qty event.save() fairtx.tx_state = "broadcast" fairtx.tx_hash = tx_hash fairtx.save() transfer = event.transfer if transfer: revent = transfer.receive_event() if revent: refairtx = revent.faircoin_transaction refairtx.tx_state = "broadcast" refairtx.tx_hash = tx_hash refairtx.save() msg = " ".join([ "Broadcasted tx", tx_hash, "amount", str(amount), "from", address_origin, "to", address_end ]) logger.info(msg) except Exception: _, e, _ = sys.exc_info() logger.critical("an exception occurred in processing events: {0}".format(e)) return "failed to process events" if events: msg = " ".join(["Broadcast", str(successful_events), "new faircoin tx."]) if failed_events: msg += " ".join([ str(failed_events), "events failed."]) else: msg = "No new faircoin tx to process." return msg
def update_data(self, realamount=None): #, oauth=None): url = None json = None inputs = [] input_vals = [] outputs = [] output_vals = [] outvals = [] mesg = '' if realamount: realamount = Decimal(realamount) if not self.tx_fee: unit = self.unit() msg = None if unit and unit.abbrev: if unit.abbrev == 'fair': if self.event.to_agent.nick == "BotC": raise ValidationError("This model is not appropiate to store the Multiwallet ID! ") elif 'faircoin' in settings.INSTALLED_APPS: from faircoin import utils as faircoin_utils wallet = faircoin_utils.is_connected() if wallet: trans = faircoin_utils.send_command('get_transaction', [self.tx_hash]) if trans != 'ERROR': json = {'hash': self.tx_hash, 'out': [], 'inputs': [],} #mesg += "Res: (outs) " for output in trans['outputs']: #mesg += output['address']+" ("+str(output['value'])+"), " json['out'].append({'addr': output['address'], 'value':output['value']}) #mesg += " - (inputs) " for inp in trans['inputs']: amount = 0 #inputs.append(inp['address'] if 'prevout_hash' in inp: intx = faircoin_utils.send_command('get_transaction', [inp['prevout_hash']]) if intx != 'ERROR': for out in intx['outputs']: if out['address'] == inp['address']: amount = int(out['value']) else: amount = 'error' #mesg += inp['address']+" ("+str(amount)+"), " if amount and not amount == 'error': json['inputs'].append({'prev_out':{'addr': inp['address'], 'value': amount}}) #inp['value']}}) else: self.event.delete() self.delete() return mesg #mesg += "<br>"+str(trans) else: mesg += trans self.event.delete() self.delete() return mesg else: mesg += "There's no faircoin wallet to check the transaction." self.event.delete() self.delete() return mesg else: mesg += "Is faircoin but the faircoin app is not installed" self.event.delete() self.delete() return mesg else: key = 'url_'+unit.abbrev+'_tx_json' if key in settings.MULTICURRENCY: url = settings.MULTICURRENCY[key]+self.tx_hash #print("URL: "+url) txobj = requests.get(url) if int(txobj.status_code) == 200: try: json = txobj.json() except: mesg += ("Can't decode tx request as json! txobj:"+str(txobj)) for prop in txobj: mesg += "<br>"+str(prop) self.event.delete() self.delete() return mesg else: mesg += ("Error retrieving the txobj: "+str(txobj)+"<br>") else: mesg += ("The key is not in settings: "+str(key)+"<br>") if json: if 'hash' in json: #.status == "ok": if json['hash'] == self.tx_hash: if 'inputs' in json: for inp in json['inputs']: if 'prev_out' in inp: if 'addr' in inp['prev_out']: inputs.append(inp['prev_out']['addr']) input_vals.append(inp['prev_out']['value']) else: print("tx has no addr in inputs prev_out? inp['prev_out']:"+str(inp['prev_out'])) mesg += ("tx has no addr in inputs prev_out? inp['prev_out']:"+str(inp['prev_out'])) else: print("tx has no prev_out? inp:"+str(inp)) mesg += ("tx has no prev_out? inp:"+str(inp)) else: print("tx has no inputs? json:"+str(json)) mesg += ("tx has no inputs? json:"+str(json)) if 'out' in json: for out in json['out']: if 'addr' in out: if out['addr'] in inputs: print("tx skip output to same input") else: outputs.append(out['addr']) outvals.append(out['value']) output_vals.append(out['value']) else: print("tx output without address? out:"+str(out)) mesg += ("tx output without address? out:"+str(out)) else: print("tx without outputs? json:"+str(json)) mesg += ("tx without outputs? json:"+str(json)) total_in = sum(inp for inp in input_vals) total_out = sum(out for out in output_vals) if total_in and total_out: fee = total_in - total_out if fee > 0: outfee = Decimal(str(fee / DIVISOR)).quantize(DECIMALS) #, settings.CRYPTO_DECIMALS) print("outfee:"+str(outfee)+" type:"+str(type(outfee))) #outfee = remove_exponent(outfee) #print("outfee2:"+str(outfee)+" type:"+str(type(outfee))) self.tx_fee = outfee else: raise ValidationError("negative fee?? json:"+str(json)) validval = 0 for outval in outvals: #) > 1: #mesg += ("Not yet suported various outputs for the crypto TX: "+str(json)) #raise ValidationError("Not yet suported various outputs for the crypto TX: "+str(json)) if self.event.event_type.name == 'Give': val = Decimal( (outval + fee) / DIVISOR).quantize(DECIMALS) #, settings.CRYPTO_DECIMALS) if realamount: if not (realamount+outfee) == val: if (realamount+outfee) < val: rest = val - (realamount+outfee) else: rest = (realamount+outfee) - val jnreq = self.related_join_request() if jnreq: if rest > jnreq.payment_margin(): print("ev-give: Declared amount and chain discovered amount are too different!! rest:"+str(remove_exponent(rest))+" fee:"+str(outfee)+", found+fee:"+str(val)+" (type:"+str(type(val))+") - declared+fee:"+str(realamount+outfee)+"(type:"+str(type(realamount))+")") #loger.info("ev-give: Declared amount and chain discovered amount are too different!! rest:"+str(remove_exponent(rest))+" fee:"+str(outfee)+", found+fee:"+str(val)+" (type:"+str(type(val))+") - declared+fee:"+str(realamount+outfee)+"(type:"+str(type(realamount))+")") #mesg += ("(give event): Declared amount and chain discovered amount are too different!! fee:"+str(outfee)+", found+fee:"+str(val)+" <> declared+fee:"+str(realamount+outfee)+" (rest:"+str(remove_exponent(rest))+")") #+"(type:"+str(type(realamount))+")") #self.event.delete() #self.delete() else: validval = val print("ev-give: Declared amount and chain discovered amount are not equal but are close. Allow... rest:"+str(rest)+" fee:"+str(outfee)+" declared:"+str(realamount)) loger.info("ev-give: Declared amount and chain discovered amount are not equal but are close. Allow... rest:"+str(rest)+" fee:"+str(outfee)+" declared:"+str(realamount)) else: # same val print("ev-give: declared exactly the same amount (+fee): "+str(val)) loger.info("ev-give: declared exactly the same amount (+fee): "+str(val)) validval = val else: # not declared realamount if len(outvals) > 1: print("ev-give: Not declared amount but tx has >1 output! can't check.") mesg += _("Sorry, the system can't check a tx with many outputs without declaring the received amount (give event). ") #self.event.delete() #self.delete() break else: print("ev-give: Without declared amount! Do we get the unique tx output as the valid value? "+str(val)) loger.info("ev-give: Without declared amount! Do we get the unique tx output as the valid value? TODO tx.id:"+str(self.id)+" ev.id:"+str(self.event.id)+" val:"+str(val)) mesg += _("Please, set the received amount to check the transaction.") if validval: if not self.event.quantity == validval: print("UPDATE ev give quantity! qty:"+str(self.event.quantity)+" validval:"+str(validval)+" (type:"+str(type(validval))+") <> declared:"+str(realamount)+"(type:"+str(type(realamount))+")") loger.info("UPDATE ev give quantity! qty:"+str(self.event.quantity)+" validval:"+str(validval)+" type:"+str(type(validval))) self.event.quantity = validval self.event.save() if self.event.commitment: if not self.event.commitment.quantity == validval: print("UPDATE ev give commitment quantity! qty:"+str(self.event.commitment.quantity)+" validval:"+str(validval)) loger.info("UPDATE ev give commitment quantity! qty:"+str(self.event.commitment.quantity)+" validval:"+str(validval)) self.event.commitment.quantity = validval self.event.commitment.save() break elif self.event.event_type.name == 'Receive': val = Decimal( outval / DIVISOR).quantize(DECIMALS) #, settings.CRYPTO_DECIMALS) if realamount: if not realamount == val: if realamount < val: rest = val - realamount else: rest = realamount - val jnreq = self.related_join_request() if jnreq: if rest > jnreq.payment_margin(): print("ev-receive: Declared amount and chain discovered amount are too different!! rest:"+str(remove_exponent(rest))+" fee:"+str(outfee)+", found:"+str(val)+" (type:"+str(type(val))+") <> declared:"+str(realamount)+"(type:"+str(type(realamount))+")") #loger.info("ev-receive: Declared amount and chain discovered amount are too different!! rest:"+str(remove_exponent(rest))+" fee:"+str(outfee)+", found:"+str(val)+" (type:"+str(type(val))+") <> declared:"+str(realamount)+"(type:"+str(type(realamount))+")") #mesg += ("(receive event): Declared amount and chain discovered amount are too different!! fee:"+str(outfee)+", found:"+str(val)+" <> declared:"+str(realamount)+" (rest:"+str(remove_exponent(rest))+")") #+"(type:"+str(type(realamount))+")") #self.event.delete() #self.delete() else: validval = val print("ev-receive: Declared amount and chain discovered amount are not equal but are close. Allow... rest:"+str(rest)+" fee:"+str(outfee)+" declared:"+str(realamount)) loger.info("ev-receive: Declared amount and chain discovered amount are not equal but are close. Allow... rest:"+str(rest)+" fee:"+str(outfee)+" declared:"+str(realamount)) else: # same val print("ev-receive: declared exactly the same amount (-fee): "+str(val)) loger.info("ev-receive: declared exactly the same amount (-fee): "+str(val)) validval = val else: # not declared realamount if len(outvals) > 1: print("ev-receive: Not declared amount but tx has >1 output! can't check.") mesg += _("Sorry, the system can't check a tx with many outputs without declaring the received amount.") #self.event.delete() #self.delete() break else: print("ev-receive: Without declared amount! Do we get the unique tx output as the valid value? "+str(val)) loger.info("ev-receive: Without declared amount! Do we get the unique tx output as the valid value? TODO tx.id:"+str(self.id)+" ev.id:"+str(self.event.id)+" val:"+str(val)) mesg += _("Please, set the received amount to check the transaction.") if validval: if not self.event.quantity == validval: print("UPDATE ev receive quantity! qty:"+str(self.event.quantity)+" val:"+str(val)+" (type:"+str(type(val))+") - realamount:"+str(realamount)+"(type:"+str(type(realamount))+")") loger.info("UPDATE ev receive quantity! qty:"+str(self.event.quantity)+" val:"+str(val)) self.event.quantity = val self.event.save() if self.event.commitment: if not self.event.commitment.quantity == val: print("UPDATE ev receive commitment quantity! qty:"+str(self.event.commitment.quantity)+" val:"+str(val)) loger.info("UPDATE ev receive commitment quantity! qty:"+str(self.event.commitment.quantity)+" val:"+str(val)) self.event.commitment.quantity = val self.event.commitment.save() break else: raise ValidationError("TX event type not supported: "+str(self.event.event_type.name)) # end for if not validval: mesg += _("Not found an output with a similar amount?")+" "+str(outvals) loger.warning("Not found an output with a similar amount? "+str(outvals)) print("Not found an output with a similar amount? "+str(outvals)) self.event.delete() self.delete() return mesg else: raise ValidationError("not tx totals? total_in:"+str(total_in)+" total_out:"+str(total_out)) if self.event: self.from_address = ' '.join(inputs) self.to_address = ' '.join(outputs) self.save() #import pdb; pdb.set_trace() return mesg else: print("tx hash is not the same?? json:"+str(json)) mesg += ("tx hash is not the same?? json:"+str(json)) else: print('tx without hash?? json:'+str(json)) mesg += ('tx without hash?? json:'+str(json)) else: print("No JSON for the tx, delete event! ") mesg += ("No JSON for the tx, delete event! ") if self.event: self.event.delete() self.delete() else: if self.event: mesg += ("There's no unit_of_quantity or abbrev in the related event: "+str(self.event)) self.event.delete() self.delete() else: mesg += ("This tx don't have a related event??") else: mesg += 'This tx already has the tx_fee!' return mesg
def broadcast_tx(): try: events = EconomicEvent.objects.filter( faircoin_transaction__tx_state="new").order_by('pk') events = events.filter( Q(event_type__name='Give') | Q(event_type__name='Distribution')) msg = " ".join(["new FairCoin event count:", str(events.count())]) logger.debug(msg) except Exception: _, e, _ = sys.exc_info() logger.critical( "an exception occurred in retrieving events: {0}".format(e)) logger.warning("releasing lock because of error...") lock.release() logger.debug("released.") return "failed to get events" try: successful_events = 0 failed_events = 0 if events and efn.is_connected(): logger.debug("broadcast_tx ready to process events") for event in events: if event.resource: if event.event_type.name == "Give": address_origin = event.resource.faircoin_address.address address_end = event.faircoin_transaction.to_address elif event.event_type.name == "Distribution": address_origin = event.from_agent.faircoin_address() address_end = event.resource.faircoin_address.address fairtx = event.faircoin_transaction amount = float(fairtx.amount) * 1.e8 # In satoshis if amount < 1001: fairtx.tx_state = "broadcast" fairtx.tx_hash = "Null" fairtx.save() continue logger.info( "About to build transaction. Amount: %d From: %s To: %s Minus Fee: %s" % (int(amount), address_origin, address_end, fairtx.minus_fee)) tx_hash = None try: tx_hash, fee = efn.make_transaction_from_address( address_origin, address_end, int(amount), fairtx.minus_fee) except Exception: _, e, _ = sys.exc_info() logger.critical( "an exception occurred in make_transaction_from_address: {0}" .format(e)) if (tx_hash == "ERROR") or (not tx_hash): logger.warning( "ERROR tx_hash, make tx failed without raising Exception" ) failed_events += 1 elif tx_hash: successful_events += 1 if event.event_type.name == "Give": qty = event.quantity qty += Decimal(fee) / Decimal("1.e8") event.quantity = qty event.save() fairtx.tx_state = "broadcast" fairtx.tx_hash = tx_hash fairtx.save() transfer = event.transfer if transfer: revent = transfer.receive_event() if revent: refairtx = revent.faircoin_transaction refairtx.tx_state = "broadcast" refairtx.tx_hash = tx_hash refairtx.save() msg = " ".join([ "Broadcasted tx", tx_hash, "amount", str(amount), "from", address_origin, "to", address_end ]) logger.info(msg) except Exception: _, e, _ = sys.exc_info() logger.critical( "an exception occurred in processing events: {0}".format(e)) return "failed to process events" if events: msg = " ".join( ["Broadcast", str(successful_events), "new faircoin tx."]) if failed_events: msg += " ".join([str(failed_events), "events failed."]) else: msg = "No new faircoin tx to process." return msg