def test_syncing(self, platon_connect): syncing = platon_connect.syncing assert is_boolean(syncing) or is_dict(syncing) if is_boolean(syncing): assert syncing is False elif is_dict(syncing): assert 'startingBlock' in syncing assert 'currentBlock' in syncing assert 'highestBlock' in syncing assert is_integer(syncing['startingBlock']) assert is_integer(syncing['currentBlock']) assert is_integer(syncing['highestBlock'])
def test_eth_syncing(self, web3): syncing = web3_offline_signing.eth.syncing assert is_boolean(syncing) or is_dict(syncing) if is_boolean(syncing): assert syncing is False elif is_dict(syncing): assert 'startingBlock' in syncing assert 'currentBlock' in syncing assert 'highestBlock' in syncing assert is_integer(syncing['startingBlock']) assert is_integer(syncing['currentBlock']) assert is_integer(syncing['highestBlock'])
def test_eth_syncing(self, web3): syncing = web3.eth.syncing assert is_boolean(syncing) or is_dict(syncing) if is_boolean(syncing): assert syncing is False elif is_dict(syncing): assert 'startingBlock' in syncing assert 'currentBlock' in syncing assert 'highestBlock' in syncing assert is_integer(syncing['startingBlock']) assert is_integer(syncing['currentBlock']) assert is_integer(syncing['highestBlock'])
def validate_positive_integer(value): error_message = "Value must be positive integers. Got: {0}".format( value, ) if not is_integer(value) or is_boolean(value): raise ValidationError(error_message) elif value < 0: raise ValidationError(error_message)
def to_hex(value): """ Auto converts any supported value into it's hex representation. """ if is_boolean(value): return "0x1" if value else "0x0" if is_dict(value): return encode_hex(json.dumps(value, sort_keys=True)) if is_string(value): if is_prefixed(value, '-0x'): return from_decimal(value) elif is_0x_prefixed(value): return value else: return encode_hex(value) if is_integer(value): return from_decimal(value) raise TypeError( "Unsupported type: '{0}'. Must be one of Boolean, Dictionary, String, " "or Integer.".format(repr(type(value))) )
def generate_cache_key(value): """ Generates a cache key for the *args and **kwargs """ if is_bytes(value): return hashlib.md5(value).hexdigest() elif is_text(value): return generate_cache_key(force_bytes(value)) elif is_boolean(value) or is_null(value) or is_number(value): return generate_cache_key(repr(value)) elif is_dict(value): return generate_cache_key(( (key, value[key]) for key in sorted(value.keys()) )) elif is_list_like(value) or isinstance(value, Generator): return generate_cache_key("".join(( generate_cache_key(item) for item in value ))) else: raise TypeError("Cannot generate cache key for value {0} of type {1}".format( value, type(value), ))
def is_primitive_type(value): return any(( value is None, is_boolean(value), is_string(value), is_number(value), ))
def to_hex(value=None, hexstr=None, text=None): """ Auto converts any supported value into it's hex representation. Trims leading zeros, as defined in: https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding """ assert_one_val(value, hexstr=hexstr, text=text) if hexstr is not None: return add_0x_prefix(hexstr.lower()) if text is not None: return encode_hex(text.encode('utf-8')) if is_boolean(value): return "0x1" if value else "0x0" if is_dict(value): return encode_hex(json.dumps(value, sort_keys=True)) if isinstance(value, bytes): return encode_hex(value) elif is_string(value): return to_hex(text=value) if is_integer(value): return hex(value) raise TypeError( "Unsupported type: '{0}'. Must be one of Boolean, Dictionary, String, " "or Integer.".format(repr(type(value))) )
def test_eth_syncing(self, web3: "Web3") -> None: syncing = web3.eth.syncing assert is_boolean(syncing) or is_dict(syncing) if is_boolean(syncing): assert syncing is False elif is_dict(syncing): sync_dict = cast(SyncStatus, syncing) assert 'startingBlock' in sync_dict assert 'currentBlock' in sync_dict assert 'highestBlock' in sync_dict assert is_integer(sync_dict['startingBlock']) assert is_integer(sync_dict['currentBlock']) assert is_integer(sync_dict['highestBlock'])
def generate_cache_key(value): """ Generates a cache key for the *args and **kwargs """ if is_bytes(value): return hashlib.md5(value).hexdigest() elif is_text(value): return generate_cache_key(force_bytes(value)) elif is_boolean(value) or is_null(value) or is_number(value): return generate_cache_key(repr(value)) elif is_dict(value): return generate_cache_key(( (key, value[key]) for key in sorted(value.keys()) )) elif is_list_like(value) or isinstance(value, Generator): return generate_cache_key("".join(( generate_cache_key(item) for item in value ))) else: raise TypeError("Cannot generate cache key for value {0} of type {1}".format( value, type(value), ))
def is_encodable(_type, value): try: base, sub, arrlist = _type except ValueError: base, sub, arrlist = process_type(_type) if arrlist: if not is_list_like(value): return False if arrlist[-1] and len(value) != arrlist[-1][0]: return False sub_type = (base, sub, arrlist[:-1]) return all(is_encodable(sub_type, sub_value) for sub_value in value) elif base == 'bool': return is_boolean(value) elif base == 'uint': if not is_integer(value): return False exp = int(sub) if value < 0 or value >= 2**exp: return False return True elif base == 'int': if not is_integer(value): return False exp = int(sub) if value <= -1 * 2**(exp - 1) or value >= 2**(exp - 1): return False return True elif base == 'string': if not is_string(value): return False return True elif base == 'bytes': if not is_string(value): return False if not sub: return True max_length = int(sub) if isinstance(value, str): decodable = is_hex(value) and len(value) % 2 == 0 return decodable and len(decode_hex(value)) <= max_length elif isinstance(value, bytes): return len(value) <= max_length else: False elif base == 'address': if is_ens_name(value): return True elif is_address(value): return True else: return False else: raise ValueError("Unsupported type")
def validate_abi_value(abi_type: TypeStr, value: Any) -> None: """ Helper function for validating a value against the expected abi_type Note: abi_type 'bytes' must either be python3 'bytes' object or '' """ if is_array_type(abi_type) and is_list_like(value): # validate length specified_length = length_of_array_type(abi_type) if specified_length is not None: if specified_length < 1: raise TypeError( "Invalid abi-type: {abi_type}. Length of fixed sized arrays" "must be greater than 0." .format(abi_type=abi_type) ) if specified_length != len(value): raise TypeError( "The following array length does not the length specified" "by the abi-type, {abi_type}: {value}" .format(abi_type=abi_type, value=value) ) # validate sub_types sub_type = sub_type_of_array_type(abi_type) for v in value: validate_abi_value(sub_type, v) return elif is_bool_type(abi_type) and is_boolean(value): return elif is_uint_type(abi_type) and is_integer(value) and value >= 0: return elif is_int_type(abi_type) and is_integer(value): return elif is_address_type(abi_type): validate_address(value) return elif is_bytes_type(abi_type): if is_bytes(value): return elif is_string(value): if is_0x_prefixed(value): return else: raise TypeError( "ABI values of abi-type 'bytes' must be either" "a python3 'bytes' object or an '0x' prefixed string." ) elif is_string_type(abi_type) and is_string(value): return raise TypeError( "The following abi value is not a '{abi_type}': {value}" .format(abi_type=abi_type, value=value) )
def test_blockscout_transaction_provider(): provider = BlockscoutTokenProvider() tx = provider.get_ERC20_transfer(MAINNET_DAI_TXN_HASH) assert is_bytes(tx.hash) and len(tx.hash) assert is_checksum_address(tx.sender) assert is_checksum_address(tx.to) assert is_integer(tx.value) assert is_integer(tx.timestamp) assert is_boolean(tx.success)
def validate_abi_value(abi_type, value): """ Helper function for validating a value against the expected abi_type Note: abi_type 'bytes' must either be python3 'bytes' object or '' """ if is_array_type(abi_type) and is_list_like(value): # validate length specified_length = length_of_array_type(abi_type) if specified_length is not None: if specified_length < 1: raise TypeError( "Invalid abi-type: {abi_type}. Length of fixed sized arrays" "must be greater than 0." .format(abi_type=abi_type) ) if specified_length != len(value): raise TypeError( "The following array length does not the length specified" "by the abi-type, {abi_type}: {value}" .format(abi_type=abi_type, value=value) ) # validate sub_types sub_type = sub_type_of_array_type(abi_type) for v in value: validate_abi_value(sub_type, v) return elif is_bool_type(abi_type) and is_boolean(value): return elif is_uint_type(abi_type) and is_integer(value) and value >= 0: return elif is_int_type(abi_type) and is_integer(value): return elif is_address_type(abi_type): validate_address(value) return elif is_bytes_type(abi_type): if sys.version_info.major >= 3 and is_bytes(value): return elif is_string(value): if is_0x_prefixed(value): return else: raise TypeError( "ABI values of abi-type 'bytes' must be either" "a python3 'bytes' object or an '0x' prefixed string." ) elif is_string_type(abi_type) and is_string(value): return raise TypeError( "The following abi value is not a '{abi_type}': {value}" .format(abi_type=abi_type, value=value) )
def test_encode_boolean(bool_value, data_byte_size): encoder = BooleanEncoder.as_encoder(data_byte_size=data_byte_size, ) if not is_boolean(bool_value): with pytest.raises(EncodingTypeError): encoder(bool_value) return expected_value = zpad(b'\x01' if bool_value else b'\x00', data_byte_size) encoded_value = encoder(bool_value) assert encoded_value == expected_value
def test_encode_boolean(bool_value, data_byte_size): encoder = BooleanEncoder( data_byte_size=data_byte_size, ) if not is_boolean(bool_value): with pytest.raises(EncodingTypeError) as exception_info: encoder(bool_value) assert 'BooleanEncoder' in str(exception_info.value) return expected_value = zpad(b'\x01' if bool_value else b'\x00', data_byte_size) encoded_value = encoder(bool_value) assert encoded_value == expected_value
def to_bytes(primitive=None, hexstr=None, text=None): assert_one_val(primitive, hexstr=hexstr, text=text) if is_boolean(primitive): return b'\x01' if primitive else b'\x00' elif isinstance(primitive, bytes): return primitive elif is_integer(primitive): return to_bytes(hexstr=to_hex(primitive)) elif hexstr is not None: if len(hexstr) % 2: hexstr = '0x0' + remove_0x_prefix(hexstr) return decode_hex(hexstr) elif text is not None: return text.encode('utf-8') raise TypeError("expected an int in first arg, or keyword of hexstr or text")
def test_get_internal_transaction_list(self, provider): transactions = provider.get_internal_transaction_list( self.wallet_address, start_block=self.start_block, end_block=self.end_block, ) assert len(transactions) == self.internal_transaction_count for txn in transactions: assert isinstance(txn, Transaction) assert is_bytes(txn.hash) and len(txn.hash) assert is_checksum_address(txn.sender) assert is_checksum_address(txn.to) assert is_integer(txn.value) assert is_integer(txn.timestamp) assert is_boolean(txn.success)
def test_get_transfer_list(self, provider): transfers = provider.get_transfer_list( self.wallet_address, self.token_address, start_block=self.start_block, end_block=self.end_block, ) assert len(transfers) == self.transfer_count for tfr in transfers: assert isinstance(tfr, Transfer) assert is_bytes(tfr.hash) and len(tfr.hash) assert is_checksum_address(tfr.sender) assert is_checksum_address(tfr.to) assert is_integer(tfr.value) assert is_integer(tfr.timestamp) assert is_boolean(tfr.success)
def to_hex(value): """ Auto converts any supported value into it's hex representation. """ if is_boolean(value): return "0x1" if value else "0x0" if is_dict(value): return encode_hex(json.dumps(value, sort_keys=True)) if is_string(value): return encode_hex(value) if is_integer(value): return from_decimal(value) raise TypeError( "Unsupported type: '{0}'. Must be one of Boolean, Dictionary, String, " "or Integer.".format(repr(type(value))))
def generate_cache_key(value: Any) -> str: """ Generates a cache key for the *args and **kwargs """ if is_bytes(value): return hashlib.md5(value).hexdigest() elif is_text(value): return generate_cache_key(to_bytes(text=value)) elif is_boolean(value) or is_null(value) or is_number(value): return generate_cache_key(repr(value)) elif is_dict(value): return generate_cache_key( ((key, value[key]) for key in sorted(value.keys()))) elif is_list_like(value) or isinstance(value, collections.abc.Generator): return generate_cache_key("".join( (generate_cache_key(item) for item in value))) else: raise TypeError( f"Cannot generate cache key for value {value} of type {type(value)}" )
def to_hex(value=None, hexstr=None, text=None): """ Auto converts any supported value into it's hex representation. Trims leading zeros, as defined in: https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding """ assert_one_val(value, hexstr=hexstr, text=text) if hexstr is not None: return trim_hex(hexstr) if text is not None: return encode_hex(text.encode('utf-8')) if is_boolean(value): return "0x1" if value else "0x0" if is_dict(value): return encode_hex(json.dumps(value, sort_keys=True)) if isinstance(value, bytes): padded = encode_hex(value) return trim_hex(padded) elif is_string(value): return to_hex(text=value) if is_integer(value): # python2 longs end up with an `L` hanging off the end of their hexidecimal # representation. return hex(value).rstrip('L') raise TypeError( "Unsupported type: '{0}'. Must be one of Boolean, Dictionary, String, " "or Integer.".format(repr(type(value))) )
def validate_value(cls, value): if not is_boolean(value): cls.invalidate_value(value)
def test_net_listening(self, web3: "Web3") -> None: listening = web3.net.listening assert is_boolean(listening)
def test_eth_mining(self, web3): mining = web3.eth.mining assert is_boolean(mining)
async def test_net_listening(self, async_w3: "Web3") -> None: listening = await async_w3.async_net.listening assert is_boolean(listening)
def validate_value(cls, value): if not is_boolean(value): cls.invalidate_value(value)
def test_net_listening(self, web3): listening = web3.net.listening assert is_boolean(listening)
def test_eth_mining(self, web3): mining = web3_offline_signing.eth.mining assert is_boolean(mining)
def signBlock(self, header_dict: dict, private_key: str, send_transaction_dicts: List[dict] = [], receive_transaction_dicts: List[dict] = []) -> AttributeDict: ''' transaction = { # Note that the address must be in checksum format: 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', 'value': 1000000000, 'gas': 2000000, 'gasPrice': 234567897654321, 'nonce': 0, 'chainId': 1 } receive_transaction = { 'senderBlockHash', 'sendTransactionHash', 'isRefund', 'remainingRefund' } header = { 'parentHash', 'blockNumber', 'extraData', } :param send_transaction_dicts: :param receive_transaction_dicts: :param reward_bundle: :param private_key: :return: ''' timestamp = int(time.time()) if not is_bytes(header_dict['parentHash']): header_dict['parentHash'] = to_bytes( hexstr=header_dict['parentHash']) if "extraData" in header_dict: if not is_bytes(header_dict['extraData']): extra_data = to_bytes(hexstr=header_dict['extraData']) else: extra_data = header_dict['extraData'] else: extra_data = b'' if "chainId" in header_dict: chain_id = header_dict['chainId'] else: if len(send_transaction_dicts) > 0: if 'chainId' in send_transaction_dicts[0]: chain_id = send_transaction_dicts[0]['chainId'] else: chain_id = 1 else: chain_id = 1 photon_timestamp = get_photon_timestamp(chain_id) if timestamp < photon_timestamp: fork_id = 0 else: fork_id = 1 account = self.privateKeyToAccount(private_key) send_transactions = [] for transaction_dict in send_transaction_dicts: if 'data' in transaction_dict: if not is_bytes(transaction_dict['data']): data = to_bytes(hexstr=transaction_dict['data']) else: data = transaction_dict['data'] else: data = b'' if not is_bytes(transaction_dict['to']): to = to_bytes(hexstr=transaction_dict['to']) else: to = transaction_dict['to'] if fork_id == 0: tx = BosonTransaction(nonce=transaction_dict['nonce'], gas_price=transaction_dict['gasPrice'], gas=transaction_dict['gas'], to=to, value=transaction_dict['value'], data=data, v=0, r=0, s=0) signed_tx = tx.get_signed(account._key_obj, chain_id) elif fork_id == 1: if 'codeAddress' in transaction_dict: if not is_bytes(transaction_dict['codeAddress']): code_address = to_bytes( hexstr=transaction_dict['codeAddress']) else: code_address = transaction_dict['codeAddress'] else: code_address = b'' if 'executeOnSend' in transaction_dict: execute_on_send = bool(transaction_dict['executeOnSend']) else: execute_on_send = False tx = PhotonTransaction(nonce=transaction_dict['nonce'], gas_price=transaction_dict['gasPrice'], gas=transaction_dict['gas'], to=to, value=transaction_dict['value'], data=data, code_address=code_address, execute_on_send=execute_on_send, v=0, r=0, s=0) signed_tx = tx.get_signed(account._key_obj, chain_id) else: raise Exception("Unknown fork id") send_transactions.append(signed_tx) receive_transactions = [] for receive_transaction_dict in receive_transaction_dicts: if not is_bytes(receive_transaction_dict['senderBlockHash']): receive_transaction_dict['senderBlockHash'] = to_bytes( hexstr=receive_transaction_dict['senderBlockHash']) if not is_bytes(receive_transaction_dict['sendTransactionHash']): receive_transaction_dict['sendTransactionHash'] = to_bytes( hexstr=receive_transaction_dict['sendTransactionHash']) if not is_boolean(receive_transaction_dict['isRefund']): receive_transaction_dict['isRefund'] = False if to_int( hexstr=receive_transaction_dict['isRefund']) == 0 else True # We renamed the fourth parameter in the new photon fork fourth_parameter = 0 if 'remainingRefund' in receive_transaction_dict: if not is_integer(receive_transaction_dict['remainingRefund']): fourth_parameter = to_int( hexstr=receive_transaction_dict['remainingRefund']) else: fourth_parameter = receive_transaction_dict[ 'remainingRefund'] elif 'refundAmount' in receive_transaction_dict: if not is_integer(receive_transaction_dict['refundAmount']): fourth_parameter = to_int( hexstr=receive_transaction_dict['refundAmount']) else: fourth_parameter = receive_transaction_dict['refundAmount'] if fork_id == 0: receive_transaction_class = BosonReceiveTransaction elif fork_id == 1: receive_transaction_class = PhotonReceiveTransaction else: raise Exception("Unknown fork id") tx = receive_transaction_class( receive_transaction_dict['senderBlockHash'], receive_transaction_dict['sendTransactionHash'], receive_transaction_dict['isRefund'], fourth_parameter) receive_transactions.append(tx) send_tx_root_hash, _ = make_trie_root_and_nodes(send_transactions) receive_tx_root_hash, _ = make_trie_root_and_nodes( receive_transactions) chain_address = account.address reward_bundle = StakeRewardBundle() header = BlockHeader(chain_address=decode_hex(chain_address), parent_hash=header_dict['parentHash'], transaction_root=send_tx_root_hash, receive_transaction_root=receive_tx_root_hash, block_number=header_dict['blockNumber'], timestamp=timestamp, extra_data=extra_data, reward_hash=reward_bundle.hash) signed_header = header.get_signed(account._key_obj, chain_id) signed_micro_header = signed_header.to_micro_header() if fork_id == 0: micro_block = BosonMicroBlock( header=signed_micro_header, transactions=send_transactions, receive_transactions=receive_transactions, reward_bundle=reward_bundle) rlp_encoded_micro_block = rlp.encode(micro_block, sedes=BosonMicroBlock) elif fork_id == 1: micro_block = PhotonMicroBlock( header=signed_micro_header, transactions=send_transactions, receive_transactions=receive_transactions, reward_bundle=reward_bundle) rlp_encoded_micro_block = rlp.encode(micro_block, sedes=PhotonMicroBlock) else: raise Exception("Unknown fork id") return AttributeDict({ 'rawBlock': encode_hex(rlp_encoded_micro_block), 'send_tx_hashes': [tx.hash for tx in send_transactions], 'receive_tx_hashes': [tx.hash for tx in receive_transactions], 'r': signed_header.r, 's': signed_header.s, 'v': signed_header.v, })
def test_net_listening(self, web3): listening = web3_offline_signing.net.listening assert is_boolean(listening)