# Path: coloredcoinlib/store.py
# class DataStore(object):
#     """ Represents a database and allows it's
#     manipulation via queries."""
#     def __init__(self, conn):
#         self.conn = conn
# 
#     def table_exists(self, tablename):
#         res = self.execute(
#             "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
#             (tablename, )).fetchone()
#         return res is not None
# 
#     def column_exists(self, tablename, column_name):
#         info = self.execute("PRAGMA table_info(tx_data)")
#         return any(row[1] == 'block_height' for row in info)
# 
#     def execute(self, statement, params=()):
#         cur = self.conn.cursor()
#         cur.execute(statement, params)
#         return cur
# 
#     def sync(self):
#         self.conn.commit()
# 
#     def transaction(self):
#         return self.conn
# 
# class DataStoreConnection(object):
#     """ A database connection """
#     def __init__(self, path, autocommit=False):
#         self.path = path
#         self.conn = sqlite3.connect(path, check_same_thread=False)
#         if autocommit:
#             self.conn.isolation_level = None
# 
#     def __del__(self):
#         if self.conn:
#             self.conn.commit()
#             self.conn.close()
# 
# class PersistentDictStore(DictMixin, DataStore):
#     """ Persistent dict object """
# 
#     def __init__(self, conn, dictname):
#         super(PersistentDictStore, self).__init__(conn)
#         conn.text_factory = str
#         self.tablename = dictname + "_dict"
#         if not self.table_exists(self.tablename):
#             self.execute("CREATE TABLE {0} (key NOT NULL PRIMARY KEY "
#                          "UNIQUE, value BLOB)".format(self.tablename))
# 
#     def deserialize(self, svalue):
#         return pickle.loads(svalue)
# 
#     def serialize(self, value):
#         return pickle.dumps(value)
# 
#     def __getitem__(self, key):
#         svalue = self.execute(
#             "SELECT value FROM {0} WHERE key = ?".format(self.tablename),
#             (key,)).fetchone()
#         if svalue:
#             return self.deserialize(unwrap1(svalue))
#         else:
#             raise KeyError()
# 
#     def __setitem__(self, key, value):
#         self.execute(
#             "INSERT OR REPLACE INTO {0} VALUES (?, ?)".format(self.tablename),
#             (key, self.serialize(value)))
# 
#     def __contains__(self, key):
#         svalue = self.execute(
#             "SELECT value FROM {0} WHERE key = ?".format(self.tablename),
#             (key,)).fetchone()
#         return svalue is not None
# 
#     def __delitem__(self, key):
#         if self.__contains__(key):
#             self.execute(
#                 "DELETE FROM {0} WHERE key = ?".format(self.tablename),
#                 (key,))
#         else:
#             raise KeyError()
# 
#     def keys(self):
#         return map(
#             unwrap1,
#             self.execute(
#                 "SELECT key FROM {0}".format(self.tablename)).fetchall())
# 
# def unwrap1(val):
#     if val:
#         return val[0]
#     else:
#         return None
# 
# Path: ngcccbase/services/blockchain.py
# class BlockchainInfoInterface(WebBlockchainInterface):
#     """Interface for blockchain.info. DO NOT USE FOR TESTNET!
#     """
#     URL_TEMPLATE = "https://blockchain.info/unspent?active=%s"
#     REVERSE_TXHASH = True
# 
#     def __init__(self, tx_db=None):
#         self.tx_db = tx_db
# 
#     def notify_confirmations(self, txhash, confirmations):
#         if self.tx_db:
#             self.tx_db.notify_confirmations(txhash, confirmations)
# 
#     def connected(self):
#         try:
#             return bool(self.get_block_count())
#         except:
#             return False
# 
#     def get_block_count(self):
#         url = "https://blockchain.info/q/getblockcount"
#         return int(urllib2.urlopen(url).read())
#     
#     def get_tx_confirmations(self, txhash):
#         try:
#             url = "https://blockchain.info/rawtx/%s" % txhash
#             data = json.loads(urllib2.urlopen(url).read())
#             if 'block_height' in data:
#                 block_count = self.get_block_count()
#                 return block_count - data['block_height'] + 1
#             else:
#                 return 0
#         except Exception as e:
#             return None
# 
#     def get_address_history(self, address):
#         block_count = self.get_block_count()
#         url = "https://blockchain.info/rawaddr/%s" % address
#         jsonData = urllib2.urlopen(url).read()
#         data = json.loads(jsonData)
#         return [tx['hash'] for tx in data['txs']]        


from time import time
from urllib2 import HTTPError
from pycoin.encoding import double_sha256
from coloredcoinlib.store import DataStore, DataStoreConnection, PersistentDictStore, unwrap1
from ngcccbase.services.blockchain import BlockchainInfoInterface
from txcons import RawTxSpec
from blockchain import VerifiedBlockchainState
import threading
import os





TX_STATUS_UNKNOWN = 0
TX_STATUS_UNCONFIRMED = 1
TX_STATUS_CONFIRMED = 2
TX_STATUS_INVALID = 3

