示例#1
0
curses.init_pair(COLOR_GOLD, 3, 0)
COLOR_LTBLUE = 7
curses.init_pair(COLOR_LTBLUE, 6, 0)
COLOR_GREEN = 2
curses.init_pair(COLOR_GREEN, 2, 0)
COLOR_WHITE = 3
curses.init_pair(COLOR_WHITE, 7, 0)
COLOR_RED = 6
curses.init_pair(COLOR_RED, 1, 0)
COLOR_PINK = 5
curses.init_pair(COLOR_PINK, 5, 0)
COLOR_BLUE = 4
curses.init_pair(COLOR_BLUE, 4, 0)

# init the bitcoin RPC connection
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                  (bitcoinAuth.USER, bitcoinAuth.PW))

# init LED grid, rows and chain length are both required parameters:
matrix = Adafruit_RGBmatrix(32, 1)

# this matrix buffers the LED grid output to avoid using clear() every frame
buffer = []

# this array stores hashes of blocks that confirms my incoming transactions
myTxBlocks = []
# on startup, load 10 (bitcoin RPC call default) recent receive transactions into that array
listTx = rpc_connection.listtransactions()
for tx in listTx:
    if tx['category'] == 'receive' and tx['confirmations'] > 0:
        myTxBlocks.append(tx['blockhash'])
示例#2
0
import bitcoinAuth
from bitcoinrpc import AuthServiceProxy, JSONRPCException


rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(bitcoinAuth.USER,bitcoinAuth.PW))

addr = rpc_connection.getnewaddress()
print addr
示例#3
0
 def __init__(self):
     """Initializes the class with the bitcoind client."""
     self.bitcoind = AuthServiceProxy(bitcoind_protocol + "://" + bitcoind_username + ":" + bitcoind_password + "@" + bitcoind_ip + ":" + bitcoind_port)  
示例#4
0
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
root.addHandler(ch)
root.setLevel(getattr(logging, args.log_level))

config = {'pass': None}
for line in args.config_path:
    pts = line.strip().split("=")
    if len(pts) != 2:
        continue
    config[pts[0]] = pts[1]

if args.passphrase_file:
    config['pass'] = args.passphrase_file.read().strip()

rpc_connection = AuthServiceProxy(
    "http://{rpcuser}:{rpcpassword}@localhost:{rpcport}/".format(**config))

try:
    balance = rpc_connection.getbalance()
except CoinRPCException as e:
    logging.error("Unable to retrieve balance, rpc returned {}".format(e))
    exit(1)

try:
    balance = Decimal(balance)
except ValueError:
    logging.error("Bogus data returned by balance call, exiting".format(
        str(balance)[:100]))
    exit(1)

if balance < Decimal("0.001"):
示例#5
0
import ipInfoAuth
from bitcoinrpc import AuthServiceProxy, JSONRPCException

#############
# constants #
#############

rootdir = sys.path[0]
peerFile = rootdir + '/data/peer_list.txt'

##############
# initialize #
##############

# initialize bitcoin RPC connection and gather info
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                  (bitcoinAuth.USER, bitcoinAuth.PW))

#############
# functions #
#############


# refresh the peers list
def refreshPeers():
    # create new file if missing
    if not os.path.isfile(peerFile):
        # create directory if missing
        if not os.path.exists(rootdir + '/data'):
            os.makedirs(rootdir + '/data')
            os.chmod(rootdir + '/data', 0777)
