def create_invoice_user (email):
	cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
	cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM user WHERE email = %s AND active = 1", (email))
	result = False
	for row in cur.fetchall():
		result = row
	if result:
		if result['masterpubkey_btc'][0:4] == "xpub":
			# BIP44
			dpk1 = bitcoin.bip32_ckd(result['masterpubkey_btc'], 0)
			dpk2 = bitcoin.bip32_ckd(dpk1, result['offset_btc'])
			pubkey = bitcoin.bip32_extract_key(dpk2)
		else:
			# Electrum 1.x
			pubkey = bitcoin.electrum_pubkey(result['masterpubkey_btc'], result['offset_btc'])
		address = bitcoin.pubkey_to_address(pubkey)
		bitcoind_importaddress(address)
		cur.execute ("UPDATE user SET offset_btc = offset_btc + 1 WHERE email = %s AND active = 1 AND masterpubkey_btc = %s", (email, result['masterpubkey_btc']))
		if result['feecurrency'] in ("USD", "GBP", "EUR"):
			result['feeamount'] /= decimal.Decimal(get_bitcoin_price(result['feecurrency']))
		cur.execute ("INSERT INTO invoice (issuer, address, coin, amount, type, paid) VALUES (%s, %s, 'BTC', %s, 1, 0)", (result['bm'], address, result['feeamount']))
		cur.close()
		return address, result['feeamount'];
	cur.close()
	return False
Example #2
0
def key_from_mysql(key):
    cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
    logging.info("Importing GPG keys from SQL for %s", key)
    cur.execute("SELECT data FROM gpg WHERE email = %s", (key))
    for row in cur.fetchall():
        import_key(row['data'])
    cur.close()
def create_invoice_domain (domain, payer):
	cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
	filterwarnings('ignore', category = MySQLdb.Warning)
	cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM domain WHERE name = %s AND active = 1", (domain))
	result = False
	for row in cur.fetchall():
		result = row
	while result:
		if result['masterpubkey_btc'][0:4] == "xpub":
			# BIP44
			dpk1 = bitcoin.bip32_ckd(result['masterpubkey_btc'], 0)
			dpk2 = bitcoin.bip32_ckd(dpk1, result['offset_btc'])
			pubkey = bitcoin.bip32_extract_key(dpk2)
		else:
			# Electrum 1.x
			pubkey = bitcoin.electrum_pubkey(result['masterpubkey_btc'], result['offset_btc'])
		address = bitcoin.pubkey_to_address(pubkey)
		bitcoind_importaddress(address)
		cur.execute ("UPDATE domain SET offset_btc = offset_btc + 1 WHERE name = %s AND active = 1 AND masterpubkey_btc = %s", (domain, result['masterpubkey_btc']))
		if result['feecurrency'] in ("USD", "GBP", "EUR"):
			result['feeamount'] /= decimal.Decimal(get_bitcoin_price(result['feecurrency']))
		cur.execute ("INSERT IGNORE INTO invoice (issuer, payer, address, coin, amount, type, paid) VALUES (%s, %s, %s, 'BTC', %s, 0, 0)", (result['bm'], payer, address, result['feeamount']))

		# invoice already exists for that address, increment
		if cur.rowcount == 0:
			cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM domain WHERE name = %s AND active = 1", (domain))
			result = False
			for row in cur.fetchall():
				result = row
			continue
		
		cur.close()
		return address, result['feeamount'];
	cur.close()
	return False
Example #4
0
def set_message_processed(msgid):
    cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
    filterwarnings('ignore', category=MySQLdb.Warning)
    cur.execute(
        "INSERT INTO inboxids (msgid, lastseen) VALUES (%s, UNIX_TIMESTAMP(NOW())) ON DUPLICATE KEY UPDATE lastseen = UNIX_TIMESTAMP(NOW())",
        (unhexlify(msgid)))
    cur.close()
