Ejemplo n.º 1
0
    async def patch(self, user):
        """Update existing relayer"""
        relayer = self.request_body
        relayer_id = relayer.get('id', None)
        relayer_owner = relayer.get('owner', None)

        verify_user(user, relayer_owner)

        if not relayer_id:
            raise MissingArgumentException('missing relayer id')

        del relayer['id']

        if relayer.get('new_owner', None):
            relayer['owner'] = relayer['new_owner']
            del relayer['new_owner']

        if not self.validator.validate(relayer):
            raise InvalidValueException(str(
                self.validator.document_error_tree))

        normalized_relayer = self.validator.normalized(relayer)

        try:
            query = (Relayer.update(**normalized_relayer).where(
                Relayer.id == relayer_id).returning(Relayer))
            cursor = query.execute()
            self.json_response(model_to_dict(cursor[0]))
        except IndexError:
            raise InvalidValueException(
                'relayer id={param} does not exist'.format(
                    param=str(relayer_id)))
Ejemplo n.º 2
0
    async def patch(self, user):
        """Update existing relayer"""
        relayer = self.request_body
        relayer_coinbase = relayer.get('coinbase', None)
        relayer_owner = relayer.get('owner', None)
        name = relayer.get('name', None)

        verify_user(user, relayer_owner)

        if relayer_coinbase == None:
            raise MissingArgumentException('missing relayer coinbase')

        del relayer['id']

        if relayer.get('new_owner', None):
            relayer['owner'] = relayer['new_owner']
            del relayer['new_owner']

        normalized_relayer = self.validator.normalized(relayer)

        try:
            b = Blockchain()
            coinbase = b.web3.toChecksumAddress(relayer_coinbase)

            db_relayer = Relayer.select().where(
                Relayer.coinbase == coinbase).get()
            db_relayer = model_to_dict(db_relayer)

            if user.lower() != db_relayer['owner'].lower():
                raise MissingArgumentException('wrong owner')

            r = b.getRelayerByCoinbase(coinbase)

            if r[1].lower() != relayer['owner'].lower():
                raise InvalidValueException('owner required')

            query = (Relayer.update(**normalized_relayer).where(
                Relayer.coinbase == coinbase).returning(Relayer))
            cursor = query.execute()

            b.updateRelayer(coinbase)

            try:
                requests.put(
                    urljoin(settings['tomodex'], '/api/relayer') +
                    '?relayerAddress=' + coinbase + '&relayerName=' + name +
                    '&relayerUrl=' + relayer['link'] + '&authKey=' +
                    settings['tomodex_auth'])
            except:
                logger.error('Update tomodex failed')

            self.json_response(model_to_dict(cursor[0]))
        except IndexError:
            raise InvalidValueException(
                'relayer id={param} does not exist'.format(
                    param=str(relayer_coinbase)))
Ejemplo n.º 3
0
def verify_user(user, relayer_owner):
    if not user:
        raise InvalidValueException('Missing user address')

    if not relayer_owner:
        raise InvalidValueException('Missing relayer owner address')

    if user.lower() != relayer_owner.lower():
        raise InvalidValueException(
            'Owner address does not match relayer_owner address')
Ejemplo n.º 4
0
    def convert(sess, star):
        try:
            sess = Session.NUMBER_TO_TEXT_MAP[sess]
        except:
            raise InvalidValueException("Invalid number of sessions")

        if star in list(Session.NUMBER_TO_TEXT_MAP.values())[:5]:
            star = list(Session.NUMBER_TO_TEXT_MAP.keys())[list(
                Session.NUMBER_TO_TEXT_MAP.values()).index(star)]
        else:
            raise InvalidValueException("Invalid number of stars")

        return print(
            f"I completed {sess} sessions and I rated my expert {star} stars")
Ejemplo n.º 5
0
    def get(self):
        from eth_account.messages import defunct_hash_message

        user_address = self.get_argument('address', None)
        signature = self.get_argument('signature', None)

        if not user_address or not signature:
            raise MissingArgumentException('Missing required argument(s)')

        web3 = self.application.blockchain.web3

        hased_message, signing_address = '', ''

        try:
            hased_message = defunct_hash_message(text=SIGNATURE_MSG)
            signing_address = web3.eth.account.recoverHash(hased_message,
                                                           signature=signature)
        except Exception:
            raise InvalidValueException(
                'Signature message is not a valid hex string')

        if signing_address.lower() != user_address.lower():
            logger.debug('Signing_addr: %s', signing_address)
            logger.debug('Provided_addr: %s', user_address)
            raise UserAuthorizationException(
                'User Address not matching Signature Address')

        token, expiry = encode_payload({'address': user_address})
        return self.json_response({'token': token, 'exp': expiry})
Ejemplo n.º 6
0
    async def post(self, user):
        """Add new relayer"""
        relayer = self.request_body
        name = relayer.get('name', None)

        verify_user(user, relayer['owner'])

        normalized_relayer = self.validator.normalized(relayer)

        b = Blockchain()
        coinbase = b.web3.toChecksumAddress(relayer['coinbase'])
        r = b.getRelayerByCoinbase(coinbase)

        if r[1].lower() != user.lower():
            raise InvalidValueException('owner required')

        b.updateRelayer(coinbase)

        query = (Relayer.update(**normalized_relayer).where(
            Relayer.coinbase == coinbase).returning(Relayer))
        cursor = query.execute()

        db_relayer = Relayer.select().where(Relayer.coinbase == coinbase).get()
        db_relayer = model_to_dict(db_relayer)

        try:
            requests.put(
                urljoin(settings['tomodex'], '/api/relayer') +
                '?relayerAddress=' + coinbase + '&relayerName=' + name +
                '&relayerUrl=' + db_relayer['link'] + '&authKey=' +
                settings['tomodex_auth'])
        except:
            logger.error('Update tomodex failed')

        self.json_response(model_to_dict(cursor[0]))
