Example #1
0
    def validate_transaction(self, tx_hash) -> Tuple[bool, List[str]]:
        """ Validate that a transactions exists and that its values generally
        look correct.
        """
        transactions = self.select(
            "SELECT {} FROM transaction WHERE hash = {};", self.columns,
            tx_hash)

        count = len(transactions)

        if count < 1:
            return (False, ["No transaction"])

        elif count > 1:
            raise ValueError('Invalid result, duplicate transactions')

        tx = transactions[0]

        return validate_conditions([
            (is_256bit_hash(tx.hash), "Transaction hash is invalid"),
            (tx.dirty is False, "Transaction is marked dirty"),
            (tx.block_number is not None, "block_number missing"),
            (is_address(tx.from_address), "from_address is not an address"),
            (is_address(tx.to_address), "to_address is not an address"),
            (tx.value is not None, "value missing"),
            (tx.gas_price is not None, "gas_price missing"),
            (tx.gas_limit is not None, "gas_limit missing"),
            (tx.nonce is not None, "nonce missing"),
            (tx.input is not None, "input missing"),
        ])
Example #2
0
    def validate_block(self, block_number) -> Tuple[bool, List[str]]:
        """ Validate that a block number exists and that its values generally
        look correct.
        """
        blocks = self.select("SELECT {} FROM block WHERE block_number = {};",
                             self.columns, block_number)

        count = len(blocks)

        if count < 1:
            return (False, ["No block"])

        elif count > 1:
            raise ValueError('Invalid result, duplicate blocks')

        block = blocks[0]

        return validate_conditions([
            (block.block_timestamp is not None, "block_timestamp is missing"),
            (block.difficulty is not None, "difficulty missing"),
            (block.hash is not None, "block hash missing"),
            (is_256bit_hash(block.hash), "block hash is not a hash"),
            (block.miner is not None, "miner missing"),
            (is_address(block.miner), "miner is not an address"),
            (block.gas_used is not None, "gas_used missing"),
            (block.gas_limit is not None, "gas_limit missing"),
            (block.nonce is not None, "nonce missing"),
            (block.size is not None, "size missing"),
        ])
def test_get_swarm(agency, blockchain_ursulas):
    _token_agent, staking_agent, _policy_agent = agency

    swarm = staking_agent.swarm()
    swarm_addresses = list(swarm)
    assert len(swarm_addresses) == len(blockchain_ursulas) + 1

    # Grab a staker address from the swarm
    staker_addr = swarm_addresses[0]
    assert isinstance(staker_addr, str)
    assert is_address(staker_addr)
Example #4
0
def test_get_swarm(agency, blockchain_ursulas, test_registry):
    staking_agent = ContractAgency.get_agent(StakingEscrowAgent,
                                             registry=test_registry)

    swarm = staking_agent.swarm()
    swarm_addresses = list(swarm)
    assert len(swarm_addresses) == len(blockchain_ursulas) + 1

    # Grab a staker address from the swarm
    staker_addr = swarm_addresses[0]
    assert isinstance(staker_addr, str)
    assert is_address(staker_addr)
Example #5
0
    def get_by_address(self, address: str) -> list:
        """ Get a list of transactions for an address """

        if not is_address(address):
            raise ValueError("Address is invalid")

        result = self.select(
            "SELECT {} FROM transaction"
            " WHERE from_address = {} OR to_address = {};", self.columns,
            address, address)

        return result
Example #6
0
 def __handle_keyfile(self, path: str) -> Tuple[str, dict]:
     """
     Read a single keystore file from the disk and return its decoded json contents then internally
     cache it on the keystore instance. Raises InvalidKeyfile if the keyfile is missing or corrupted.
     """
     try:
         address, key_metadata = self.__read_keyfile(path=path)
     except FileNotFoundError:
         error = f"No such keyfile '{path}'"
         raise self.InvalidKeyfile(error)
     except JSONDecodeError:
         error = f"Invalid JSON in keyfile at {path}"
         raise self.InvalidKeyfile(error)
     except KeyError:
         error = f"Keyfile does not contain address field at '{path}'"
         raise self.InvalidKeyfile(error)
     else:
         if not is_address(address):
             raise self.InvalidKeyfile(
                 f"'{path}' does not contain a valid ethereum address")
         address = to_checksum_address(address)
     return address, key_metadata