Example #5
0
    def load(self, bm=None, uid=None, email=None, unalias=False):
        cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
        filterwarnings('ignore', category=MySQLdb.Warning)
        multirow = False
        self.uid = None
        if bm != None:
            cur.execute("SELECT * FROM user WHERE bm = %s", (bm))
        elif uid != None:
            cur.execute("SELECT * FROM user WHERE uid = %s", (uid))
        elif email != None:
            if unalias:
                alias = GWAlias(email=email).target
                if alias:
                    email = alias
            cur.execute("SELECT * FROM user WHERE email = %s", (email))
        else:
            # if no arguments, return all
            multirow = True
            cur.execute("SELECT * FROM user ORDER BY email")

        for row in cur.fetchall():
            if multirow:
                print "%1s %-40s %-39s " % ("*" if row['active'] else " ",
                                            row['email'], row['bm'])
            else:
                for column in row:
                    setattr(self, column, row[column])
        cur.close()
        if hasattr(self, 'email'):
            self.aliases = GWAlias(alias=self.email).aliases
def create_invoice_user (email):
	BMMySQL().db.ping(True)
	cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)
	cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM user WHERE email = %s AND active = 1", (email))
	result = False
	for row in cur.fetchall():
		result = row
	if result:
		if result['masterpubkey_btc'][0:4] == "xpub":
			# BIP44
			dpk1 = pybitcointools.bip32_ckd(result['masterpubkey_btc'], 0)
			dpk2 = pybitcointools.bip32_ckd(dpk1, result['offset_btc'])
			pubkey = pybitcointools.bip32_extract_key(dpk2)
		else:
			# Electrum 1.x
			pubkey = pybitcointools.electrum_pubkey(result['masterpubkey_btc'], result['offset_btc'])
		address = pybitcointools.pubkey_to_address(pubkey)
		cur.execute ("UPDATE user SET offset_btc = offset_btc + 1 WHERE email = %s AND active = 1 AND masterpubkey_btc = %s", (email, result['masterpubkey_btc']))
		if result['feecurrency'] in ("USD", "GBP", "EUR"):
			result['feeamount'] /= decimal.Decimal(get_bitcoin_price(result['feecurrency']))
		cur.execute ("INSERT INTO invoice (issuer, address, coin, amount, type, paid) VALUES (%s, %s, 'BTC', %s, 1, 0)", (result['bm'], address, result['feeamount']))
		bitcoind_importaddress(address)
		cur.close()
		return address, result['feeamount'];
	cur.close()
	return False
Example #7
0
	def load(self, bm = None, uid = None, email = None, unalias = False):
		BMMySQL().db.ping(True)
		cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)
		filterwarnings('ignore', category = MySQLdb.Warning)
		multirow = False
		self.uid = None
		if bm != None:
			cur.execute ("SELECT * FROM user WHERE bm = %s", (bm))
		elif uid != None:
			cur.execute ("SELECT * FROM user WHERE uid = %s", (uid))
		elif email != None:
			if unalias:
				alias = GWAlias(email).target
				if alias:
					email = alias
			cur.execute ("SELECT * FROM user WHERE email = %s", (email))
		else:
			# if no arguments, return all
			multirow = True
			cur.execute ("SELECT * FROM user ORDER BY email")

		for row in cur.fetchall():
			if multirow:
				print "%1s %-40s %-39s " % ("*" if row['active'] else " ", row['email'], row['bm'])
			else:
				for column in row:
					setattr(self, column, row[column])
		cur.close()
    def envrcpt(self, to, *str):
        # <>
        if self.mailfrom == "":
            return Milter.CONTINUE

        # de +ify
        addr = Milter.utils.parse_addr(to.lower())
        rcpt = addr[0] + "@" + addr[1]

        userdata = lib.user.GWUser(email=rcpt)

        # non exising user
        if not userdata.check():
            return Milter.CONTINUE

        if userdata.cancharge == 0 or userdata.masterpubkey_btc == None or userdata.feeamount == 0:
            return Milter.CONTINUE

        h = hashlib.new('sha256')
        h.update(self.mailfrom + "!" + rcpt)
        digest = h.digest()

        cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)

        cur.execute("SELECT id, status FROM sendercharge WHERE hash = %s",
                    (digest))

        result = False
        for row in cur.fetchall():
            result = row

        if result and result['status'] == 1:
            cur.close()
            return Milter.CONTINUE

        if result:  # result['status'] == 0
            cur.execute(
                "SELECT address, amount FROM invoice WHERE sendercharge_id = %s",
                (row['id']))
            for row in cur.fetchall():
                result = row
            url = lib.payment.create_payment_url(result['address'], 'BTC',
                                                 result['amount'], rcpt,
                                                 'Sending emails')
        else:  # no record
            btcaddress, amount = lib.payment.create_invoice_user(rcpt)
            url = lib.payment.create_payment_url(btcaddress, 'BTC', amount,
                                                 rcpt, 'Sending emails')
            cur.execute(
                "INSERT INTO sendercharge (hash, status) values (%s, %s)",
                (digest, 0))
            sendercharge_id = cur.lastrowid
            cur.execute(
                "UPDATE invoice SET sendercharge_id = %s WHERE address = %s and coin = 'BTC'",
                (sendercharge_id, btcaddress))
        cur.close()

        url = url.replace("%", "%%")
        self.setreply("550", "5.7.0", "PAYMENT REQUIRED: %s" % url)
        return Milter.REJECT