Ejemplo n.º 7
0
    async def post(self):
        payload = self.request_body.get('contract', None)

        if not payload:
            raise InvalidValueException('relayer payload is empty')

        async with self.application.objects.atomic():
            contract = await self.application.objects.create(
                Contract, **payload)
            self.json_response(model_to_dict(contract))
Ejemplo n.º 8
0
    async def patch(self):
        contract = self.request_body
        contract_id = contract.get('id', None)

        if not contract_id:
            raise InvalidValueException('Missing contract id')

        del contract['id']

        try:
            query = (Contract.update(**contract).where(
                Contract.id == contract_id).returning(Contract))
            cursor = query.execute()
            self.json_response(model_to_dict(cursor[0]))
        except IndexError:
            raise InvalidValueException(
                'contract id={param} does not exist'.format(
                    param=str(contract_id)))
        except ProgrammingError:
            raise InvalidValueException(
                'update payload is invalid: {param}'.format(
                    param=str(contract)))
Ejemplo n.º 9
0
    def get(self):
        user_address = self.get_argument('address', None)

        if not user_address:
            raise MissingArgumentException('Missing user address')

        try:
            checksum_addr = self.application.blockchain.web3.toChecksumAddress(
                user_address.lower())
            self.application.blockchain.web3.eth.getBalance(checksum_addr)
            token, expiry = encode_payload({'address': user_address})
            return self.json_response({'token': token, 'exp': expiry})
        except Exception as err:
            raise InvalidValueException('address is not valid')
Ejemplo n.º 10
0
    async def post(self, user):
        """Add new relayer"""
        relayer = self.request_body

        verify_user(user, relayer['owner'])

        if not self.validator.validate(relayer):
            raise InvalidValueException(str(
                self.validator.document_error_tree))

        normalized_relayer = self.validator.normalized(relayer)

        obj = await self.application.objects.create(Relayer,
                                                    **normalized_relayer)
        self.json_response(model_to_dict(obj))
Ejemplo n.º 11
0
    async def delete(self, user):
        """Delete a relayer"""
        relayer_id = self.get_argument('id', None)

        if not relayer_id:
            raise MissingArgumentException('missing relayer id')

        try:
            relayer = Relayer.select().where(Relayer.owner == user,
                                             Relayer.id == relayer_id).get()
            relayer.delete_instance()
            self.json_response({})
        except Exception:
            raise InvalidValueException(
                'invalid relayer: relayer with id={} or owner={} does not exist'
                .format(relayer_id, user))
Ejemplo n.º 12
0
    async def post(self):
        contracts = self.request_body

        if not contracts:
            raise InvalidValueException('Invalid empty payload')

        if not isinstance(contracts, list):
            # NOTE: might need to implement Schema Validator
            contract = contracts
            obj = await self.application.objects.create(Contract, **contract)
            return self.json_response(model_to_dict(obj))

        async with self.application.objects.atomic():
            result = []
            for contract in contracts:
                obj = await self.application.objects.create(
                    Contract, **contract)
                result.append(model_to_dict(obj))

            return self.json_response(result)
Ejemplo n.º 13
0
    async def post(self, user=None):
        """Add new tokens"""
        tokens = self.request_body

        if not tokens:
            raise InvalidValueException('Invalid empty payload')

        if not isinstance(tokens, list):
            token = tokens
            obj = await self.application.objects.create(Token, **token)
            return self.json_response(model_to_dict(obj))

        async with self.application.objects.atomic():
            result = []
            for token in tokens:
                # required_fields = ['name', 'symbol', 'address', 'total_supply']
                obj = await self.application.objects.create(Token, **token)
                result.append(model_to_dict(obj))

            self.json_response(result)
Ejemplo n.º 14
0
    async def delete(self, user):
        """Delete a relayer"""
        coinbase = self.get_argument('coinbase', None)
        b = Blockchain()
        coinbase = b.web3.toChecksumAddress(coinbase)

        if not coinbase:
            raise MissingArgumentException('missing relayer coinbase')

        try:
            relayer = Relayer.select().where(
                Relayer.coinbase == coinbase).get()
            db_relayer = model_to_dict(relayer)

            if user.lower() != db_relayer['owner'].lower():
                raise MissingArgumentException('wrong owner')

            relayer.delete_instance()
            self.json_response({})
        except Exception:
            raise InvalidValueException(
                'invalid relayer: relayer with id={} or owner={} does not exist'
                .format(coinbase, user))
Ejemplo n.º 15
0
    async def post(self, user=None):
        """Add new tokens"""
        tokens = self.request_body

        if not tokens:
            raise InvalidValueException('Invalid empty payload')

        b = Blockchain()
        if not isinstance(tokens, list):
            token = tokens
            address = b.web3.toChecksumAddress(token['address'])
            b.updateToken(address)
            obj = Token.select().where(Token.address == address).get()
            return self.json_response(model_to_dict(obj))

        result = []
        for token in tokens:
            address = b.web3.toChecksumAddress(token['address'])
            b.updateToken(address)
            obj = Token.select().where(Token.address == address).get()
            result.append(model_to_dict(obj))

        self.json_response(result)
Ejemplo n.º 16
0
    async def post(self, user):
        mail = self.request_body

        if not mail.get('feedback') or len(mail['feedback']) < 20 or len(
                mail['feedback']) > 400:
            raise InvalidValueException('Missing or invalid feedback message')