def store_contract(contract, pipe=None):
        """
        Store a contract in the database.

        Arguments:
        contract    -- contract object to be store in the database

        Returns:
        list        -- list containing results of each query used to store an object (0s and 1s)
                    0s indicate that the field was updated (already present)
                    1s indicate that the field is new and was stored
            OR
        pipeline    -- pipeline object to continue inserting into redis with (if pipe was passed in)
        """
        rs = RedisService()
        rs.store_object(contract)
        r = rs._connect()
        pipe_created = False
        if pipe == None:
            pipe = r.pipeline()
            pipe_created = True
        pipe.zadd(ContractFilter.RATE, contract.rate, contract._hash)
        pipe.zadd(ContractFilter.AMOUNT, contract.amount, contract._hash)
        pipe.zadd(ContractFilter.CREATED, contract.created_timestamp,
                  contract._hash)
        pipe.zadd(ContractFilter.DURATION, contract.duration, contract._hash)
        pipe.zadd(ContractFilter.SIGN_END, contract.sign_end_timestamp,
                  contract._hash)

        if pipe_created:
            return pipe.execute()
        else:
            return pipe
 def on_message(self, ws, message):
     msg = json.loads(message)
     if isinstance(msg, list) and msg[1] == "tu":
         # add this to the db
         price_stamp = self.trade_pricestamp_adaptor(msg)
         price_stamp.update_hash()
         rs = RedisService()
         rs.store_object(price_stamp)
         r = rs._connect()
         r.zadd('price_stamps', price_stamp.timestamp, price_stamp.price)
Example #3
0
    def get_all_mempool_objects(obj):
        rs = RedisService()
        r = rs._connect()

        name = obj._to_index()[-1] + ':is_mempool:1'
        object_list = r.smembers(name)

        objects = list()
        for object_hash in object_list:
            t = rs.get_object_by_full_key(object_hash, obj)
            objects.append(t)

        return objects
    def get_all_contracts_by_owner(owner_key):
        """
        Get all contracts for a given owner public key.

        Arguments:
        owner_key   -- public key to search database by

        Returns:
        list    -- list of contracts that are owned by the public key supplied
        """

        rs = RedisService()
        r = rs._connect()
        contract_hashes = r.smembers('contract:owner:' + owner_key)
        contracts = list()
        for contract_hash in contract_hashes:
            contract = ContractService.get_contract_by_full_key(contract_hash)
            contracts.append(contract)
        return contracts
