def withdraw(req, arg): """%withdraw <address> [amount] - Sends 'amount' coins to the specified dogecoin address. If no amount specified, sends the whole balance""" if len(arg) == 0: return req.reply(gethelp("withdraw")) acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if Transactions.lock(acct): return req.reply_private("Your account is currently locked") if len(arg) == 1: amount = max(Transactions.balance(acct) - 1, 1) else: try: amount = parse_amount(arg[1], acct, all_offset = -1) except ValueError as e: return req.reply_private(str(e)) to = arg[0] if not Transactions.verify_address(to): return req.reply_private(to + " doesn't seem to be a valid dogecoin address") token = Logger.token() try: tx = Transactions.withdraw(token, acct, to, amount) req.reply("Coins have been sent, see http://dogechain.info/tx/%s [%s]" % (tx, token)) except Transactions.NotEnoughMoney: req.reply_private("You tried to withdraw Ɖ%i (+Ɖ1 TX fee) but you only have Ɖ%i" % (amount, Transactions.balance(acct))) except Transactions.InsufficientFunds: req.reply("Something went wrong, report this to mniip [%s]" % (token)) Logger.irclog("InsufficientFunds while executing '%s' from '%s'" % (req.text, req.nick))
def tip(req, arg): """%tip <target> <amount> - Sends 'amount' coins to the specified nickname. Nickname can be suffixed with @ and an account name, if you want to make sure you are tipping the correct person""" if len(arg) < 2: return req.reply(gethelp("tip")) to = arg[0] acct, toacct = Irc.account_names([req.nick, target_nick(to)]) if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if Transactions.lock(acct): return req.reply_private("Your account is currently locked") if not toacct: if toacct == None: return req.reply_private(target_nick(to) + " is not online") else: return req.reply_private(target_nick(to) + " is not identified with freenode services") if not target_verify(to, toacct): return req.reply_private("Account name mismatch") try: amount = parse_amount(arg[1], acct) except ValueError as e: return req.reply_private(str(e)) token = Logger.token() try: Transactions.tip(token, acct, toacct, amount) if Irc.equal_nicks(req.nick, req.target): req.reply("Done [%s]" % (token)) else: req.say(" %s tipped BITB%i to %s! (to claim /msg Beaner help) [%s]" % (req.nick, amount, target_nick(to), token)) req.privmsg(target_nick(to), "%s has tipped you BITB%i (to claim /msg Beaner help) [%s]" % (req.nick, amount, token), priority = 10) except Transactions.NotEnoughMoney: req.reply_private("You tried to tip BITB%i but you only have BITB%i" % (amount, Transactions.balance(acct)))
def donate(req, arg): """%donate <amount> - Donate 'amount' coins to the developers of this bot""" if len(arg) < 1: return req.reply(gethelp("donate")) acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if Transactions.lock(acct): return req.reply_private("Your account is currently locked") toacct = "mniip" if arg[0] == "all": arg[0] = str(Transactions.balance(acct)) try: amount = float(arg[0]) if math.isnan(amount): raise ValueError except ValueError as e: return req.reply_private(repr(arg[0]) + " - invalid amount") if amount > 1e12: return req.reply_private(repr(arg[0]) + " - invalid amount (value too large)") if amount < 1: return req.reply_private(repr(arg[0]) + " - invalid amount (should be 1 or more)") if not int(amount) == amount: return req.reply_private(repr(arg[0]) + " - invalid amount (should be integer)") amount = int(amount) token = Logger.token() try: Transactions.tip(token, acct, toacct, amount) req.reply("Donated Ɖ%i [%s]" % (amount, token)) req.privmsg(toacct, "Such %s donated Ɖ%i [%s]" % (req.nick, amount, token), priority = 10) except Transactions.NotEnoughMoney: req.reply_private("You tried to donate Ɖ%i but you only have Ɖ%i" % (amount, Transactions.balance(acct)))
def tip(req, arg): """%tip <target> <amount> - Sends 'amount' coins to the specified nickname. Nickname can be suffixed with @ and an account name, if you want to make sure you are tipping the correct person""" if len(arg) < 2: return req.reply(gethelp("tip")) to = arg[0] acct, toacct = Irc.account_names([req.nick, target_nick(to)]) if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if Transactions.lock(acct): return req.reply_private("Your account is currently locked") if not toacct: if toacct == None: return req.reply_private(target_nick(to) + " is not online") else: return req.reply_private(target_nick(to) + " is not identified with freenode services") if not target_verify(to, toacct): return req.reply_private("Account name mismatch") try: amount = parse_amount(arg[1], acct) except ValueError as e: return req.reply_private(str(e)) token = Logger.token() try: Transactions.tip(token, acct, toacct, amount) if Irc.equal_nicks(req.nick, req.target): req.reply("Done [%s]" % (token)) else: req.say("Such %s tipped much Ɖ%i to %s! (to claim /msg %s help) [%s]" % (req.nick, amount, target_nick(to), req.instance, token)) req.privmsg(target_nick(to), "Such %s has tipped you Ɖ%i (to claim /msg %s help) [%s]" % (req.nick, amount, req.instance, token), priority = 10) except Transactions.NotEnoughMoney: req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (amount, Transactions.balance(acct)))
def tip(req, arg): """%tip <target> <amount> - Sends 'amount' coins to the specified nickname""" if len(arg) < 2: return req.reply(gethelp("tip")) to = arg[0] acct, toacct = Irc.account_names([req.nick, to]) if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if Transactions.lock(acct): return req.reply_private("Your account is currently locked") if not toacct: if toacct == None: return req.reply_private(to + " is not online") else: return req.reply_private(to + " is not identified with freenode services") try: amount = parse_amount(arg[1], acct) except ValueError as e: return req.reply_private(str(e)) token = Logger.token() try: Transactions.tip(token, acct, toacct, amount) if Irc.equal_nicks(req.nick, req.target): req.reply("Done [%s]" % (token)) else: req.say("Such %s tipped much Ɖ%i to %s! (to claim /msg Doger help) [%s]" % (req.nick, amount, to, token)) req.privmsg(to, "Such %s has tipped you Ɖ%i (to claim /msg Doger help) [%s]" % (req.nick, amount, token), priority = 10) except Transactions.NotEnoughMoney: req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (amount, Transactions.balance(acct)))
def mtip(req, arg): """%mtip <targ1> <amt1> [<targ2> <amt2> ...] - Send multiple tips at once""" if not len(arg) or len(arg) % 2: return req.reply(gethelp("mtip")) acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private( "You are not identified with freenode services (see /msg NickServ help)" ) if Transactions.lock(acct): return req.reply_private("Your account is currently locked") for i in range(0, len(arg), 2): try: arg[i + 1] = parse_amount(arg[i + 1], acct) except ValueError as e: return req.reply_private(str(e)) targets = [] amounts = [] total = 0 for i in range(0, len(arg), 2): target = arg[i] amount = arg[i + 1] found = False for i in range(len(targets)): if Irc.equal_nicks(targets[i], target): amounts[i] += amount total += amount found = True break if not found: targets.append(target) amounts.append(amount) total += amount balance = Transactions.balance(acct) if total > balance: return req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (total, balance)) accounts = Irc.account_names(targets) totip = {} failed = "" tipped = "" for i in range(len(targets)): if accounts[i]: totip[accounts[i]] = amounts[i] tipped += " %s %d" % (targets[i], amounts[i]) elif accounts[i] == None: failed += " %s (offline)" % (targets[i]) else: failed += " %s (unidentified)" % (targets[i]) token = Logger.token() try: Transactions.tip_multiple(token, acct, totip) tipped += " [%s]" % (token) except Transactions.NotEnoughMoney: return req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (total, Transactions.balance(acct))) output = "Tipped:" + tipped if len(failed): output += " Failed:" + failed req.reply(output)
def withdraw(req, arg): """%withdraw <address> [amount] - Sends 'amount' coins to the specified dogecoin address. If no amount specified, sends the whole balance""" if len(arg) == 0: return req.reply("%withdraw <address> [amount]") acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if len(arg) == 1: amount = max(Transactions.balance(acct) - 1, 1) else: try: amount = int(arg[1]) if amount <= 0: raise ValueError() amount = min(amount, 1000000000000) except ValueError as e: req.reply_private(repr(arg[1]) + " - invalid amount") return None to = arg[0] if not Transactions.verify_address(to): return req.reply_private(to + " doesn't seem to be a valid dogecoin address") with Logger.token() as token: try: tx = Transactions.withdraw(acct, to, amount) token.log("t", "acct:%s withdrew %d, TX id is %s (acct:%s(%d))" % (acct, amount, tx, acct, Transactions.balance(acct))) req.reply("Coins have been sent, see http://dogechain.info/tx/%s [%s]" % (tx, token.id)) except Transactions.NotEnoughMoney: req.reply_private("You tried to withdraw Ɖ%i (+Ɖ1 TX fee) but you only have Ɖ%i" % (amount, Transactions.balance(acct))) except Transactions.InsufficientFunds: token.log("te", "acct:%s tried to withdraw %d" % (acct, amount)) req.reply("Something went wrong, report this to mniip [%s]" % (token.id))
def join(instance, source, channel, account, _): curtime = time.time() if account == "*": account = False nick = Irc.get_nickname(source, "") with Global.account_lock: if nick == instance: Global.account_cache[channel] = {} Global.account_cache[channel][nick] = account Global.nick_source_cache[nick] = source if account != False and account != None: Global.acctnick_list[account] = nick for channel in Global.account_cache: if nick in Global.account_cache[channel] and channel[0] != "@": if channel in Config.config["welcome_channels"] and (not account or not Transactions.check_exists(account)) and not Transactions.check_exists(nick) and (nick not in Global.welcome_list or Global.welcome_list[nick] + (60*10) < curtime): Global.welcome_list[nick] = curtime # Irc.instance_send(instance, ("PRIVMSG", channel, "Welcome our newest Rogeteer - %s! Try &help, &rogerme and &faucet to get started!" % (nick)), priority = 20, lock = False) Irc.instance_send(instance, ("PRIVMSG", channel, "Welcome our newest Rogeteer - %s! Try &help, &rogerme and &faucet to get started!" % (nick)), priority = 20, lock = False) elif channel in Config.config["welcome_channels"] and account and (Transactions.check_exists(nick) or Transactions.check_exists(account)) and (nick not in Global.welcome_list or Global.welcome_list[nick] + (60*10) < curtime): Global.welcome_list[nick] = curtime welcome_str = str(Commands.random_line('quotes_welcome')) Irc.instance_send(instance, ("NOTICE", nick, "Welcome back %s! %s" % (nick, welcome_str)), priority = 20, lock = False) Global.account_cache[channel][nick] = account Logger.log("w", "Propagating %s=%s into %s" % (nick, account, channel)) if account != False: Expire.bump_last(account)
def main(): print("Hello World!") for row in Customers_test_data: # print(row) Customers.AddCustomer(row) #db.printTable(Constants.CUSTOMER_TBL) for row in Transactions_data: print("Transaction:", row) Transactions.ProcessTrans(row) #db.printTable(Constants.TRANS_TBL) #db.printTable(Constants.CUSTOMER_TBL) for row in Payments_data: print("Payment : ", row) Payments.ProcessPayments(row) #db.printTable(Constants.TRANS_TBL) #db.printTable(Constants.PAYMENTS_TBL) #db.printTable(Constants.CUSTOMER_TBL) Customers.generateStatment(); for row in Transactions_data: print("Transaction:",row) Transactions.ProcessTrans(row) #db.printTable(Constants.TRANS_TBL) #db.printTable(Constants.CUSTOMER_TBL) for row in Payments_data: print("Payment : ", row) Payments.ProcessPayments(row) #db.printTable(Constants.TRANS_TBL) #db.printTable(Constants.PAYMENTS_TBL) #db.printTable(Constants.CUSTOMER_TBL) Customers.generateStatment();
def tip(req, arg): """%tip <target> <amount> - Sends 'amount' coins to the specified nickname""" if len(arg) < 2: return req.reply("%tip <target> <amount>") to = arg[0] acct, toacct = Irc.account_names([req.nick, to]) if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if not toacct: if toacct == None: return req.reply_private(to + " is not online") else: return req.reply_private(to + " is not identified with freenode services") try: amount = int(arg[1]) if amount <= 0: raise ValueError() amount = min(amount, 1000000000000) except ValueError as e: req.reply_private(repr(arg[1]) + " - invalid amount") return None with Logger.token() as token: try: Transactions.tip(acct, toacct, amount) token.log("t", "acct:%s tipped %d to acct:%s(%d)" % (acct, amount, toacct, Transactions.balance(toacct))) if Irc.equal_nicks(req.nick, req.target): req.reply("Done [%s]" % (token.id)) else: req.say("Such %s tipped much Ɖ%i to %s! (to claim /msg Doger help) [%s]" % (req.nick, amount, to, token.id)) Irc.instance_send(req.instance, "PRIVMSG", to, "Such %s has tipped you Ɖ%i (to claim /msg Doger help) [%s]" % (req.nick, amount, token.id)) except Transactions.NotEnoughMoney: req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (amount, Transactions.balance(acct)))
def mtip(req, arg): """%mtip <targ1> <amt1> [<targ2> <amt2> ...] - Send multiple tips at once""" if not len(arg) or len(arg) % 2: return req.reply(gethelp("mtip")) acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if Transactions.lock(acct): return req.reply_private("Your account is currently locked") for i in range(0, len(arg), 2): try: arg[i + 1] = parse_amount(arg[i + 1], acct) except ValueError as e: return req.reply_private(str(e)) targets = [] amounts = [] total = 0 for i in range(0, len(arg), 2): target = arg[i] amount = arg[i + 1] found = False for i in range(len(targets)): if Irc.equal_nicks(targets[i], target): amounts[i] += amount total += amount found = True break if not found: targets.append(target) amounts.append(amount) total += amount balance = Transactions.balance(acct) if total > balance: return req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (total, balance)) accounts = Irc.account_names([target_nick(target) for target in targets]) totip = {} failed = "" tipped = "" for i in range(len(targets)): if accounts[i] == None: failed += " %s (offline)" % (target_nick(targets[i])) elif accounts[i] == False: failed += " %s (unidentified)" % (target_nick(targets[i])) elif not target_verify(targets[i], accounts[i]): failed += " %s (mismatch)" % (targets[i]) else: totip[accounts[i]] = totip.get(accounts[i], 0) + amounts[i] tipped += " %s %d" % (target_nick(targets[i]), amounts[i]) token = Logger.token() try: Transactions.tip_multiple(token, acct, totip) tipped += " [%s]" % (token) except Transactions.NotEnoughMoney: return req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (total, Transactions.balance(acct))) output = "Tipped:" + tipped if len(failed): output += " Failed:" + failed req.reply(output)
def mtip(req, arg): """%mtip <targ1> <amt1> [<targ2> <amt2> ...] - Send multiple tips at once""" if not len(arg) or len(arg) % 2: return req.reply("%mtip <targ1> <amt1> [<targ2> <amt2> ...]") acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") for i in range(0, len(arg), 2): try: if int(arg[i + 1]) <= 0: raise ValueError() except ValueError as e: req.reply_private(repr(arg[i + 1]) + " - invalid amount") return None targets = [] amounts = [] total = 0 for i in range(0, len(arg), 2): target = arg[i] amount = int(arg[i + 1]) amount = min(amount, 1000000000000) found = False for i in range(len(targets)): if Irc.equal_nicks(targets[i], target): amounts[i] += amount total += amount found = True break if not found: targets.append(target) amounts.append(amount) total += amount balance = Transactions.balance(acct) if total > balance: return req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (total, balance)) accounts = Irc.account_names(targets) totip = {} failed = "" tipped = "" for i in range(len(targets)): if accounts[i]: totip[accounts[i]] = amounts[i] tipped += " %s %d" % (targets[i], amounts[i]) elif accounts[i] == None: failed += " %s (offline)" % (targets[i]) else: failed += " %s (unidentified)" % (targets[i]) with Logger.token() as token: try: Transactions.tip_multiple(acct, totip) token.log("t", "acct:%s mtipped: %s" % (acct, repr(totip))) tipped += " [%s]" % (token.id) except Transactions.NotEnoughMoney: return req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (total, Transactions.balance(acct))) output = "Tipped:" + tipped if len(failed): output += " Failed:" + failed req.reply(output)
def loadHavelockFile(self, filename): f = open(filename, "r") raw = f.read() f.close() transactions = Transactions() for line in raw.split("\n"): transactions.addTransaction(line) self.loadTransactions(transactions)
class TkinterCalendar(calendar.Calendar): def __init__(self, root, user, firstweekday=0): self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday self.date_clicked = None self.root = root self.transaction = Transactions(user, self.root) self.transaction_dates = [] def formatmonth(self, root, year, month): self.transaction_dates = self.transaction.get_datesof_transactions() dates = self.monthdatescalendar(year, month) frame = Frame(root, bg="white") labels = [] for r, week in enumerate(dates): labels_row = [] for c, date in enumerate(week): text = date.strftime('%d') text2 = date.strftime('%Y/%m/%d') date_btn = customButton(frame, text=text, tag=text2, bg="white", fg="black") date_btn.config( command=lambda btn=date_btn: self.generate_day_info(btn)) date_btn.grid(row=r, column=c, ipadx=17, ipady=10) if date.month != month: date_btn['bg'] = '#aaa' date_btn.config(state='disabled') date_btn.grid_forget() if date.day == datetime.datetime.now( ).day and date.month == datetime.datetime.now().month: self.date_clicked = date_btn date_btn.invoke() if c == 6: date_btn['fg'] = 'red' if date_btn.tag in self.transaction_dates: date_btn['fg'] = "orange" labels_row.append(date_btn) labels.append(labels_row) return frame def generate_day_info(self, btn): self.date_clicked["bg"] = "white" self.date_clicked = btn self.date_clicked["bg"] = "#2C9BD2" self.transaction.date = self.date_clicked.tag self.transaction.date_btn = btn self.transaction.display_transaction_section()
def __init__(self, conf): self.conf = conf self.apiKey = self.conf.hl_api_key self.currentPrices = {} self.transactions = Transactions() self.portfolio = Portfolio(self.conf.epsilon) self.havelockBalance = None self.havelockBalanceAvailable = None # (timestamps) api calls, last 600s self.apiRate = []
def balance(req, _): """%balance - Displays your confirmed and unconfirmed balance""" acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") confirmed = Transactions.balance(acct) pending = Transactions.balance_unconfirmed(acct) if pending: req.reply("Your balance is Ɖ%i (+Ɖ%i unconfirmed)" % (confirmed, pending)) else: req.reply("Your balance is Ɖ%i" % (confirmed))
def process_IN_CREATE(self, event): try: with blocklock: Transactions.notify_block() except Exception as e: type, value, tb = sys.exc_info() Logger.log("te", "ERROR in blocknotify") Logger.log("te", repr(e)) Logger.log("te", "".join(traceback.format_tb(tb))) try: os.remove(os.path.join(event.path, event.name)) except: pass
def Terminal(): print('-' * 70) command = input('[+]COMMAND:') if command == "send": transactions.SendBTC().GetTXInfo() else: Terminal()
def sendCoins(pu_send, amt_send, pr_send, pu_recv, amt_recv, miner_list): newTx = Transactions.Tx() newTx.add_input(pu_send, amt_send) newTx.add_output(pu_recv, amt_recv) newTx.sign(pr_send) SocketUtils.sendObj('localhost', newTx) return True
def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.tran = Transactions() self.load_table(self.tran.expense_transactions) self.show()
def nonceFinder(wallet_list,miner_public): # Add txs to block global break_now while not break_now: newBlock = TxBlock.TxBlock([],findLongestBlockchain()) for tx in tx_list: newBlock.addTx(tx) # Compute and add mining reward total_in,total_out = newBlock.count_totals() mine_reward = Transactions.Tx() mine_reward.add_output(miner_public,25.0+total_in-total_out) newBlock.addTx(mine_reward) # Find nonce print ("Finding Nonce...") newBlock.find_nonce(10000) if newBlock.good_nonce(): print ("Good nonce found") # Send new block for ip_addr,port in wallet_list: print ("Sending to " + ip_addr + ":" + str(port)) Socketutil.sendObj(ip_addr,newBlock,5006) head_blocks.remove(newBlock.previousBlock) head_blocks.append(newBlock) break return True
def nonceFinder(wallet_list, miner_public): global break_now # add Txs to new block while not break_now: newBlock = TxBlock.TxBlock(TxBlock.findLongestBlockchain(head_blocks)) for tx in tx_list: newBlock.addTx(tx) # Compute and add mining reward total_in, total_out = newBlock.count_totals() mine_reward = Transactions.Tx() mine_reward.add_output(miner_public, 25.0 + total_in - total_out) newBlock.addTx(mine_reward) # Find nonce if verbose: print("Finding Nonce...") newBlock.find_nonce(10000) if newBlock.good_nonce(): if verbose: print("Good nonce found") head_blocks.remove(newBlock.previousBlock) head_blocks.append(newBlock) # Send new block savePrev = newBlock.previousBlock newBlock.previousBlock = None for ip_addr, port in wallet_list: if verbose: print("Sending to " + ip_addr + ":" + str(port)) SocketUtils.sendObj(ip_addr, newBlock, 5006) newBlock.previousBlock = savePrev # Remove used txs from tx_list for tx in newBlock.data: if tx != mine_reward: tx_list.remove(tx) return True
def bump_check(ilike): db = Transactions.database() cur = db.cursor() cur.execute( "UPDATE accounts SET last_check = EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) WHERE account ILIKE %s", (ilike, )) db.commit()
def expirer(event): try: while not event.is_set(): cur = Transactions.database().cursor() cur.execute( "SELECT account FROM accounts WHERE (((last_seen < EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - interval '10 weeks')) IS NOT FALSE AND (last_check < EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - interval '6 hours')) IS NOT FALSE) OR ((last_seen > EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - interval '10 weeks')) IS NOT FALSE AND (last_check < EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - interval '1 week')) IS NOT FALSE)) AND NOT EXISTS (SELECT * FROM locked WHERE locked.account = accounts.account) AND account NOT LIKE '@%' ORDER BY COALESCE(last_check, 0) ASC, balance DESC LIMIT 1" ) if cur.rowcount and Config.config["svs"] in Global.instances: Irc.instance_send( Config.config["svs"], ("NS", "INFO " + Irc.sanitize_nickname(cur.fetchone()[0]))) if not event.is_set(): time.sleep(10) if not event.is_set(): time.sleep(10) if not event.is_set(): time.sleep(5) except Exception as e: type, value, tb = sys.exc_info() Logger.log("te", "ERROR in expirer") Logger.log("te", repr(e)) Logger.log("te", "".join(traceback.format_tb(tb))) Logger.irclog("Error in expirer: %s" % (repr(e))) Logger.irclog("".join(traceback.format_tb(tb)).replace("\n", " || ")) del tb Global.svsevent.set() for instance in Global.instances: Global.instances[instance].expirer_dead.set()
def nonceFinder(wallet_list, miner_public): global break_now global head_blocks # add Txs to new block try: head_blocks = TxBlock.loadBlocks("AllBlocks.dat") except: head_blocks = TxBlock.loadBlocks("GenesisBlock.dat") while not break_now: newBlock = TxBlock.TxBlock(TxBlock.findLongestBlockchain(head_blocks)) tmp = Transactions.Tx() tmp.add_output(miner_public, 25.0) newBlock.addTx(tmp) for tx in tx_list: newBlock.addTx(tx) if not newBlock.check_size(): newBlock.removeTx(tx) break newBlock.removeTx(tmp) # Compute and add mining reward total_in, total_out = newBlock.count_totals() mine_reward = Transactions.Tx() mine_reward.add_output(miner_public, 25.0 + total_in - total_out) newBlock.addTx(mine_reward) # Find nonce if verbose: print("Finding Nonce...") newBlock.find_nonce(10000) if newBlock.good_nonce(): if verbose: print("Good nonce found") if not newBlock.previousBlock in head_blocks: break head_blocks.remove(newBlock.previousBlock) head_blocks.append(newBlock) # Send new block savePrev = newBlock.previousBlock newBlock.previousBlock = None for ip_addr, port in wallet_list: if verbose: print("Sending to " + ip_addr + ":" + str(port)) SocketUtils.sendObj(ip_addr, newBlock, port) newBlock.previousBlock = savePrev # Remove used txs from tx_list for tx in newBlock.data: if tx != mine_reward: tx_list.remove(tx) TxBlock.saveBlocks(head_blocks, "AllBlocks.dat") return True
def nonceFinder(wallet_list, miner_public): global break_now try: head_blocks = TxBlock.loadBlocks("AllBlocks.dat") except: print("No previous blocks found. Starting fresh.") head_blocks = [None] # add Txs to new block while not break_now: newBlock = TxBlock.TxBlock(TxBlock.findLongestBlockchain(head_blocks)) placeholder = Transactions.Tx() placeholder.add_output(miner_public,25.0) newBlock.addTx(placeholder) #sort tx_list by tx fee per byte for tx in tx_list: newBlock.addTx(tx) if not newBlock.check_size(): newBlock.removeTx(tx) break newBlock.removeTx(placeholder) if verbose: print("new Block has " + str(len(newBlock.data)) + "txs.") # Compute and add mining reward total_in,total_out = newBlock.count_totals() mine_reward = Transactions.Tx() mine_reward.add_output(miner_public,25.0+total_in-total_out) newBlock.addTx(mine_reward) # Find nonce if verbose: print ("Finding Nonce...") newBlock.find_nonce(10000) if newBlock.good_nonce(): if verbose: print ("Good nonce found") head_blocks.remove(newBlock.previousBlock) head_blocks.append(newBlock) # Send new block savePrev = newBlock.previousBlock newBlock.previousBlock = None for ip_addr,port in wallet_list: if verbose: print ("Sending to " + ip_addr + ":" + str(port)) SocketUtils.sendObj(ip_addr,newBlock,5006) newBlock.previousBlock = savePrev # Remove used txs from tx_list for tx in newBlock.data: if tx != mine_reward: tx_list.remove(tx) TxBlock.saveBlocks(head_blocks,"AllBlocks.dat") return True
def bump_last(ilike, t=None): if t == None: t = int(time.time()) db = Transactions.database() cur = db.cursor() cur.execute("UPDATE accounts SET last_seen = %s WHERE account ILIKE %s", (t, ilike)) db.commit()
def loadBitcoinFile(self, filename): f = open(filename, "r") raw = f.read() f.close() transactions = Transactions() ts = [] for line in raw.split("\n"): if not line: continue b = BitcoinTransaction() if b.parse(line): ts.append(b) transactions.addTransactions(ts) self.loadTransactions(transactions)
def deposit(req, _): """%deposit - Displays your deposit address""" acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") req.reply_private( "To deposit, send coins to %s (transactions will be credited after %d confirmations)" % (Transactions.deposit_address(acct), Config.config["confirmations"]) )
def deposit(req, _): """%deposit - Displays your deposit address""" acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private( "You are not identified with freenode services (see /msg NickServ help)" ) req.reply_private( "To deposit, send coins to %s (transactions will be credited after %d confirmations)" % (Transactions.deposit_address(acct), Config.config["confirmations"]))
def donate(req, arg): """%donate <amount> - Donate 'amount' coins to help fund the server Doger is running on""" if len(arg) < 1: return req.reply(gethelp("donate")) acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if Transactions.lock(acct): return req.reply_private("Your account is currently locked") toacct = "@DONATIONS" try: amount = parse_amount(arg[0], acct) except ValueError as e: return req.reply_private(str(e)) token = Logger.token() try: Transactions.tip(token, acct, toacct, amount) req.reply("Donated Ɖ%i, thank you very much for your donation [%s]" % (amount, token)) except Transactions.NotEnoughMoney: req.reply_private("You tried to donate Ɖ%i but you only have Ɖ%i" % (amount, Transactions.balance(acct)))
def sendCoins(pu_send, amt_send, pr_send, pu_recv, amt_recv): global tx_index newTx = Transactions.Tx() if not pu_send in tx_index: tx_index[pu_send] = 0 newTx.add_input(pu_send, amt_send, tx_index[pu_send]) newTx.add_output(pu_recv, amt_recv) newTx.sign(pr_send) for ip, port in miners: SocketUtils.sendObj(ip, newTx, port) tx_index[pu_send] = tx_index[pu_send] + 1 return True
def donate(req, arg): if len(arg) < 1: return req.reply("%donate <amount>") acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") toacct = "@DONATIONS" try: amount = int(arg[0]) if amount <= 0: raise ValueError() amount = min(amount, 1000000000000) except ValueError as e: req.reply_private(repr(arg[0]) + " - invalid amount") return None with Logger.token() as token: try: Transactions.tip(acct, toacct, amount) token.log("t", "acct:%s tipped %d to acct:%s(%d)" % (acct, amount, toacct, Transactions.balance(toacct))) req.reply("Done [%s]" % (token.id)) except Transactions.NotEnoughMoney: req.reply_private("You tried to donate Ɖ%i but you only have Ɖ%i" % (amount, Transactions.balance(acct)))
def processTrainData(): train = readData(filepath) # Merge all datasets members = Members.getProcessedData() training = pd.merge(left=train, right=members, how='left', on=['msno']) training = Members.imputeMissingValues(training) del members transactions = Transactions.getProcessedData() training = pd.merge(left=training, right=transactions, how='left', on=['msno']) training = Transactions.imputeMissingValues(training) del transactions user_logs = Preprocessing_user_logs.getProcessedDataForTrain() training = pd.merge(left=training, right=user_logs, how='left', on=['msno']) del user_logs del training['Unnamed: 0'] training = training.drop_duplicates(keep="first") training = training.dropna() writeData(training)
def processTestData(): test = readData(filepath) # Merge all datasets members = Members.getProcessedData() test_dataset = pd.merge(left=test, right=members, how='left', on=['msno']) test_dataset = Members.imputeMissingValues(test_dataset) del members transactions = Transactions.getProcessedData() test_dataset = pd.merge(left=test_dataset, right=transactions, how='left', on=['msno']) test_dataset = Transactions.imputeMissingValues(test_dataset) del transactions user_logs = Preprocessing_user_logs.getProcessedDataForTest() test_dataset = pd.merge(left=test_dataset, right=user_logs, how='left', on=['msno']) del user_logs del test_dataset['Unnamed: 0'] test_dataset = test_dataset.drop_duplicates(keep="first") test_dataset = test_dataset.dropna() writeData(test_dataset)
def getData(self, sym): s = self.portfolio.symbols[sym] ts = s.getTimestamps() ret = [] for t in ts: tes = s.getTransactions(end=t) allTrans = Transactions() allTrans.addTransactions(tes) buys = allTrans.getBuyAmount() sells = allTrans.getSellAmount() dividend = allTrans.getDividendAmount() try: val = allTrans.getShareQuantity() * self.currentPrices[sym] except: val = allTrans.getShareQuantity() * s.getMeanPrice() ret.append((t, val + dividend + sells - buys)) return ret
def svsdata(data): db = Transactions.database() cur = db.cursor() ilike = data["nick"].replace("\\", "\\\\").replace("_", "\\_") cur.execute( "SELECT account, last_seen, registered FROM accounts WHERE account ILIKE %s", (ilike, )) if cur.rowcount: acct, last_seen, registered = cur.fetchone() bump_check(ilike) if "reg" not in data: Logger.irclog("Dormant lock on account %s: not registered" % (acct)) Transactions.lock(acct, True) elif registered != None and registered != data["reg"]: Logger.irclog( "Dormant lock on account %s: registered at %d, remember %d" % (acct, data["reg"], registered)) Transactions.lock(acct, True) else: if registered == None: cur.execute( "SELECT MAX(timestamp) FROM txlog WHERE destination ILIKE %s", (ilike, )) lasttx = cur.fetchone()[0] if cur.rowcount else None if lasttx != None and lasttx < data["reg"]: Logger.irclog( "Dormant lock on account %s: registered at %d, last tx at %d" % (acct, data["reg"], lasttx)) Transactions.lock(acct, True) else: cur.execute( "UPDATE accounts SET registered = %s WHERE account ILIKE %s", (data["reg"], ilike)) db.commit() if "userlast" in data: bump_last(ilike, data["userlast"]) elif "last" in data: bump_last(ilike, data["last"]) elif "userlastweeks" in data: bump_last( ilike, int(time.time()) - (data["userlastweeks"] + 1) * 86400 * 7 - 60) elif "lastweeks" in data: bump_last( ilike, int(time.time()) - (data["lastweeks"] + 1) * 86400 * 7 - 60)
def parse_amount(s, acct, all_offset = 0): if s.lower() == "all": return max(Transactions.balance(acct) + all_offset, 1) else: try: amount = float(s) if math.isnan(amount): raise ValueError except ValueError: raise ValueError(repr(s) + " - invalid amount") if amount > 1e12: raise ValueError(repr(s) + " - invalid amount (value too large)") if amount <= 0: raise ValueError(repr(s) + " - invalid amount (should be 1 or more)") if not int(amount) == amount: raise ValueError(repr(s) + " - invalid amount (should be integer)") return int(amount)
def getActivity(self): # get all timestamps where something happens ts = self.transactions.getTimestamps() ret = [] for t in ts: trans = self.transactions.getTransactions(end=t) allTrans = Transactions() allTrans.addTransactions(trans) bal = allTrans.getBalance() dep = allTrans.getDepositAmount() wit = allTrans.getWithdrawAmount() portfolio = Portfolio(self.conf.epsilon) prices = {} for s in allTrans.getSymbols(): portfolio.addTransactions(allTrans.getTransactions(symbol=s), s) prices[s] = portfolio.symbols[s].getLastPrice() portfolio.setCurrentPrices(prices) val = portfolio.getCurrentValue() ret.append((t, bal + val + wit - dep)) return ret
def getData(self, sym): s = self.portfolio.symbols[sym] ts = s.getTimestamps() ret = [] for t in ts: tes = s.getTransactions(end=t) allTrans = Transactions() allTrans.addTransactions(tes) buys = allTrans.getBuyAmount() sells = allTrans.getSellAmount() dividend = allTrans.getDividendAmount() try: val = allTrans.getShareQuantity() * self.currentPrices[sym] except: val = allTrans.getShareQuantity() * s.getMeanPrice() ret.append((t, val+dividend+sells-buys)) return ret
def getActivity(self): # get all timestamps where something happens ts = self.transactions.getTimestamps() ret = [] for t in ts: trans = self.transactions.getTransactions(end=t) allTrans = Transactions() allTrans.addTransactions(trans) bal = allTrans.getBalance() dep = allTrans.getDepositAmount() wit = allTrans.getWithdrawAmount() portfolio = Portfolio(self.conf.epsilon) prices = {} for s in allTrans.getSymbols(): portfolio.addTransactions(allTrans.getTransactions(symbol=s), s) prices[s] = portfolio.symbols[s].getLastPrice() portfolio.setCurrentPrices(prices) val = portfolio.getCurrentValue() ret.append((t, bal+val+wit-dep)) return ret
class Havelock: def __init__(self, conf): self.conf = conf self.apiKey = self.conf.hl_api_key self.currentPrices = {} self.transactions = Transactions() self.portfolio = Portfolio(self.conf.epsilon) self.havelockBalance = None self.havelockBalanceAvailable = None # (timestamps) api calls, last 600s self.apiRate = [] def checkApiRate(self, nosleep=False, apirate=None): debug = self.conf.debug apirate = apirate or 0 time_window = 600.0 max_calls = 300 self.apiRate.append(time.time()) self.apiRate = [x for x in self.apiRate if x > (time.time() - time_window)] if len(self.apiRate) < 2: return diff = self.apiRate[-1] - self.apiRate[0] calls_in_window = max(apirate, len(self.apiRate)) avg_rate = diff / time_window max_rate = max_calls / time_window cur_rate = (calls_in_window / time_window) / max_rate # exponential sleep scaling ex = 1.5 scale = 1 + log(1, ex) sleep_time = max(0.0, (1.0/max_rate) * ((1+log(cur_rate, ex)) / scale)) if sleep_time > 0.0 and not nosleep: time.sleep(sleep_time) if debug: print ("api-calls: {:>3d} in time window - rate calculated: " + "{:.2%} reported: {:.2%} - sleep: {:>4d}msecs"). \ format(len(self.apiRate), avg_rate, cur_rate, int(sleep_time*1000)) return {"sleep_time": sleep_time, "avg_rate": avg_rate, "cur_rate": cur_rate, "max_rate": max_rate, "remaining": max_calls - calls_in_window} def fetchData(self, dataType, post=None): debug = self.conf.debug payload = {} # use post to update the payload if post is not None: assert isinstance(post, dict), "'post' arg must be an dict" payload.update(post) url = "https://www.havelockinvestments.com/r/{:s}".format(dataType) if dataType == "portfolio" or "balance": payload["key"] = self.apiKey elif dataType.startswith("orderbook"): assert "symbol" in post elif dataType == "ordercreate": payload['key'] = self.apiKey elif dataType == "ordercancel": payload['key'] = self.apiKey elif dataType == "orders": payload['key'] = self.apiKey elif dataType == "transactions": payload['key'] = self.apiKey payload["limit"] = 300 # add sinceid to payload else: print "data Type not known!" return None if debug: print "Send hl API - type: {} payload: {}". \ format(dataType, " ".join("{}: {}". \ format(k,v) for k,v in payload.items())) try: r = requests.post(url, data=payload) j = json.loads(r.text) apirate = int(j["apirate"]) if "apirate" in j else 0 rate_data = self.checkApiRate(nosleep=False, apirate=apirate) # include rate data in output j["rate_data"] = rate_data if j["status"] == "error": print "Havelock - API error message: ", j["message"] if j["status"] != "ok": print "failed to fetch data ({})".format(dataType) return None except requests.exceptions.ConnectionError: print "failed to resolve havelockinvestments.com!" return None except ValueError: print "failed to get data from havelock" return None return j def fetchOrderbook(self, symbol, full=False): """ get orderbook """ dtype = "orderbookfull" if full else "orderbook" j = self.fetchData(dtype, {"symbol": symbol}) if j is None: return None return j["asks"], j["bids"] def fetchOrders(self): """ fetch open orders """ j = self.fetchData("orders") if j is None: return None return j["orders"] def createOrder(self, symbol, action, price, units): """ create new order """ assert action in ["buy", "sell"] d = {"symbol": symbol, "action": action, "price": price, "units": units} j = self.fetchData("ordercreate", d) return j def cancelOrder(self, order_id): """ cancel order """ d = {"id": order_id} j = self.fetchData("ordercancel", d) return j is not None def fetchPortfolio(self): """ get portfolio """ j = self.fetchData("portfolio") if j is None: return None portfolio = j["portfolio"] ts = time.time() for d in portfolio: self.currentPrices[d["symbol"]] = float(d["lastprice"]) if not __debug__: print "fetched lastprice {} for symbol {}".format( (self.currentPrices[d["symbol"]], d["symbol"])) self.portfolio.setCurrentPrices(self.currentPrices) def fetchBalance(self): """ get balance """ j = self.fetchData("balance") if j is None: return None balance = j["balance"] self.havelockBalance = float(balance["balance"]) self.havelockBalanceAvailable = float(balance["balanceavailable"]) #print "havelock balance: {:f} BTC".format(self.havelockBalance) def fetchTransactions(self): """ get history """ j = self.fetchData("transactions") if j is None: return None transactions = j["transactions"] ts = [] for tr in transactions: t = Transaction() if t.parse(tr): ts.append(t) self.mergeTransactions(ts) def loadTransactionFile(self, filename): f = open(filename, "r") raw = f.read() f.close() # first havelock transaction file load is in wrong order lines = raw.split("\n") try: first = lines[1].split(",")[0] first = int(time.mktime(datetime.datetime.strptime(first, "%Y-%m-%d %H:%M:%S").timetuple())) last = lines[-2].split(",")[0] last = int(time.mktime(datetime.datetime.strptime(last, "%Y-%m-%d %H:%M:%S").timetuple())) if first > last: lines.reverse() except: pass for line in lines: self.transactions.addTransaction(line) self.buildPortfolio() def buildPortfolio(self): for s in self.transactions.getSymbols(): self.portfolio.addTransactions(self.transactions.getTransactions(symbol=s), s) def setStartDate(self, timestamp): self.transactions.setStartDate(timestamp) for s in self.portfolio.getSymbols().values(): s.setStartDate(timestamp) def setEndDate(self, timestamp): self.transactions.setEndDate(timestamp) for s in self.portfolio.getSymbols().values(): s.setEndDate(timestamp) def getBalance(self, includePortfolio=True): if self.havelockBalance is None: bal = self.calculateBalance(includePortfolio) else: bal = self.havelockBalanceAvailable#+self.havelockBalance if not includePortfolio: return bal por = self.portfolio.getCurrentValue() return (bal+por) def calculateBalance(self, includePortfolio=True): bal = self.transactions.getBalance() if not includePortfolio: return bal por = self.portfolio.getCurrentValue() return (bal+por) def mergeTransactionFile(self, filename): f = open(filename) content = f.read() f.close() ts = [] for tr in content.split("\n"): t = Transaction() if t.parse(tr): ts.append(t) self.mergeTransactions(ts) def mergeTransactions(self, transactions): cnt = 0 for t in transactions: if self.insertTransaction(t): cnt += 1 self.transactions.sortTransactions() self.portfolio.sortTransactions() if cnt > 0: print "merge {:d} new transactions".format(cnt) def insertTransaction(self, transaction): if not transaction in self.transactions: self.transactions.addTransactions([transaction]) self.portfolio.addTransactions([transaction], transaction.getSymbol()) return True return False def printDetails(self, full=True, btc2eur=None): btc2eur = btc2eur or 1.0 print "Havelock Account Details:" print "-" * get_console_size()["width"] wit = self.transactions.getWithdrawAmount() dep = self.transactions.getDepositAmount() if full: print "total buys: {:>20d} shares".format( self.transactions.getBuyQuantity()) print "total sells: {:>20d} shares".format( self.transactions.getSellQuantity()) print "total dividend received: {:>20f} BTC".format( self.transactions.getDividendAmount()) print "total withdraw: {:>20f} BTC".format(wit) print "total deposit: {:>20f} BTC".format(dep) print "total fees: {:>20f} BTC".format( self.transactions.getFeeAmount()) print "-" * get_console_size()["width"] self.printPortfolio(btc2eur=btc2eur) print "-" * get_console_size()["width"] bal = self.getBalance(includePortfolio=False) print "{:<30s} | {:>26f} BTC | {:>25.2f} EUR |".format("current balance: ", bal, bal*btc2eur) por = self.portfolio.getCurrentValue() print "{:<30s} | {:>26f} BTC | {:>25.2f} EUR |".format("portfolio value: ", por, por*btc2eur) print "{:<30s} | {:>26f} BTC | {:>25.2f} EUR |".format("total deposit: ", dep-wit, (dep-wit)*btc2eur) summ = wit + por + bal - dep print "{:<30s} | {:>26f} BTC | {:>25.2f} EUR |".format("in sum: ", summ, summ*btc2eur) print "-" * get_console_size()["width"] def printPortfolio(self, btc2eur=None, allSymbols=True): p = self.portfolio console_width = get_console_size()["width"] print "Your Portfolio:" print "-" * console_width fmts = [".2f", "s", "s", ".3f", ".5f", ".5f", ".3f"] header = ["Trend (%)", "Buys (Price)", "", "Market (B)", "Divs (B)", "Mean (B)", "Win (B)"] fmts2 = [".2f", "s", "d", ".3f", ".5f", ".5f", ".2f"] header2 = ["Overall (%)", "Sells (Price)", "Sum", "Book (B)", "Fee (B)", "Cur (B)", "Win (E)"] colwidth = (console_width / len(header)) - 3 fill = " | " print fill.join("{:>{}s}".format(h, colwidth) \ for f, h in zip(fmts, header)) print fill.join("{:>{}s}".format(h, colwidth) \ for f, h in zip(fmts, header2)) return for s in self.portfolio.symbols: t = p.symbols[s] if not allSymbols and t.getShareQuantity() == 0: continue print "-" * console_width _s = "{1:-^{0}}".format(console_width, "> " + s + " <") print _s[console_width/5:] + _s[:console_width/5] buy = "{:d} ({:f})".format(t.getBuyQuantity(), t.getMeanBuyPrice()) data = [p.getTrend(s), buy, "", p.getCurrentValue(s), t.getDividendAmount(), t.getMeanPrice(), p.getCurrentWin(s) ] sell = "{:d} ({:f})".format(t.getSellQuantity(), t.getMeanSellPrice()) data2 = [p.getOverallTrend(s), sell, t.getShareQuantity(), p.getBookValue(s), t.getFeeAmount(), p.getCurrentPrice(s), p.getCurrentWin(s) * btc2eur] print fill.join("{0:>{1}{2}}".format(d, colwidth, f) \ for f, d in zip(fmts, data)) print fill.join("{0:>{1}{2}}".format(d, colwidth, f) \ for f, d in zip(fmts2, data2)) def plain(self): p = self.portfolio for s in self.portfolio.symbols: t = p.getSymbol(s) print "[{:s}]\nshares:{:d},value:{:0.3f},rate:{:0.6f},trend:{:0.2f}".format(t.getName(), t.getShareQuantity(), p.getCurrentValue(s), p.getCurrentPrice(s), p.getTrend(s)) wit = self.transactions.getWithdrawAmount() dep = self.transactions.getDepositAmount() bal = self.getBalance(includePortfolio=False) por = self.portfolio.getCurrentValue() summ = wit + por + bal - dep print "[Havelock]\nsum:{:0.5f}".format(summ) def store(self, filename): content = "{:s}\n".format(Transaction().getHeader()) for t in self.transactions.transactions: content += "{:s}\n".format(t) f = open(filename, "w") f.write(content) f.close() def getData(self, sym): s = self.portfolio.symbols[sym] ts = s.getTimestamps() ret = [] for t in ts: tes = s.getTransactions(end=t) allTrans = Transactions() allTrans.addTransactions(tes) buys = allTrans.getBuyAmount() sells = allTrans.getSellAmount() dividend = allTrans.getDividendAmount() try: val = allTrans.getShareQuantity() * self.currentPrices[sym] except: val = allTrans.getShareQuantity() * s.getMeanPrice() ret.append((t, val+dividend+sells-buys)) return ret def getActivity(self): # get all timestamps where something happens ts = self.transactions.getTimestamps() ret = [] for t in ts: trans = self.transactions.getTransactions(end=t) allTrans = Transactions() allTrans.addTransactions(trans) bal = allTrans.getBalance() dep = allTrans.getDepositAmount() wit = allTrans.getWithdrawAmount() portfolio = Portfolio(self.conf.epsilon) prices = {} for s in allTrans.getSymbols(): portfolio.addTransactions(allTrans.getTransactions(symbol=s), s) prices[s] = portfolio.symbols[s].getLastPrice() portfolio.setCurrentPrices(prices) val = portfolio.getCurrentValue() ret.append((t, bal+val+wit-dep)) return ret
def mtip(req, arg): """%mtip <targ1> <amt1> [<targ2> <amt2> ...] - Send multiple tips at once""" if not len(arg) or len(arg) % 2: return req.reply(gethelp("mtip")) acct = Irc.account_names([req.nick])[0] if not acct: return req.reply_private("You are not identified with freenode services (see /msg NickServ help)") if Transactions.lock(acct): return req.reply_private("Your account is currently locked") for i in range(0, len(arg), 2): if arg[i + 1] == "all": arg[i + 1] = str(Transactions.balance(acct)) try: amount = float(arg[i + 1]) if math.isnan(amount): raise ValueError except ValueError as e: return req.reply_private(repr(arg[i + 1]) + " - invalid amount") if amount > 1e12: return req.reply_private(repr(arg[i + 1]) + " - invalid amount (value too large)") if amount < 1: return req.reply_private(repr(arg[i + 1]) + " - invalid amount (should be 1 or more)") if not int(amount) == amount: return req.reply_private(repr(arg[i + 1]) + " - invalid amount (should be integer)") targets = [] amounts = [] total = 0 for i in range(0, len(arg), 2): target = arg[i] amount = int(float(arg[i + 1])) found = False for i in range(len(targets)): if Irc.equal_nicks(targets[i], target): amounts[i] += amount total += amount found = True break if not found: targets.append(target) amounts.append(amount) total += amount balance = Transactions.balance(acct) if total > balance: return req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (total, balance)) accounts = Irc.account_names(targets) totip = {} failed = "" tipped = "" for i in range(len(targets)): if accounts[i]: totip[accounts[i]] = amounts[i] tipped += " %s %d" % (targets[i], amounts[i]) elif accounts[i] == None: failed += " %s (offline)" % (targets[i]) else: failed += " %s (unidentified)" % (targets[i]) token = Logger.token() try: Transactions.tip_multiple(token, acct, totip) tipped += " [%s]" % (token) except Transactions.NotEnoughMoney: return req.reply_private("You tried to tip Ɖ%i but you only have Ɖ%i" % (total, Transactions.balance(acct))) output = "Tipped:" + tipped if len(failed): output += " Failed:" + failed req.reply(output)
def admin(req, arg): """ admin""" if len(arg): command = arg[0] arg = arg[1:] if command == "reload": for mod in arg: reload(sys.modules[mod]) req.reply("Reloaded") elif command == "exec" and Config.config.get("enable_exec", None): exec(" ".join(arg).replace("$", "\n")) elif command == "ignore": Irc.ignore(arg[0], int(arg[1])) req.reply("Ignored") elif command == "die": for instance in Global.instances: Global.manager_queue.put(("Disconnect", instance)) Global.manager_queue.join() Blocknotify.stop() Global.manager_queue.put(("Die",)) elif command == "restart": for instance in Global.instances: Global.manager_queue.put(("Disconnect", instance)) Global.manager_queue.join() Blocknotify.stop() os.execv(sys.executable, [sys.executable] + sys.argv) elif command == "manager": for cmd in arg: Global.manager_queue.put(cmd.split("$")) req.reply("Sent") elif command == "raw": Irc.instance_send(req.instance, eval(" ".join(arg))) elif command == "config": if arg[0] == "save": os.rename("Config.py", "Config.py.bak") with open("Config.py", "w") as f: f.write("config = " + pprint.pformat(Config.config) + "\n") req.reply("Done") elif arg[0] == "del": exec("del Config.config " + " ".join(arg[1:])) req.reply("Done") else: try: req.reply(repr(eval("Config.config " + " ".join(arg)))) except SyntaxError: exec("Config.config " + " ".join(arg)) req.reply("Done") elif command == "join": Irc.instance_send(req.instance, ("JOIN", arg[0]), priority = 0.1) elif command == "part": Irc.instance_send(req.instance, ("PART", arg[0]), priority = 0.1) elif command == "caches": acsize = 0 accached = 0 with Global.account_lock: for channel in Global.account_cache: for user in Global.account_cache[channel]: acsize += 1 if Global.account_cache[channel][user] != None: accached += 1 acchannels = len(Global.account_cache) whois = " OK" whoisok = True for instance in Global.instances: tasks = Global.instances[instance].whois_queue.unfinished_tasks if tasks: if whoisok: whois = "" whoisok = False whois += " %s:%d!" % (instance, tasks) req.reply("Account caches: %d user-channels (%d cached) in %d channels; Whois queues:%s" % (acsize, accached, acchannels, whois)) elif command == "channels": inss = "" for instance in Global.instances: chans = [] with Global.account_lock: for channel in Global.account_cache: if instance in Global.account_cache[channel]: chans.append(channel) inss += " %s:%s" % (instance, ",".join(chans)) req.reply("Instances:" + inss) elif command == "balances": database, dogecoind = Transactions.balances() req.reply("Dogecoind: %.8f; Database: %.8f" % (dogecoind, database)) elif command == "blocks": info, hashd = Transactions.get_info() hashb = Transactions.lastblock req.reply("Best block: " + hashd + ", Last tx block: " + hashb + ", Blocks: " + str(info.blocks) + ", Testnet: " + str(info.testnet)) elif command == "lock": if len(arg) > 1: if arg[1] == "on": Transactions.lock(arg[0], True) elif arg[1] == "off": Transactions.lock(arg[0], False) req.reply("Done") elif len(arg): req.reply("locked" if Transactions.lock(arg[0]) else "not locked")