Example #9
0
 def getSchedule(key):
     cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
     cur.execute("SELECT ts FROM schedules WHERE id = %s", (key))
     ret = None
     for row in cur.fetchall():
         ret = row['ts']
     cur.close()
     return ret
def payment_exists_domain (domain, payer):
	cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
	cur.execute ("SELECT address, amount FROM invoice WHERE type = 0 AND payer = %s AND paid = '0000-00-00 00:00:00'", (payer))
	result = False
	for row in cur.fetchall():
		result = row
	if result:
		return result['address'], result['amount']
	cur.close()
	return False, False
def payment_exists_domain (domain, payer):
	BMMySQL().db.ping(True)
	cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)
	cur.execute ("SELECT address, amount FROM invoice WHERE type = 0 AND payer = %s AND paid = '0000-00-00 00:00:00'", (payer))
	result = False
	for row in cur.fetchall():
		result = row
	if result:
		return result['address'], result['amount']
	cur.close()
	return False, False
Example #12
0
def check_message_processed(msgid):
    cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
    filterwarnings('ignore', category=MySQLdb.Warning)
    cur.execute(
        "UPDATE inboxids SET lastseen = UNIX_TIMESTAMP(NOW()) WHERE msgid = %s",
        (unhexlify(msgid)))
    if cur.rowcount >= 1:
        cur.close()
        return True
    else:
        cur.close()
        return False
Example #13
0
	def setlastrelay(self, lastrelay = None):
		BMMySQL().db.ping(True)
		cur = BMMySQL().db.cursor()
		filterwarnings('ignore', category = MySQLdb.Warning)
		if lastrelay == None:
			cur.execute ("UPDATE user SET lastrelay = UNIX_TIMESTAMP() WHERE uid = %s", (self.uid))
		else:
			cur.execute ("UPDATE user SET lastrelay = %s WHERE uid = %s", (lastrelay, self.uid))
		if (cur.rowcount == 1):
			logging.debug('Set lastrelay for (%u)', self.uid)
		else:
			logging.warning('Failure setting lastrelay for (%u)', self.uid)
		cur.close()
Example #14
0
	def delete(self):
		BMMySQL().db.ping(True)
		cur = BMMySQL().db.cursor()
		filterwarnings('ignore', category = MySQLdb.Warning)
		if self.uid:
			cur.execute ("DELETE FROM user WHERE uid = %s", (self.uid))
			if (cur.rowcount == 1):
				logging.info('Deleted user (%u) %s / %s', self.uid, self.email, self.bm)
			elif (cur.rowcount > 1):
				logging.warning('Deleted user (%u) returned more than one row', self.uid)
		else:
			logging.info('Asked to delete nonexisting user')
		cur.close()
