def get_transaction_by_rid(cls, selector, rid=False, raw=False):
        from block import Block
        from transaction import Transaction
        from crypt import Crypt
        ds = Config.get_bulletin_secret()
        if not rid:
            selectors = [TU.hash(ds + selector), TU.hash(selector + ds)]
        else:
            if not isinstance(selector, list):
                selectors = [
                    selector,
                ]

        for block in Mongo.db.blocks.find(
            {"transactions": {
                "$elemMatch": {
                    "relationship": {
                        "$ne": ""
                    }
                }
            }}):
            for transaction in block.get('transactions'):
                if transaction.get('rid') in selectors:
                    if 'relationship' in transaction:
                        if not raw:
                            try:
                                cipher = Crypt(Config.wif)
                                decrypted = cipher.decrypt(
                                    transaction['relationship'])
                                relationship = json.loads(decrypted)
                                transaction['relationship'] = relationship
                            except:
                                continue
                    return transaction
 def get_transactions(cls, raw=False, skip=None):
     if not skip:
         skip = []
     from block import Block
     from transaction import Transaction
     from crypt import Crypt
     transactions = []
     for block in Mongo.db.blocks.find(
         {"transactions": {
             "$elemMatch": {
                 "relationship": {
                     "$ne": ""
                 }
             }
         }}):
         for transaction in block.get('transactions'):
             try:
                 if transaction.get('id') in skip:
                     continue
                 if 'relationship' not in transaction:
                     continue
                 if not transaction['relationship']:
                     continue
                 if not raw:
                     cipher = Crypt(Config.wif)
                     decrypted = cipher.decrypt(transaction['relationship'])
                     relationship = json.loads(decrypted)
                     transaction['relationship'] = relationship
                 transaction['height'] = block['index']
                 transactions.append(transaction)
             except:
                 continue
     return transactions
 def get_relationships(cls):
     from block import Block
     from transaction import Transaction
     from crypt import Crypt
     relationships = []
     for block in cls.get_blocks():
         for transaction in block.get('transactions'):
             try:
                 cipher = Crypt(Config.wif)
                 decrypted = cipher.decrypt(transaction['relationship'])
                 relationship = json.loads(decrypted)
                 relationships.append(relationship)
             except:
                 continue
     return relationships
 def verify_message(cls, rid, message):
     from crypt import Crypt
     sent = False
     received = False
     txns = cls.get_transactions_by_rid(rid, rid=True, raw=True)
     shared_secrets = TU.get_shared_secrets_by_rid(rid)
     for txn in txns:
         for shared_secret in list(set(shared_secrets)):
             try:
                 cipher = Crypt(shared_secret.encode('hex'), shared=True)
                 decrypted = cipher.shared_decrypt(txn['relationship'])
                 signin = json.loads(decrypted)
                 if u'signIn' in signin and message == signin['signIn']:
                     if Config.public_key != txn['public_key']:
                         received = True
                     else:
                         sent = True
             except:
                 pass
     return sent, received
    def get_posts(cls, rids):
        from crypt import Crypt

        if not isinstance(rids, list):
            rids = [
                rids,
            ]

        posts_cache = Mongo.db.posts_cache.find({
            'rid': {
                '$in': rids
            }
        }).sort([('height', -1)])

        latest_block = cls.get_latest_block()

        if posts_cache.count():
            posts_cache = posts_cache[0]
            block_height = posts_cache['height']
        else:
            block_height = 0
        transactions = Mongo.db.blocks.aggregate([{
            "$match": {
                "index": {
                    '$gt': block_height
                }
            }
        }, {
            "$match": {
                "transactions": {
                    "$elemMatch": {
                        "relationship": {
                            "$ne": ""
                        }
                    }
                },
                "transactions.dh_public_key": '',
                "transactions.rid": ''
            }
        }, {
            "$unwind": "$transactions"
        }, {
            "$project": {
                "_id": 0,
                "txn": "$transactions",
                "height": "$index"
            }
        }, {
            "$match": {
                "txn.relationship": {
                    "$ne": ""
                },
                "txn.dh_public_key": '',
                "txn.rid": ''
            }
        }, {
            "$sort": {
                "height": 1
            }
        }])
        # transactions are all posts not yet cached by this rid
        # so we want to grab all bulletin secrets for this rid
        mutual_bulletin_secrets = cls.get_mutual_bulletin_secrets(rids)
        friends = list(
            set([
                friend['relationship']['bulletin_secret']
                for friend in cls.get_transactions_by_rid(rids, rid=True)
            ]))
        had_txns = False
        if friends:
            mutual_bulletin_secrets.extend(friends)
            for i, x in enumerate(transactions):
                for bs in mutual_bulletin_secrets:
                    try:
                        crypt = Crypt(hashlib.sha256(bs).hexdigest())
                        decrypted = crypt.decrypt(x['txn']['relationship'])
                        try:
                            decrypted = base64.b64decode(decrypted)
                        except:
                            continue
                        data = json.loads(decrypted)
                        x['txn']['relationship'] = data
                        if 'postText' in decrypted:
                            had_txns = True
                            print 'caching posts at height:', x['height']
                            for rid in rids:
                                Mongo.db.posts_cache.update(
                                    {
                                        'rid': rid,
                                        'height': x['height'],
                                        'id': x['txn']['id'],
                                        'bulletin_secret': bs
                                    }, {
                                        'rid': rid,
                                        'height': x['height'],
                                        'id': x['txn']['id'],
                                        'txn': x['txn'],
                                        'bulletin_secret': bs
                                    },
                                    upsert=True)
                    except:
                        pass
        if not had_txns:
            for rid in rids:
                Mongo.db.posts_cache.insert({
                    'rid': rid,
                    'height': latest_block['index']
                })

        for x in Mongo.db.posts_cache.find({'rid': {'$in': rids}}):
            if 'txn' in x:
                x['txn']['height'] = x['height']
                x['txn']['bulletin_secret'] = x['bulletin_secret']
                yield x['txn']
    def get_transactions_by_rid(cls,
                                selector,
                                rid=False,
                                raw=False,
                                returnheight=True,
                                bulletin_secret=None):
        #selectors is old code before we got an RID by sorting the bulletin secrets
        from block import Block
        from transaction import Transaction
        from crypt import Crypt
        ds = Config.get_bulletin_secret()

        if not rid:
            selectors = [TU.hash(ds + selector), TU.hash(selector + ds)]
        else:
            if not isinstance(selector, list):
                selectors = [
                    selector,
                ]
            else:
                selectors = selector

        transactions_by_rid_cache = Mongo.db.transactions_by_rid_cache.find({
            'raw':
            raw,
            'rid':
            rid,
            'bulletin_secret':
            bulletin_secret,
            'returnheight':
            returnheight,
            'selector': {
                '$in': selectors
            }
        }).sort([('height', -1)])
        latest_block = cls.get_latest_block()
        if transactions_by_rid_cache.count():
            transactions_by_rid_cache = transactions_by_rid_cache[0]
            block_height = transactions_by_rid_cache['height']
        else:
            block_height = 0
        transactions = []
        blocks = Mongo.db.blocks.find({
            "transactions.rid": {
                "$in": selectors
            },
            "transactions": {
                "$elemMatch": {
                    "relationship": {
                        "$ne": ""
                    }
                }
            },
            'index': {
                '$gt': block_height
            }
        })
        for block in blocks:
            for transaction in block.get('transactions'):
                if 'relationship' in transaction and transaction[
                        'relationship']:
                    if returnheight:
                        transaction['height'] = block['index']
                    if not raw:
                        try:
                            cipher = Crypt(Config.wif)
                            decrypted = cipher.decrypt(
                                transaction['relationship'])
                            relationship = json.loads(decrypted)
                            transaction['relationship'] = relationship
                        except:
                            continue
                    for selector in selectors:
                        print 'caching transactions_by_rid at height:', block[
                            'index']
                        Mongo.db.transactions_by_rid_cache.insert({
                            'raw':
                            raw,
                            'rid':
                            rid,
                            'bulletin_secret':
                            bulletin_secret,
                            'returnheight':
                            returnheight,
                            'selector':
                            selector,
                            'txn':
                            transaction,
                            'height':
                            block['index']
                        })
                    transactions.append(transaction)
        if not transactions:
            for selector in selectors:
                Mongo.db.transactions_by_rid_cache.insert({
                    'raw':
                    raw,
                    'rid':
                    rid,
                    'bulletin_secret':
                    bulletin_secret,
                    'returnheight':
                    returnheight,
                    'selector':
                    selector,
                    'height':
                    latest_block['index']
                })
        for x in Mongo.db.transactions_by_rid_cache.find({
                'raw': raw,
                'rid': rid,
                'returnheight': returnheight,
                'selector': {
                    '$in': selectors
                }
        }):
            if 'txn' in x:
                yield x['txn']