示例#6
0
class BitcoinClient(object):
    # TODO: Figure out how to implement this class as a Singleton
    # TODO: Add/fix parameters where needed per https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list
    
    def __init__(self):
        """Initializes the class with the bitcoind client."""
        self.bitcoind = AuthServiceProxy(bitcoind_protocol + "://" + bitcoind_username + ":" + bitcoind_password + "@" + bitcoind_ip + ":" + bitcoind_port)  
        
    # def addmultisigaddress(self, nrequired, ["key","key"], account=None):
    #     """Add a nrequired-to-sign multisignature address to the wallet.
        
    #     Each key is a bitcoin address or hex-encoded public key. 
    #     If [account] is specified, assign address to [account].
        
    #     nrequired: number of signatures to require
    #     ["key","key"]: 
    #     account: account to add to
    #     """
    #     return self.bitcoind.addmultisigaddress(nrequired, ["key","key"], account)
    
    def addnode(self, node, action):
        """Attempts add or remove <node> from the addnode list or try a connection to <node> once.
        
        node: connection node 
        action: action to take on node (possible: add/remove/onetry)
        """
        return self.bitcoind.addnode(node, action)
    
    def backupwallet(self, destination):
        """Safely copies wallet.dat to destination, which can be a directory or a path with filename.
        
        destination: directory or a path with filename to backup wallet to
        """
        return self.bitcoind.backupwallet(destination)
    
    def createmultisig(self):
        return None
    
    def createrawtransaction(self):
        return None
    
    def decoderawtransaction(self):
        return None
    
    def dumpprivkey(self, bitcoinaddress):
        """Reveals the private key corresponding to <bitcoinaddress>
        
        bitcoinaddress: address to reveal private key for
        """
        return self.bitcoind.dumpprivkey(bitcoinaddress)
    
    def encryptwallet(self, passphrase):
        """Encrypts the wallet with <passphrase>.
        
        passphrase: passphrase to encrypt wallet with     
        """
        return self.bitcoind.encryptwallet(passphrase)
    
    def getaccount(self, bitcoinaddress):
        """Returns the account associated with the given address.
        
        bitcoinaddress: address associated with account
        """
        return self.bitcoind.getaccount(bitcoinaddress)
    
    def getaccountaddress(self, account):
        """Returns the current bitcoin address for receiving payments to this account.
        
        account: account to return receiving address for
        """
        return self.bitcoind.getaccountaddress(account)
    
    def getaddednodeinfo(self):
        return None
    
    def getaddressesbyaccount(self, account):
        """Returns the list of addresses for the given account.
        
        account: account to return addresses for        
        """
        return self.bitcoind.getaddressesbyaccount(account)
    
    def getbalance(self, account=None, minconf=1):
        """Returns balance for server's total available balance.
        
        account: if [account] is not specified, returns the server's total available balance, otherwise returns the balance in the account.
        minconf: number of min confirmations to count
        """
        return self.bitcoind.getbalance(account, minconf)
    
    def getblock(self, hash):
        """Returns information about the block with the given hash.
        
        hash: hash to return block info for
        """
        return self.bitcoind.getblock(hash)

    def getblockcount(self):
        """Returns the number of blocks in the longest block chain."""
        return self.bitcoind.getblockcount()
        
    def getblockhash(self, index):
        """Returns hash of block in best-block-chain at <index>; index 0 is the genesis block.
        
        index: index of block to hash
        """
        return self.bitcoind.getblockhash(index)
    
    def getblocktemplate(self, params=None):
        """Returns data needed to construct a block to work on.
        
        params: 
        """
        return None
    
    def getconnectioncount(self):
        """Returns the number of connections to other nodes."""
        return self.bitcoind.getconnectioncount()
    
    def getdifficulty(self):
        """Returns the proof-of-work difficulty as a multiple of the minimum difficulty."""
        return self.bitcoind.getdifficulty()
    
    def getgenerate(self):
        """Returns true or false whether bitcoind is currently generating hashes."""
        return self.bitcoind.getgenerate()
    
    def gethashespersec(self):
        """Returns a recent hashes per second performance measurement while generating."""
        return self.bitcoind.gethashespersec()
    
    def getinfo(self):
        """Returns an object containing various state info."""
        return self.bitcoind.getinfo()
    
    def getmemorypool(self):
        return None
    
    def getmininginfo(self):
        """ Returns an object containing mining-related information:
        - blocks
        - currentblocksize
        - currentblocktx
        - difficulty
        - errors
        - generate
        - genproclimit
        - hashespersec
        - pooledtx
        - testnet
        """
        return self.bitcoind.getmininginfo()
    
    def getnewaddress(self, account=None):
        """Returns a new bitcoin address for receiving payments. 
        
        account: if [account] is specified (recommended), it is added to the address book 
        so payments received with the address will be credited to [account].
        """
        return self.bitcoind.getnewaddress(account)
    
    def getpeerinfo(self):
        """Returns data about each connected node."""
        return self.bitcoind.getpeerinfo()
    
    def getrawmempool(self):
        """Returns all transaction ids in memory pool."""
        return self.bitcoind.getrawmempool()
    
    def getrawtransaction(self):
        return None
    
    def getreceivedbyaccount(self, account=None, minconf=1):
        """Returns the total amount received by addresses with [account] in transactions with at least [minconf] confirmations. 
        
        account: if [account] not provided return will include all transactions to all accounts
        minconf: minimum number of confirmations to count        
        """
        return None
    
    def getreceivedbyaddress(self, bitcoinaddress, minconf=1):
        """Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations. 
        
        While some might consider this obvious, value reported by this only considers *receiving* transactions. 
        It does not check payments that have been made *from* this address. In other words, this is not "getaddressbalance". Works only for addresses in the local wallet, external addresses will always show 0.
        
        bitcoinaddress: address 
        minconf = minimum number of confirmations to count
        """
        return self.bitcoind.getreceivedbyaddress(bitcoinaddress, minconf)
    
    def gettransaction(self, txid):
        """Returns an object about the given transaction containing:
        - amount: total amount of the transaction
        - confirmations: number of confirmations of the transaction
        - txid: the transaction ID
        - time: time associated with the transaction[1].
        - details - An array of objects containing:
            - account
            - address
            - category
            - amount
            - fee
            
        txid: transaction id
        """
        return self.bitcoind.gettransaction(txid)
    
    def gettxout(self):
        return None
    
    def gettxoutsetinfo(self):
        """Returns statistics about the unspent transaction output (UTXO) set."""
        return self.bitcoind.gettxoutsetinfo()
    
    def getwork(self):
        return None
    
    def help(self, command=None):
        """List commands, or get help for a command.
        
        command: command to get help for
        """
        return self.bitcoind.help(command)
    
    def importprivkey(self, bitcoinprivkey, label, rescan=None):
        """Adds a private key (as returned by dumpprivkey) to your wallet. 
        
        This may take a while, as a rescan is done, looking for existing transactions.
        
        bitcoinprivkey: 
        label: 
        rescan: True/False
        """
        return self.bitcoind.importprivkey(bitcoinprivkey, label, rescan)
    
    def keypoolrefill(self):
        """Fills the keypool, requires wallet passphrase to be set."""
        return self.bitcoind.keypoolrefill()
    
    def listaccounts(self, minconf=1):
        """Returns Object that has account names as keys, account balances as values.
        
        minconf: minimum number of confirmations to count
        """        
        return self.bitcoind.listaccounts(minconf)
    
    def listaddressgroupings(self):
        """Returns all addresses in the wallet and info used for coincontrol."""
        return self.bitcoind.listaddressgroupings()
    
    def listreceivedbyaccount(self, minconf=1, includeempty=False):
        """Returns an array of objects containing:
        - account: the account of the receiving addresses
        - amount: total amount received by addresses with this account
        - confirmations: number of confirmations of the most recent transaction included
        
        minconf: minimum number of confirmations to count
        includeempty: True/False
        """
        return self.bitcoind.listreceivedbyaccount(minconf, includeempty)
    
    def listreceivedbyaddress(self, minconf=1, includeempty=False):
        """Returns an array of objects containing:
        - address: receiving address
        - account: the account of the receiving address
        - amount: total amount received by the address
        - confirmations: number of confirmations of the most recent transaction included
        
        To get a list of accounts on the system, execute bitcoind listreceivedbyaddress 0 true
        
        minconf: minimum number of confirmations to count
        includeempty: True/False
        """
        return self.bitcoind.listreceivedbyaddress(minconf, includeempty)
    
    def listsinceblock(self, blockhash, targetconfirmations):
        """Get all transactions in blocks since block [blockhash], or all transactions if omitted.
        
        blockhash:
        target-confirmations: 
        """
        return self.bitcoind.listsinceblock(blockhash, targetconfirmations)
    
    def listtransactions(self, account, count=10, numfrom=0):
        """Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]. 
        
        account: if [account] not provided will return recent transaction from all accounts
        count: 
        from: 
        """
        return self.bitcoind.listtransactions(account, count, numfrom)
    
    def listunspent(self, minconf=1, maxconf=999999):
        """Returns array of unspent transaction inputs in the wallet.
        
        minconf: 
        maxconf: 
        """
        return self.bitcoind.listunspent(minconf, maxconf)
    
    def listlockunspent(self):
        """Returns list of temporarily unspendable outputs."""
        return self.bitcoind.listlockunspent()
    
    def lockunspent(self):
        return None
    
    def move(self, fromaccount, toaccount, minconf=1, comment=None):
        """Move from one account in your wallet to another.
        
        fromaccount: account to move from
        toaccount: account to move to
        minconf: minimum number of confirmations
        comment: optional comment        
        """
        return self.bitcoind.move(fromaccount, toaccount, minconf, comment)
    
    def sendfrom(self, fromaccount, tobitcoinaddress, amount, minconf=1, comment=None, commentto=None):
        """Will send the given amount to the given address, ensuring the account has a valid balance using [minconf] confirmations. Returns the transaction ID if successful (not in JSON object).
        
        fromaccount: account to send from
        tobitcoinaddress: address to send to
        <amount> is a real and is rounded to 8 decimal places. 
        minconf: minimum number of confirmations
        comment: optional comment
        comment-to: optional comment-to
        """
        return self.bitcoind.sendfrom(fromaccount, tobitcoinaddress, amount, minconf, comment, commentto)
    
    def sendmany(self):
        return None
    
    def sendrawtransaction(self):
        return None
    
    def sendtoaddress(self, bitcoinaddress, amount, comment=None, commentto=None):
        """Sends bitcoins to an address. Returns the transaction ID <txid> if successful.
        
        bitcoinaddress: address to send to
        amount: <amount> is a real and is rounded to 8 decimal places. 
        comment: optional comment
        comment-to: optional comment-to
        """
        return self.bitcoind.sendtoaddress(bitcoinaddress, amount, comment, commentto)
    
    def setaccount(self, bitcoinaddress, account):
        """Sets the account associated with the given address.
        
        Assigning address that is already assigned to the same account will create a new address associated with that account.
        
        bitcoinaddress: address to associate with
        account: account to associate with
        """
        return self.bitcoind.setaccount(bitcoinaddress, account)
    
    def setgenerate(self):
        return None

    def settxfee(self, amount):
        """ Sets a transaction fee.
        
        amount: <amount> is a real and is rounded to the nearest 0.00000001
        """
        return self.bitcoind.settxfee(amount)
    
    def signmessage(self, bitcoinaddress, message):
        """Sign a message with the private key of an address.
        
        bitcoinaddress: address to send message to
        message: message to send
        """
        return self.bitcoind.signmessage(bitcoinaddress, message)
    
    def signrawtransaction(self):
        return None
    
    def stop(self):
        """Stop bitcoin server."""
        return self.bitcoind.stop()
    
    def submitblock(self):
        return None
    
    def validateaddress(self, bitcoinaddress):
        """Return information about <bitcoinaddress>.
        
        bitcoinaddress: address to retrieve information about
        """
        return self.bitcoind.validateaddress(bitcoinaddress)
    
    def verifymessage(self, bitcoinaddress, signature, message):
        """Verify a signed message.
        
        bitcoinaddress: address received from
        signature: signature of message
        message: message content
        """
        return self.bitcoind.verifymessage(bitcoinaddress, signature, message)
    
    def walletlock(self):
        """	 Removes the wallet encryption key from memory, locking the wallet. 
        
        After calling this method, you will need to call walletpassphrase again 
        before being able to call any methods which require the wallet to be unlocked.
        """
        return self.bitcoind.walletlock()
    
    def walletpassphrase(self, passphrase, timeout):
        """Stores the wallet decryption key in memory for <timeout> seconds.
        
        passphrase: passphrase to decrypt wallet with
        timeout: time before key expires
        """
        return self.bitcoind.walletpassphrase(passphrase, timeout)