Example #15
0
	def envrcpt (self, to, *str):
		# <>
		if self.mailfrom == "":
			return Milter.CONTINUE
	
		# de +ify
        	addr = Milter.utils.parse_addr(to.lower())
		rcpt = addr[0] + "@" + addr[1]

		BMMySQL().db.ping(True)
		userdata = lib.user.GWUser(email = rcpt)

		# non exising user
		if not userdata.check():
			return Milter.CONTINUE

		if userdata.cancharge == 0 or userdata.masterpubkey_btc == None or userdata.feeamount == 0:
			return Milter.CONTINUE
		
		h = hashlib.new('sha256')
		h.update (self.mailfrom + "!" + rcpt);
		digest = h.digest()

		cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)

		cur.execute("SELECT id, status FROM sendercharge WHERE hash = %s", (digest))
		
		result = False
		for row in cur.fetchall():
			result = row

		if result and result['status'] == 1:
			cur.close()
			return Milter.CONTINUE

		if result: # result['status'] == 0
			cur.execute("SELECT address, amount FROM invoice WHERE sendercharge_id = %s", (row['id']))
			for row in cur.fetchall():
				result = row
			url = lib.payment.create_payment_url(result['address'], 'BTC', result['amount'], rcpt, 'Sending emails')
		else: # no record
			btcaddress, amount = lib.payment.create_invoice_user(rcpt)
			url = lib.payment.create_payment_url(btcaddress, 'BTC', amount, rcpt, 'Sending emails')
			cur.execute("INSERT INTO sendercharge (hash, status) values (%s, %s)", (digest, 0))
			sendercharge_id = cur.lastrowid
			cur.execute("UPDATE invoice SET sendercharge_id = %s WHERE address = %s and coin = 'BTC'", (sendercharge_id, btcaddress))
		cur.close()

		url = url.replace("%", "%%")
		self.setreply("550", "5.7.0", "PAYMENT REQUIRED: %s" % url)
		return Milter.REJECT
Example #16
0
 def delete(self):
     cur = BMMySQL().conn().cursor()
     filterwarnings('ignore', category=MySQLdb.Warning)
     if self.uid:
         cur.execute("DELETE FROM user WHERE uid = %s", (self.uid))
         if (cur.rowcount == 1):
             logging.info('Deleted user (%u) %s / %s', self.uid, self.email,
                          self.bm)
         elif (cur.rowcount > 1):
             logging.warning('Deleted user (%u) returned more than one row',
                             self.uid)
     else:
         logging.info('Asked to delete nonexisting user')
     cur.close()
Example #17
0
 def setlastrelay(self, lastrelay=None):
     cur = BMMySQL().conn().cursor()
     filterwarnings('ignore', category=MySQLdb.Warning)
     if lastrelay == None:
         cur.execute(
             "UPDATE user SET lastrelay = UNIX_TIMESTAMP() WHERE uid = %s",
             (self.uid))
     else:
         cur.execute("UPDATE user SET lastrelay = %s WHERE uid = %s",
                     (lastrelay, self.uid))
     if (cur.rowcount == 1):
         logging.debug('Set lastrelay for (%u)', self.uid)
     else:
         logging.warning('Failure setting lastrelay for (%u)', self.uid)
     cur.close()
Example #18
0
	def add(self, bm, email, postmap = None):
		BMMySQL().db.ping(True)
		cur = BMMySQL().db.cursor()
		if postmap == None:
			postmap = pwd.getpwuid(os.getuid())[0]
		trash, domain = email.split("@")
		filterwarnings('ignore', category = MySQLdb.Warning)
		cur.execute ("""INSERT IGNORE INTO user (bm, email, postmap, domain, credits, exp, active, cansend, cancharge, caninvoice, attachments)
				VALUES (%s, %s, %s, %s, '0', '1971-01-01', 1, 1, 0, 0, 0)""", (bm, email, postmap, domain))
		uid = None
		if cur.rowcount == 1:
			uid = cur.lastrowid
			self.load(uid = uid)
			logging.info('Registered new user (%u) %s', uid, email)
		else:
			logging.error('Failed to add new user entry into the database for %s', email)
		cur.close()
		return uid