Example #7
0
def test_is_address(args, is_any, is_hexstr, is_binary):
    assert is_address(args) == is_any
    assert is_hex_address(args) == is_hexstr
    assert is_binary_address(args) == is_binary
Example #8
0
def eth_address_validator(value):
    if not is_address(value):
        raise ValidationError(_("Enter a valid ethereum address"))
Example #9
0
def test_is_address(value, is_any_address, is_hex, is_binary, is_32byte):
    assert is_address(value) is is_any_address
    assert is_hex_address(value) is is_hex
    assert is_binary_address(value) is is_binary
    assert is_32byte_address(value) is is_32byte
Example #10
0
 def is_address(self, addr):
     return is_address(addr)
Example #11
0
     user = cursor.fetchone()
     if user is not None:
         print(message.author.name)
         message.reply("your karma till 30/1/2018 is {0}".format(
             user[0]))
     else:
         message.reply("sorry, your username was not found")
 elif '0x' in text:
     cursor.execute(
         "SELECT id, address FROM users WHERE username = %s",
         (message.author.name, ))
     user = cursor.fetchone()
     if user is not None:
         address = next(x for x in text.split() if '0x' in x)
         print(address)
         if address is not None and is_address(address):
             cursor.execute(
                 "UPDATE users SET address = %s WHERE id = %s",
                 (address, user[0]))
             if user[1] is not None:
                 message.reply(
                     "you have updated your pre-registration ethereum address to: {0}"
                     .format(address))
             else:
                 message.reply(
                     "you are now pre-registered with the address: {0}"
                     .format(address))
         else:
             message.reply(
                 "that's doesn't appear to be a valid ethereum address."
             )
Example #12
0
def eth_address_validator(value):
    if not is_address(value):
        raise ValidationError(
            _(u"Введите валидный ethereum адрес")
        )
Example #13
0
    def post(self):
        """ Handle POST request """

        if not self.request.body:
            log.warning('Missing body')
            self.set_status(400)
            self.write_json({
                'success': False,
                'clicks': None,
                'token': '',
            })
            return

        req = json.loads(self.request.body)
        token = req.get('token')
        recipient = req.get('recipient')
        contract = req.get('contract')

        invalids = []
        if not is_valid_token(token):
            invalids.append('token')
        if not recipient or not is_address(recipient):
            invalids.append('recipient')
        if not contract or not is_address(contract):
            invalids.append('contract')

        recipient = Web3.toChecksumAddress(recipient)
        contract = Web3.toChecksumAddress(contract)

        if len(invalids) > 0:
            log.warning('Invalid input: {}'.format(', '.join(invalids)))

            self.set_status(400)
            self.write_json({
                'success': False,
                'clicks': None,
                'token': '',
                'message': 'Invalid input'
            })
            return

        # Verify it exists
        clicks = rgetint(self.redis, token, 0)

        if not clicks:
            log.warning('Token has no clicks')
            self.write_json({
                'success': False,
                'clicks': None,
                'token': token,
                'message': 'Try clicking first'
            })
            return

        log.info('create_claim({}, {}, {}, {})'.format(recipient,
                                                       add_0x_prefix(token),
                                                       clicks * int(1e18),
                                                       contract))

        # Assemble claim
        claim = create_claim(recipient, add_0x_prefix(token),
                             clicks * int(1e18), contract)
        prefixed_claim_hash = defunct_hash_message(claim)
        # Docstring for this function sugests this does not prefix messages, so
        # we're prefixing above
        signed = self.accounts.eth_account.signHash(
            prefixed_claim_hash, self.signer_account_privkey)

        self.write_json({
            'success': True,
            'clicks': clicks,
            'token': token,
            'claim': claim.hex(),
            'signature': signed.signature.hex(),
            'contract': contract,
        })
def test_is_address(value, expected):
    assert is_address(value) is expected
Example #15
0
 def validate_lnd(cls, addr):
     return is_address(addr)
Example #16
0
 def validate_eth(cls, addr):
     return is_address(addr)