示例#7
0
import os

# to measure processing time and elapsed block time
from datetime import datetime
startTime = datetime.utcnow()

# for sleep
import time

# for reading JSON block info
import json

# initialize bitcoin RPC connection and gather mempool info
import bitcoinAuth
from bitcoinrpc import AuthServiceProxy, JSONRPCException
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                  (bitcoinAuth.USER, bitcoinAuth.PW))
mempoolInfo = rpc_connection.getmempoolinfo()
numTx = mempoolInfo['size']
mempoolSize = mempoolInfo['bytes'] / float(1000000)

# load recent block info from file
f = open('data/block_list.txt', 'r')
d = f.read()
blockData = json.loads(d)
f.close()

# find the blocks that happened in past n hours
now = datetime.utcnow()
elapsed = 120
latest = True
blockTimes = []
示例#8
0
curses.init_pair(COLOR_GOLD, 3, 0)
COLOR_LTBLUE = 7
curses.init_pair(COLOR_LTBLUE, 6, 0)
COLOR_GREEN = 2
curses.init_pair(COLOR_GREEN, 2, 0)
COLOR_WHITE = 3
curses.init_pair(COLOR_WHITE, 7, 0)
COLOR_RED = 6
curses.init_pair(COLOR_RED, 1, 0)
COLOR_PINK = 5
curses.init_pair(COLOR_PINK, 5, 0)
COLOR_BLUE = 4
curses.init_pair(COLOR_BLUE, 4, 0)