Example #19
0
 def setlastackreceived(self, lastackreceived=None):
     # for example user deleted
     if self.uid is None:
         return
     cur = BMMySQL().conn().cursor()
     filterwarnings('ignore', category=MySQLdb.Warning)
     if lastackreceived == None:
         cur.execute(
             "UPDATE user SET lastackreceived = UNIX_TIMESTAMP() WHERE uid = %s",
             (self.uid))
     else:
         cur.execute("UPDATE user SET lastackreceived = %s WHERE uid = %s",
                     (lastackreceived, self.uid))
     if (cur.rowcount == 1):
         logging.debug('Set lastackreceived for (%u)', self.uid)
     else:
         logging.warning('Failure setting lastackreceived for (%u)',
                         self.uid or -1)
     cur.close()
Example #20
0
def delete_expired_subkey(address):
    global gpgme

    out = pyme.core.Data()
    key = check_key(address, whatreturn="key", operation="any", expired=True)
    if key:
        gpgme.op_edit(key, KeyEditor("delkey").edit_fnc, out, out)
        keyagain = check_key(address,
                             whatreturn="key",
                             operation="any",
                             expired=True)
        if not keyagain:
            cur = BMMySQL().conn().cursor()
            cur.execute(
                "INSERT INTO gpg (email, fingerprint, private, exp, data) VALUES (%s, %s, %s, FROM_UNIXTIME(%s), %s) ON DUPLICATE KEY UPDATE exp = VALUES(exp), data = VALUES(data)",
                (key.uids[0].email, key.subkeys[0].fpr, 0,
                 key.subkeys[0].expires, public))
            rowcount += cur.rowcount
            cur.close()
Example #21
0
	def __init__(self, domain = None):
		self.name = None
		self.active = None
		BMMySQL().db.ping(True)
		cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)
		filterwarnings('ignore', category = MySQLdb.Warning)
		multirow = False
		if domain != None:
			cur.execute ("SELECT * FROM domain WHERE active = 1 AND name = %s", (domain))
		else:
			multirow = True
			cur.execute ("SELECT * FROM domain WHERE active = 1")
		for row in cur.fetchall():
			if multirow:
				print "%40s %1u" % (row['name'], row['active'])
			else:
				self.name = row['name']
				self.active = row['active']
		cur.close()
Example #22
0
 def __init__(self, domain=None):
     self.name = None
     self.active = None
     cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
     filterwarnings('ignore', category=MySQLdb.Warning)
     multirow = False
     if domain != None:
         cur.execute("SELECT * FROM domain WHERE active = 1 AND name = %s",
                     (domain))
     else:
         multirow = True
         cur.execute("SELECT * FROM domain WHERE active = 1")
     for row in cur.fetchall():
         if multirow:
             print "%40s %1u" % (row['name'], row['active'])
         else:
             self.name = row['name']
             self.active = row['active']
     cur.close()
Example #23
0
def key_to_mysql(key):
    # stupid gpgme library has no support for exporting secret keys
    global gpg
    public = gpg.export_keys(key.subkeys[0].fpr)  # Public
    secret = gpg.export_keys(key.subkeys[0].fpr, True)  # Private

    rowcount = 0

    cur = BMMySQL().conn().cursor()
    cur.execute(
        "INSERT INTO gpg (email, fingerprint, private, exp, data) VALUES (%s, %s, %s, FROM_UNIXTIME(%s), %s) ON DUPLICATE KEY UPDATE exp = VALUES(exp), data = VALUES(data)",
        (key.uids[0].email, key.subkeys[0].fpr, 0, key.subkeys[0].expires,
         public))
    rowcount += cur.rowcount
    cur.execute(
        "INSERT INTO gpg (email, fingerprint, private, exp, data) VALUES (%s, %s, %s, FROM_UNIXTIME(%s), %s) ON DUPLICATE KEY UPDATE exp = VALUES(exp), data = VALUES(data)",
        (key.uids[0].email, key.subkeys[0].fpr, 1, key.subkeys[0].expires,
         secret))
    rowcount += cur.rowcount
    cur.close()
    return rowcount