Example #5
0
    def mine_block(miner_priv_key, last_block):
        balances = BlockService.get_all_balances()

        transactions = BaseObjectService.get_all_mempool_objects(Transaction)
        transactions_to_add = []
        for transaction in transactions:
            if len(transactions_to_add) == 100:
                break
            valid, balances = Miner.validate_transaction(balances, transaction)
            if valid:
                transactions_to_add.append(transaction)

        pos_transactions = BaseObjectService.get_all_mempool_objects(
            PosTransaction)
        pos_transactions_to_add = []
        for pos_transaction in pos_transactions:
            if len(pos_transactions_to_add) == 10:
                break
            valid, balances = Miner.validate_pos_transaction(
                balances, pos_transaction)
            if valid:
                pos_transactions_to_add.append(pos_transaction)

        contract_transactions = BaseObjectService.get_all_mempool_objects(
            ContractTransaction)
        contract_transactions_to_add = []
        for contract_transaction in contract_transactions:
            if len(contract_transactions_to_add) == 10:
                break
            valid, balances = Miner.validate_contract_transaction(
                balances, contract_transaction)
            if valid:
                contract_transactions_to_add.append(contract_transaction)

        contracts = BaseObjectService.get_all_mempool_objects(Contract)
        contracts_to_add = []
        for contract in contracts:
            if len(contracts_to_add) == 20:
                break
            valid, balances = Miner.validate_contract(balances, contract)
            if valid:
                contracts_to_add.append(contract)

        signed_contracts = BaseObjectService.get_all_mempool_objects(
            SignedContract)
        signed_contracts_to_add = []
        for signed_contract in signed_contracts:
            print('signed_contract:' + signed_contract._hash)
            if len(signed_contracts_to_add) == 20:
                break
            valid, balances = Miner.validate_signed_contract(
                balances, signed_contract)
            if valid:
                signed_contracts_to_add.append(signed_contract)

        terminated_contracts_to_add = []
        signed_contracts_to_check = SignedContractService.get_all_open_signed_contracts(
        )
        for sc_to_check in signed_contracts_to_check:
            print('signed_c to check: ' + sc_to_check._hash)
            end_time = sc_to_check.signed_timestamp + sc_to_check.duration
            now = int(time.time())
            # print('signed_time=' + str(sc_to_check.signed_timestamp) + ' duration=' + str(sc_to_check.duration) + ' end time='+ str(end_time) + '  now=' + str(now) + '   end<=now=' + str(end_time<=now))
            if end_time <= now:
                rs = RedisService()
                r = rs._connect()
                prices = r.zrangebyscore('price_stamps',
                                         end_time - 2000,
                                         end_time + 2000,
                                         withscores=True)
                if len(prices) != 0:
                    price = min(prices, key=lambda x: abs(x[1] - end_time))
                    print('terminated contract: ' + sc_to_check._hash)
                    tc = TerminatedContract(sc_to_check._hash, price[0],
                                            end_time)
                    terminated_contracts_to_add.append(tc)
                else:
                    print('no prices found')

        last_block_hash = last_block._hash
        miner_pub_key = EcdsaHashing.recover_public_key_str(miner_priv_key)
        height = last_block.height + 1
        block = Block('', '', miner_pub_key, last_block_hash, height,
                      transactions_to_add, pos_transactions_to_add,
                      contract_transactions_to_add, contracts_to_add,
                      signed_contracts_to_add, terminated_contracts_to_add,
                      time.time())
        block.update_signature(miner_priv_key)
        block.update_hash()
        return block
    def get_contracts_by_filter(contract_filters, include_mempool):
        """
        Get contracts by a filter.

        Arguments:
        contract_filters    -- list of ContractFilter objects to filter database on
        include_mempool     -- True if results should include those in the mempool, false otherwise

        Returns:
        list    -- list of contracts based on filters passed in
        """
        rs = RedisService()
        r = rs._connect()

        contract_hashes = set()
        temp_hashes = set()
        mempool_list = list()
        mempool_set = set()

        if not include_mempool:
            mempool_list = r.smembers('contract:is_mempool:0')
            for mem_hash in mempool_list:
                mempool_set.add(
                    mem_hash[9:]
                )  # remove 'contract:' from the beginning of the key

        if not contract_filters:
            if include_mempool:
                in_mempool_list = r.smembers('contract:is_mempool:1')
                in_mempool_set = set()
                for mem_hash in in_mempool_list:
                    in_mempool_set.add(
                        mem_hash[9:]
                    )  # remove 'contract:' from the beginning of the key
                contract_hashes = in_mempool_set.union(mempool_set)
            else:
                contract_hashes = mempool_set.copy()
        else:
            for contract_filter in contract_filters:
                print("key: " + contract_filter.key + " | range: " +
                      str(contract_filter.minimum) + "->" +
                      str(contract_filter.maximum))
                hashes = r.zrangebyscore(contract_filter.key,
                                         contract_filter.minimum,
                                         contract_filter.maximum)
                temp_hashes = set(hashes)
                # if first filter
                if len(contract_hashes) == 0:
                    contract_hashes = temp_hashes.copy()
                    # if mempool contracts are to be ignored
                    if not include_mempool:
                        contract_hashes = contract_hashes.intersection(
                            mempool_set)
                    temp_hashes.clear()
                else:
                    # after first filter
                    contract_hashes = contract_hashes.intersection(temp_hashes)

        contracts = list()
        for contract_hash in contract_hashes:
            print(contract_hash)
            contract = rs.get_object_by_hash(contract_hash, Contract, r)
            contracts.append(contract)
        contracts.sort(key=lambda c: (-c.created_timestamp))
        return contracts[:50]