# init the bitcoin RPC connection
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(bitcoinAuth.USER,bitcoinAuth.PW))

# init LED grid, rows and chain length are both required parameters:
matrix = Adafruit_RGBmatrix(32, 1)

# this matrix buffers the LED grid output to avoid using clear() every frame
buffer = []

# this array stores hashes of blocks that confirms my incoming transactions
myTxBlocks = []
# on startup, load 10 (bitcoin RPC call default) recent receive transactions into that array
listTx = rpc_connection.listtransactions()
for tx in listTx:
	if tx['category'] == 'receive' and tx['confirmations'] > 0:
		myTxBlocks.append(tx['blockhash'])
示例#9
0
ch.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
root.addHandler(ch)
root.setLevel(getattr(logging, args.log_level))

config = {'pass': None}
for line in args.config_path:
    pts = line.strip().split("=")
    if len(pts) != 2:
        continue
    config[pts[0]] = pts[1]

if args.passphrase_file:
    config['pass'] = args.passphrase_file.read().strip()

rpc_connection = AuthServiceProxy(
    "http://{rpcuser}:{rpcpassword}@localhost:{rpcport}/"
    .format(**config))

try:
    balance = rpc_connection.getbalance()
except CoinRPCException as e:
    logging.error("Unable to retrieve balance, rpc returned {}".format(e))
    exit(1)