Example #24
0
 def update(self, data):
     col_names = BMMySQL().filter_column_names("user", data)
     cur = BMMySQL().conn().cursor()
     update_list = []
     for key in col_names:
         if data[key] is not None:
             update_list.append("`" + key + "`" + " = \"" +
                                BMMySQL().conn().escape_string(data[key]) +
                                "\"")
     if len(update_list) == 0:
         return False
     cur.execute(
         "UPDATE user SET " + ", ".join(update_list) + " WHERE bm = %s",
         (self.bm))
     #print ("UPDATE user SET " + ", ".join(update_list) + " WHERE bm = %s" % (self.bm))
     if cur.rowcount == 1:
         cur.close()
         return True
     else:
         cur.close()
         return False
Example #25
0
 def __init__(self, email=None, alias=None):
     self.aliases = []
     self.target = None
     cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
     result = False
     if email:
         seen = {email: True}
         src = email
         while not result:
             cur.execute("SELECT target FROM alias WHERE alias = %s", (src))
             result = True
             for row in cur.fetchall():
                 result = False
                 seen[row['target']] = True
                 src = row['target']
                 for column in row:
                     setattr(self, column, row[column])
     elif alias:
         cur.execute("SELECT alias FROM alias WHERE target = %s", (alias))
         for row in cur.fetchall():
             self.aliases.append(row['alias'])
     cur.close()
Example #26
0
def mega_upload(bm, fname, data):
	m = mega_login()
	if m == None:
		return None, None
	foldername = BMConfig().get("bmgateway", "mega", "folder")
	folder = m.find(foldername)
	loops = 30
	while folder == None and loops > 0:
		try:
			m.create_folder(foldername)
			folder = m.find(foldername)
		except:
			pass
		if folder == None:
			time.sleep (1)
		loops -= 1
	if folder == None:
		return None, None

	
	uploadedfile = None
	loops = 30
	while uploadedfile == None and loops > 0:
		try:
			uploadedfile = m.upload(data, folder[0], dest_filename=fname, save_key=False)
		except:
			pass
		if uploadedfile == None:
			time.sleep (1)
		loops -= 1
		
	file_id = uploadedfile['f'][0]['h']
	link = m.get_upload_link(uploadedfile)
	cur = BMMySQL().conn().cursor()
	cur.execute ("INSERT IGNORE INTO mega (fileid, bm) VALUES (%s, %s)", (
		file_id, bm))
	cur.close()
	return file_id, link
Example #27
0
    def add(self, bm, email, postmap=None):
        cur = BMMySQL().conn().cursor()
        if postmap == None:
            postmap = pwd.getpwuid(os.getuid())[0]
        trash, domain = email.split("@")
        filterwarnings('ignore', category=MySQLdb.Warning)
        pgp = 1 if BMConfig().get("bmgateway", "default", "pgp") else 0
        attachments = 1 if BMConfig().get("bmgateway", "default",
                                          "attachments") else 0
        cur.execute(
            """INSERT IGNORE INTO user (bm, email, postmap, domain, pgp, credits, exp, active, cansend, cancharge, caninvoice, attachments, html, lastackreceived)
				VALUES (%s, %s, %s, %s, %s, '0', '1971-01-01', 1, 1, 0, 0, %s, 0, UNIX_TIMESTAMP(NOW()))""",
            (bm, email, postmap, domain, pgp, attachments))
        uid = None
        if cur.rowcount == 1:
            uid = cur.lastrowid
            self.load(uid=uid)
            logging.info('Registered new user (%u) %s', uid, email)
        else:
            logging.error(
                'Failed to add new user entry into the database for %s', email)
        cur.close()
        return uid
