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()
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().db.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
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().db.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
	return rowcount
	def __init__(self, email):
		self.alias = None
		self.target = None
		BMMySQL().db.ping(True)
		cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)
		result = False
		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])
Exemple #5
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 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
Exemple #7
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
Exemple #8
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
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 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
Exemple #11
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()
 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()
 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()
 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()
	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()
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
	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()
 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()
Exemple #19
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
 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()
Exemple #21
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()
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
    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
Exemple #24
0
			if atime > time.time() - 10:
				continue
		fhandle = open (os.path.join(BMConfig().get("bmgateway", "bmgateway", "mail_folder"), k), 'r')
		try:
			fcntl.flock(fhandle, fcntl.LOCK_EX|fcntl.LOCK_NB)
		except IOError:
			fhandle.close()
			# locked, skip this time
			continue
		email_thread = threading.Thread(target=handle_email, name="EmailIn", args=(k,))
		email_thread.start()
		email_thread.join()
		fcntl.flock(fhandle, fcntl.LOCK_UN)
		fhandle.close()

if not BMMySQL().connect():
	print "Failed to connect to mysql"
	sys.exit()

lib.gpg.gpg_init()

## main  
parser = argparse.ArgumentParser(description='An email <-> bitmessage gateway.')
parser.add_argument('-l','--list', help='List known internal and external addresses',required=False, action='store_true')
parser.add_argument('-d','--delete', help='Delete an address',required=False, default=False)
parser.add_argument('-a','--add', help='Generate a new bitmessage address with given label',required=False, default=False)

args = parser.parse_args()

## call correct function
if args.list == True:
Exemple #25
0
if coin == 'BTC':
    cfg = parse_configfile('~/.bitcoin/bitcoin.conf')
elif coin == 'DRK':
    cfg = parse_configfile('~/.dash/dash.conf')
else:
    print "Unknown coin " + coin
    sys.exit()

client = jsonrpclib.Server('http://' + cfg['rpcuser'] + ":" +
                           cfg['rpcpassword'] + "@" + cfg['rpcconnect'] + ":" +
                           str(cfg['rpcport']) + "/")

txinfo = client.gettransaction(txid, True)

BMLogging()
cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
while BMAPI().conn() is False:
    print "Failure connecting to API, sleeping..."
    time.sleep(random.random() + 0.5)

filterwarnings('ignore', category=MySQLdb.Warning)

#amount = txinfo['amount']
for detail in txinfo['details']:
    if detail['category'] == "receive":
        print detail['address'] + " -> " + str(detail['amount'])
        cur.execute(
            """INSERT IGNORE INTO payment (address, coin, txid, amount, confirmations) VALUES (%s, %s, %s, %s, %s)""",
            (detail['address'], coin, txid, detail['amount'],
             txinfo['confirmations']))
        if txinfo['confirmations'] == 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]

        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
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
	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
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
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
	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 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
def key_from_mysql(key):
	cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)
	logger.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'])
if coin == 'BTC':
	cfg = parse_configfile('~/.bitcoin/bitcoin.conf')
elif coin == 'DRK':
	cfg = parse_configfile('~/.dash/dash.conf')
else:
	print "Unknown coin " + coin
	sys.exit()

client = jsonrpclib.Server('http://' + cfg['rpcuser'] + ":" + cfg['rpcpassword'] + "@" + cfg['rpcconnect'] + ":" + str(cfg['rpcport']) + "/")

txinfo = client.gettransaction(txid, True)

BMLogging()
BMMySQL().connect()
cur = BMMySQL().db.cursor(MySQLdb.cursors.DictCursor)
while BMAPI().conn() is False:
	print "Failure connecting to API, sleeping..."
	time.sleep(random.random()+0.5)

filterwarnings('ignore', category = MySQLdb.Warning)

#amount = txinfo['amount']
for detail in txinfo['details']:
	if detail['category'] == "receive":
		print detail['address'] + " -> " + str(detail['amount'])
		cur.execute ( """INSERT IGNORE INTO payment (address, coin, txid, amount, confirmations) VALUES (%s, %s, %s, %s, %s)""",
			(detail['address'], coin, txid, detail['amount'], txinfo['confirmations']))
		if txinfo['confirmations'] == 0:
			# select from invoice
			cur.execute ("SELECT amount, paid, type, payer, sendercharge_id FROM invoice WHERE address = %s AND coin = %s", (detail['address'], coin))