try:
    balance = Decimal(balance)
except ValueError:
    logging.error("Bogus data returned by balance call, exiting"
                  .format(str(balance)[:100]))
    exit(1)
示例#10
0
#############
# constants #
#############

rootdir = sys.path[0]
txFile = rootdir + '/data/tx.txt'

##############
# initialize #
##############

# from command line paramaters
script, txid = argv

# initialize bitcoin RPC connection and gather info
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                  (bitcoinAuth.USER, bitcoinAuth.PW))

#############
# functions #
#############


# because JSON dump hates decimals for soem reason
def allToString(obj):
    return str(obj)


########
# main #
########
示例#11
0
#############
# constants #
#############

rootdir = sys.path[0]
txFile =  rootdir + '/data/tx.txt'

##############
# initialize #
##############

# from command line paramaters
script, txid = argv

# initialize bitcoin RPC connection and gather info
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(bitcoinAuth.USER,bitcoinAuth.PW))


#############
# functions #
#############

# because JSON dump hates decimals for soem reason
def allToString(obj):
	return str(obj)


########
# main #
########
示例#12
0
import os

# to measure processing time and elapsed block time
from datetime import datetime
startTime = datetime.utcnow()

# for sleep
import time

# for reading JSON block info
import json

# initialize bitcoin RPC connection and gather mempool info
import bitcoinAuth
from bitcoinrpc import AuthServiceProxy, JSONRPCException
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332"%(bitcoinAuth.USER,bitcoinAuth.PW))
mempoolInfo = rpc_connection.getmempoolinfo()
numTx = mempoolInfo['size']
mempoolSize = mempoolInfo['bytes']/float(1000000)

# load recent block info from file
f = open('data/block_list.txt','r')
d = f.read()
blockData = json.loads(d)
f.close()