def create_invoice_domain (domain, payer):
	BMMySQL().db.ping(True)
	cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)
	filterwarnings('ignore', category = MySQLdb.Warning)
	cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM domain WHERE name = %s AND active = 1", (domain))
	result = False
	for row in cur.fetchall():
		result = row
	while result:
		if result['masterpubkey_btc'][0:4] == "xpub":
			# BIP44
			dpk1 = pybitcointools.bip32_ckd(result['masterpubkey_btc'], 0)
			dpk2 = pybitcointools.bip32_ckd(dpk1, result['offset_btc'])
			pubkey = pybitcointools.bip32_extract_key(dpk2)
		else:
			# Electrum 1.x
			pubkey = pybitcointools.electrum_pubkey(result['masterpubkey_btc'], result['offset_btc'])
		address = pybitcointools.pubkey_to_address(pubkey)
		cur.execute ("UPDATE domain SET offset_btc = offset_btc + 1 WHERE name = %s AND active = 1 AND masterpubkey_btc = %s", (domain, result['masterpubkey_btc']))
		if result['feecurrency'] in ("USD", "GBP", "EUR"):
			result['feeamount'] /= decimal.Decimal(get_bitcoin_price(result['feecurrency']))
		cur.execute ("INSERT IGNORE INTO invoice (issuer, payer, address, coin, amount, type, paid) VALUES (%s, %s, %s, 'BTC', %s, 0, 0)", (result['bm'], payer, address, result['feeamount']))

		# invoice already exists for that address, increment
		if cur.rowcount == 0:
			cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM domain WHERE name = %s AND active = 1", (domain))
			result = False
			for row in cur.fetchall():
				result = row
			continue
		
		bitcoind_importaddress(address)
		cur.close()
		return address, result['feeamount'];
	cur.close()
	return False
						months = 0
					else:
						months = incomingamount / invoice['amount']
					print "Extending for " + str(months) + " months"
					userdata = GWUser(bm = invoice['payer'])
					datefrom = userdata.exp if userdata.exp > datetime.date.today() else datetime.date.today()
					cur.execute ("UPDATE user SET cansend = 1, exp = IF(exp < CURDATE(),DATE_ADD(CURDATE(), INTERVAL " +
						str(months) + " MONTH),DATE_ADD(exp, INTERVAL " + str(months) +
						" MONTH)) WHERE bm = %s", invoice['payer']);
					userdata = GWUser(bm = invoice['payer'])
					dateuntil = userdata.exp
					SendBMTemplate(
						sender = BMAPI().get_address(BMConfig().get("bmgateway", "bmgateway", "registration_address_label")),
						recipient = invoice['payer'],
						template = "invoice",
                                                addmaps = {
							'btcamount': str(incomingamount),
                                                        'service': 'Subscription for ' + userdata.email + ' from ' + datefrom.strftime("%B %-d %Y") +
                                                                ' until ' + dateuntil.strftime("%B %-d %Y"),
                                                        'email': userdata.email
                                                })

				elif invoice['type'] == 1:
					# find in combo table and allow
					cur.execute ("UPDATE sendercharge SET status = 1 WHERE id = %s", (invoice['sendercharge_id']))
				elif invoice['type'] == 2:
					# notify user that payment is incoming
					pass
			pass
cur.close()
Example #30
0
                        invoice['payer'])
                    userdata = GWUser(bm=invoice['payer'])
                    dateuntil = userdata.exp
                    SendBMTemplate(
                        sender=BMAPI().get_address(BMConfig().get(
                            "bmgateway", "bmgateway",
                            "registration_address_label")),
                        recipient=invoice['payer'],
                        template="invoice",
                        addmaps={
                            'btcamount':
                            str(incomingamount),
                            'service':
                            'Subscription for ' + userdata.email + ' from ' +
                            datefrom.strftime("%B %-d %Y") + ' until ' +
                            dateuntil.strftime("%B %-d %Y"),
                            'email':
                            userdata.email
                        })

                elif invoice['type'] == 1:
                    # find in combo table and allow
                    cur.execute(
                        "UPDATE sendercharge SET status = 1 WHERE id = %s",
                        (invoice['sendercharge_id']))
                elif invoice['type'] == 2:
                    # notify user that payment is incoming
                    pass
            pass
cur.close()