create_transaction_table = """\
CREATE TABLE tx_data (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    txhash TEXT,
    data TEXT,
    status INTEGER,

# Path: coloredcoinlib/store.py
# class DataStore(object):
#     """ Represents a database and allows it's
#     manipulation via queries."""
#     def __init__(self, conn):
#         self.conn = conn
# 
#     def table_exists(self, tablename):
#         res = self.execute(
#             "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
#             (tablename, )).fetchone()
#         return res is not None
# 
#     def column_exists(self, tablename, column_name):
#         info = self.execute("PRAGMA table_info(tx_data)")
#         return any(row[1] == 'block_height' for row in info)
# 
#     def execute(self, statement, params=()):
#         cur = self.conn.cursor()
#         cur.execute(statement, params)
#         return cur
# 
#     def sync(self):
#         self.conn.commit()
# 
#     def transaction(self):
#         return self.conn
# 
# class DataStoreConnection(object):
#     """ A database connection """
#     def __init__(self, path, autocommit=False):
#         self.path = path
#         self.conn = sqlite3.connect(path, check_same_thread=False)
#         if autocommit:
#             self.conn.isolation_level = None
# 
#     def __del__(self):
#         if self.conn:
#             self.conn.commit()
#             self.conn.close()
# 
# class PersistentDictStore(DictMixin, DataStore):
#     """ Persistent dict object """
# 
#     def __init__(self, conn, dictname):
#         super(PersistentDictStore, self).__init__(conn)
#         conn.text_factory = str
#         self.tablename = dictname + "_dict"
#         if not self.table_exists(self.tablename):
#             self.execute("CREATE TABLE {0} (key NOT NULL PRIMARY KEY "
#                          "UNIQUE, value BLOB)".format(self.tablename))
# 
#     def deserialize(self, svalue):
#         return pickle.loads(svalue)
# 
#     def serialize(self, value):
#         return pickle.dumps(value)
# 
#     def __getitem__(self, key):
#         svalue = self.execute(
#             "SELECT value FROM {0} WHERE key = ?".format(self.tablename),
#             (key,)).fetchone()
#         if svalue:
#             return self.deserialize(unwrap1(svalue))
#         else:
#             raise KeyError()
# 
#     def __setitem__(self, key, value):
#         self.execute(
#             "INSERT OR REPLACE INTO {0} VALUES (?, ?)".format(self.tablename),
#             (key, self.serialize(value)))
# 
#     def __contains__(self, key):
#         svalue = self.execute(
#             "SELECT value FROM {0} WHERE key = ?".format(self.tablename),
#             (key,)).fetchone()
#         return svalue is not None
# 
#     def __delitem__(self, key):
#         if self.__contains__(key):
#             self.execute(
#                 "DELETE FROM {0} WHERE key = ?".format(self.tablename),
#                 (key,))
#         else:
#             raise KeyError()
# 
#     def keys(self):
#         return map(
#             unwrap1,
#             self.execute(
#                 "SELECT key FROM {0}".format(self.tablename)).fetchall())
# 
# def unwrap1(val):
#     if val:
#         return val[0]
#     else:
#         return None
# 
# Path: ngcccbase/services/blockchain.py
# class BlockchainInfoInterface(WebBlockchainInterface):
#     """Interface for blockchain.info. DO NOT USE FOR TESTNET!
#     """
#     URL_TEMPLATE = "https://blockchain.info/unspent?active=%s"
#     REVERSE_TXHASH = True
# 
#     def __init__(self, tx_db=None):
#         self.tx_db = tx_db
# 
#     def notify_confirmations(self, txhash, confirmations):
#         if self.tx_db:
#             self.tx_db.notify_confirmations(txhash, confirmations)
# 
#     def connected(self):
#         try:
#             return bool(self.get_block_count())
#         except:
#             return False
# 
#     def get_block_count(self):
#         url = "https://blockchain.info/q/getblockcount"
#         return int(urllib2.urlopen(url).read())
#     
#     def get_tx_confirmations(self, txhash):
#         try:
#             url = "https://blockchain.info/rawtx/%s" % txhash
#             data = json.loads(urllib2.urlopen(url).read())
#             if 'block_height' in data:
#                 block_count = self.get_block_count()
#                 return block_count - data['block_height'] + 1
#             else:
#                 return 0
#         except Exception as e:
#             return None
# 
#     def get_address_history(self, address):
#         block_count = self.get_block_count()
#         url = "https://blockchain.info/rawaddr/%s" % address
#         jsonData = urllib2.urlopen(url).read()
#         data = json.loads(jsonData)
#         return [tx['hash'] for tx in data['txs']]        


# Path: ngcccbase/txdb.py
from time import time
from urllib2 import HTTPError
from pycoin.encoding import double_sha256
from coloredcoinlib.store import DataStore, DataStoreConnection, PersistentDictStore, unwrap1
from ngcccbase.services.blockchain import BlockchainInfoInterface
from txcons import RawTxSpec
from blockchain import VerifiedBlockchainState
import threading
import os






TX_STATUS_UNKNOWN = 0
TX_STATUS_UNCONFIRMED = 1
TX_STATUS_CONFIRMED = 2
TX_STATUS_INVALID = 3

create_transaction_table = """\
CREATE TABLE tx_data (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    txhash TEXT,
    data TEXT,
    status INTEGER,

    block_height INTEGER