# find the blocks that happened in past n hours
now = datetime.utcnow()
elapsed=120
latest = True
blockTimes =[]
示例#13
0
def create_app(config='/config.yml', celery=False):
    # initialize our flask application
    app = Flask(__name__, static_folder='../static', static_url_path='/static')

    # set our template path and configs
    app.jinja_loader = FileSystemLoader(os.path.join(root, 'templates'))
    config_vars = yaml.load(open(root + config))
    # inject all the yaml configs
    app.config.update(config_vars)
    app.logger.info(app.config)

    app.rpc_connection = AuthServiceProxy(
        "http://{0}:{1}@{2}:{3}/"
        .format(app.config['coinserv']['username'],
                app.config['coinserv']['password'],
                app.config['coinserv']['address'],
                app.config['coinserv']['port'],
                pool_kwargs=dict(maxsize=app.config.get('maxsize', 10))))

    app.merge_rpc_connection = {}
    for cfg in app.config['merge']:
        if not cfg['enabled']:
            continue
        app.merge_rpc_connection[cfg['currency_name']] = AuthServiceProxy(
            "http://{0}:{1}@{2}:{3}/"
            .format(cfg['coinserv']['username'],
                    cfg['coinserv']['password'],
                    cfg['coinserv']['address'],
                    cfg['coinserv']['port'],
                    pool_kwargs=dict(maxsize=app.config.get('maxsize', 10))))

    # add the debug toolbar if we're in debug mode...
    if app.config['DEBUG']:
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(app)
        app.logger.handlers[0].setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(filename)s:%(lineno)d]'))

    # map all our merged coins into something indexed by type for convenience
    app.config['merged_cfg'] = {cfg['currency_name']: cfg for cfg in app.config['merge']}

    # register all our plugins
    db.init_app(app)
    cache_config = {'CACHE_TYPE': 'redis'}
    cache_config.update(app.config.get('main_cache', {}))
    cache.init_app(app, config=cache_config)

    if not celery:
        hdlr = logging.FileHandler(app.config.get('log_file', 'webserver.log'))
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        app.logger.addHandler(hdlr)
        app.logger.setLevel(logging.INFO)

        # try and fetch the git version information
        try:
            output = subprocess.check_output("git show -s --format='%ci %h'",
                                             shell=True).strip().rsplit(" ", 1)
            app.config['hash'] = output[1]
            app.config['revdate'] = output[0]
        # celery won't work with this, so set some default
        except Exception:
            app.config['hash'] = ''
            app.config['revdate'] = ''

    # filters for jinja
    @app.template_filter('fader')
    def fader(val, perc1, perc2, perc3, color1, color2, color3):
        """
        Accepts a decimal (0.1, 0.5, etc) and slots it into one of three categories based
        on the percentage.
        """
        if val > perc3:
            return color3
        if val > perc2:
            return color2
        return color1

    @app.template_filter('sig_round')
    def sig_round_call(*args, **kwargs):
        return sig_round(*args, **kwargs)

    @app.template_filter('duration')
    def time_format(seconds):
        # microseconds
        if seconds > 3600:
            return "{}".format(timedelta(seconds=seconds))
        if seconds > 60:
            return "{:,.2f} mins".format(seconds / 60.0)
        if seconds <= 1.0e-3:
            return "{:,.4f} us".format(seconds * 1000000.0)
        if seconds <= 1.0:
            return "{:,.4f} ms".format(seconds * 1000.0)
        return "{:,.4f} sec".format(seconds)

    @app.template_filter('time_ago')
    def pretty_date(time=False):
        """
        Get a datetime object or a int() Epoch timestamp and return a
        pretty string like 'an hour ago', 'Yesterday', '3 months ago',
        'just now', etc
        """

        now = datetime.utcnow()
        if type(time) is int:
            diff = now - datetime.utcfromtimestamp(time)
        elif isinstance(time, datetime):
            diff = now - time
        elif not time:
            diff = now - now
        second_diff = diff.seconds
        day_diff = diff.days

        if day_diff < 0:
            return ''

        if day_diff == 0:
            if second_diff < 60:
                return str(second_diff) + " seconds ago"
            if second_diff < 120:
                return "a minute ago"
            if second_diff < 3600:
                return str(second_diff / 60) + " minutes ago"
            if second_diff < 7200:
                return "an hour ago"
            if second_diff < 86400:
                return str(second_diff / 3600) + " hours ago"
        if day_diff == 1:
            return "Yesterday"
        if day_diff < 7:
            return str(day_diff) + " days ago"
        if day_diff < 31:
            return str(day_diff/7) + " weeks ago"
        if day_diff < 365:
            return str(day_diff/30) + " months ago"
        return str(day_diff/365) + " years ago"

    from .tasks import celery
    celery.conf.update(app.config)

    # Route registration
    # =========================================================================
    from . import views, models, api, rpc_views
    app.register_blueprint(views.main)
    app.register_blueprint(api.api, url_prefix='/api')

    return app