def _encode_abi(cls, abi, arguments, data=None): argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( ', '.join(argument_types), )) try: encoded_arguments = encode_abi( argument_types, force_obj_to_bytes(arguments), ) except EncodingError as e: raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type: {0}".format(str(e))) if data: return add_0x_prefix( force_bytes(remove_0x_prefix(data)) + force_bytes(remove_0x_prefix(encode_hex(encoded_arguments)))) else: return encode_hex(encoded_arguments)
def test_transacting_with_contract_respects_explicit_gas(web3, STRING_CONTRACT, skip_if_testrpc, wait_for_block): skip_if_testrpc(web3) wait_for_block(web3) StringContract = web3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.deploy(args=["Caqalai"]) deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30) assert deploy_receipt is not None string_contract = StringContract(address=deploy_receipt['contractAddress']) # eth_abi will pass as raw bytes, no encoding # unless we encode ourselves txn_hash = string_contract.functions.setValue(force_bytes("ÄLÄMÖLÖ")).transact({'gas': 200000}) txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30) assert txn_receipt is not None final_value = string_contract.functions.getValue().call() assert force_bytes(final_value) == force_bytes("ÄLÄMÖLÖ") txn = web3.eth.getTransaction(txn_hash) assert txn['gas'] == 200000
def test_auto_gas_computation_when_transacting(web3, STRING_CONTRACT, skip_if_testrpc, wait_for_block, call, transact): skip_if_testrpc(web3) wait_for_block(web3) StringContract = web3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.deploy(args=["Caqalai"]) deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30) assert deploy_receipt is not None string_contract = StringContract(address=deploy_receipt['contractAddress']) gas_estimate = string_contract.functions.setValue(force_bytes("ÄLÄMÖLÖ")).estimateGas() # eth_abi will pass as raw bytes, no encoding # unless we encode ourselves txn_hash = transact(contract=string_contract, contract_function="setValue", func_args=[force_bytes("ÄLÄMÖLÖ")]) txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30) assert txn_receipt is not None final_value = call(contract=string_contract, contract_function='getValue') assert force_bytes(final_value) == force_bytes("ÄLÄMÖLÖ") txn = web3.eth.getTransaction(txn_hash) assert txn['gas'] == gas_estimate + 100000
def _encode_abi(cls, abi, arguments, data=None): argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( ', '.join(argument_types), ) ) try: encoded_arguments = encode_abi( argument_types, force_obj_to_bytes(arguments), ) except EncodingError as e: raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type: {0}".format(str(e)) ) if data: return add_0x_prefix( force_bytes(remove_0x_prefix(data)) + force_bytes(remove_0x_prefix(encode_hex(encoded_arguments))) ) else: return encode_hex(encoded_arguments)
def test_transacting_with_contract_respects_explicit_gas(web3, STRING_CONTRACT, skip_if_testrpc, wait_for_block, call, transact): skip_if_testrpc(web3) wait_for_block(web3) StringContract = web3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.deploy(args=["Caqalai"]) deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30) assert deploy_receipt is not None string_contract = StringContract(address=deploy_receipt['contractAddress']) # eth_abi will pass as raw bytes, no encoding # unless we encode ourselves txn_hash = transact(contract=string_contract, contract_function='setValue', func_args=[force_bytes("ÄLÄMÖLÖ")], tx_kwargs={'gas': 200000}) txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30) assert txn_receipt is not None final_value = call(contract=string_contract, contract_function='getValue') assert force_bytes(final_value) == force_bytes("ÄLÄMÖLÖ") txn = web3.eth.getTransaction(txn_hash) assert txn['gas'] == 200000
def test_auto_gas_computation_when_transacting(web3, STRING_CONTRACT, skip_if_testrpc, wait_for_block): skip_if_testrpc(web3) wait_for_block(web3) StringContract = web3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.deploy(args=["Caqalai"]) deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn, 30) assert deploy_receipt is not None string_contract = StringContract(address=deploy_receipt['contractAddress']) gas_estimate = string_contract.estimateGas().setValue( force_bytes("ÄLÄMÖLÖ")) # eth_abi will pass as raw bytes, no encoding # unless we encode ourselves txn_hash = string_contract.transact().setValue(force_bytes("ÄLÄMÖLÖ")) txn_receipt = wait_for_transaction_receipt(web3, txn_hash, 30) assert txn_receipt is not None final_value = string_contract.call().getValue() assert force_bytes(final_value) == force_bytes("ÄLÄMÖLÖ") txn = web3.eth.getTransaction(txn_hash) assert txn['gas'] == gas_estimate + 100000
def stringify(value): if is_bytes(value): yield value elif is_text(value): yield force_bytes(value) elif is_list_like(value): yield b''.join(( b'(', b','.join((stringify(item) for item in value)), b')', )) elif is_dict(value): yield b''.join(( b'{', b','.join((b":".join((stringify(key), stringify(item))) for key, item in value.items())), b'}', )) elif is_integer(value): yield force_bytes(str(value)) elif is_null(value): yield 'None@{0}'.format(id(value)) else: raise TypeError("Unsupported type for stringification: {0}".format( type(value)))
def test_eth_sign(web3, skip_if_testrpc): skip_if_testrpc(web3) private_key_hex = '0x5e95384d8050109aab08c1922d3c230739bc16976553c317e5d0b87b59371f2a' private_key = decode_hex(private_key_hex) # This imports the private key into the running geth instance and unlocks # the account so that it can sign things. # `0xa5df35f30ba0ce878b1061ae086289adff3ba1e0` address = web3.personal.importRawKey(private_key, "password") web3.personal.unlockAccount(address, "password") assert add_0x_prefix(encode_hex(privtoaddr(private_key))) == add_0x_prefix(address) assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0' # the data to be signed data = b'1234567890abcdefghijklmnopqrstuvwxyz' # the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3` data_hash = web3.sha3(data, encoding=None) data_hash_bytes = decode_hex(data_hash) assert force_bytes(data_hash) == sha3(data) priv_key = PrivateKey(flags=ALL_FLAGS) priv_key.set_raw_privkey(private_key) # sanit check the extract_ecdsa_signer function works as expected. vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=sha3_256) vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig) vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id)) vector_address = force_text(extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full)) assert vector_address == address # Now have geth sign some data. signature_hex = web3.eth.sign(address, data) signature_bytes = decode_hex(signature_hex) actual_signer = extract_ecdsa_signer(data_hash_bytes, signature_bytes) assert actual_signer == address # Verify the signature against the public key derived from the # original private key. It fails. rec_id = signature_bytes[64] if is_string(rec_id): rec_id = ord(rec_id) recoverable_signature = priv_key.ecdsa_recoverable_deserialize( signature_bytes[:64], rec_id, ) signature = priv_key.ecdsa_recoverable_convert(recoverable_signature) is_valid = priv_key.pubkey.ecdsa_verify( msg=data, raw_sig=signature, digest=sha3_256, ) assert is_valid
def test_transacting_with_contract_with_string_argument(web3, string_contract): # eth_abi will pass as raw bytes, no encoding # unless we encode ourselves txn_hash = string_contract.transact().setValue(force_bytes("ÄLÄMÖLÖ")) txn_receipt = web3.eth.getTransactionReceipt(txn_hash) assert txn_receipt is not None final_value = string_contract.call().getValue() assert force_bytes(final_value) == force_bytes("ÄLÄMÖLÖ")
def test_contract_deployment_no_constructor(web3, MathContract, MATH_RUNTIME): deploy_txn = MathContract.deploy() txn_receipt = web3.eth.getTransactionReceipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] blockchain_code = web3.eth.getCode(contract_address) assert force_bytes(blockchain_code) == force_bytes(MATH_RUNTIME)
def normalize_fixture(fixture): normalized_fixture = { 'in': tuple(( decode_hex(key) if is_0x_prefixed(key) else force_bytes(key), (decode_hex(value) if is_0x_prefixed(value) else force_bytes(value) ) if value is not None else None, ) for key, value in (fixture['in'].items( ) if isinstance(fixture['in'], dict) else fixture['in'])), 'root': decode_hex(fixture['root']) } return normalized_fixture
def test_contract_deployment_with_constructor_with_address_argument(web3, WithConstructorAddressArgumentsContract, WITH_CONSTRUCTOR_ADDRESS_RUNTIME): deploy_txn = WithConstructorAddressArgumentsContract.deploy(args=["0x16d9983245de15e7a9a73bc586e01ff6e08de737"]) txn_receipt = web3.eth.getTransactionReceipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] blockchain_code = web3.eth.getCode(contract_address) assert force_bytes(blockchain_code) == force_bytes(WITH_CONSTRUCTOR_ADDRESS_RUNTIME)
def test_contract_deployment_with_constructor_with_arguments(web3, WithConstructorArgumentsContract, WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME): deploy_txn = WithConstructorArgumentsContract.deploy(args=[1234, 'abcd']) txn_receipt = web3.eth.getTransactionReceipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] blockchain_code = web3.eth.getCode(contract_address) assert force_bytes(blockchain_code) == force_bytes(WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME)
def test_contract_deployment_with_constructor_without_args(web3, SimpleConstructorContract, SIMPLE_CONSTRUCTOR_RUNTIME): deploy_txn = SimpleConstructorContract.deploy() txn_receipt = web3.eth.getTransactionReceipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] blockchain_code = web3.eth.getCode(contract_address) assert force_bytes(blockchain_code) == force_bytes(SIMPLE_CONSTRUCTOR_RUNTIME)
def test_contract_deployment_with_constructor_without_args( web3, SimpleConstructorContract, SIMPLE_CONSTRUCTOR_RUNTIME): deploy_txn = SimpleConstructorContract.deploy() txn_receipt = web3.eth.getTransactionReceipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] blockchain_code = web3.eth.getCode(contract_address) assert force_bytes(blockchain_code) == force_bytes( SIMPLE_CONSTRUCTOR_RUNTIME)
def test_contract_deployment_with_constructor_with_arguments( web3, WithConstructorArgumentsContract, WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME): deploy_txn = WithConstructorArgumentsContract.deploy(args=[1234, 'abcd']) txn_receipt = web3.eth.getTransactionReceipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] blockchain_code = web3.eth.getCode(contract_address) assert force_bytes(blockchain_code) == force_bytes( WITH_CONSTRUCTOR_ARGUMENTS_RUNTIME)
def test_contract_deployment_with_constructor_with_address_argument( web3, WithConstructorAddressArgumentsContract, WITH_CONSTRUCTOR_ADDRESS_RUNTIME): deploy_txn = WithConstructorAddressArgumentsContract.deploy( args=["0x16d9983245de15e7a9a73bc586e01ff6e08de737"]) txn_receipt = web3.eth.getTransactionReceipt(deploy_txn) assert txn_receipt is not None assert txn_receipt['contractAddress'] contract_address = txn_receipt['contractAddress'] blockchain_code = web3.eth.getCode(contract_address) assert force_bytes(blockchain_code) == force_bytes( WITH_CONSTRUCTOR_ADDRESS_RUNTIME)
def encrypt(data: bytes, pubkey: datatypes.PublicKey, shared_mac_data: bytes = b'') -> bytes: """Encrypt data with ECIES method to the given public key 1) generate r = random value 2) generate shared-secret = kdf( ecdhAgree(r, P) ) 3) generate R = rG [same op as generating a public key] 4) 0x04 || R || AsymmetricEncrypt(shared-secret, plaintext) || tag """ # 1) generate r = random value ephemeral = generate_privkey() # 2) generate shared-secret = kdf( ecdhAgree(r, P) ) key_material = ecdh_agree(ephemeral, pubkey) key = kdf(key_material) key_enc, key_mac = key[:KEY_LEN // 2], key[KEY_LEN // 2:] key_mac = sha256(key_mac).digest() # 3) generate R = rG [same op as generating a public key] ephem_pubkey = ephemeral.public_key # Encrypt algo = CIPHER(key_enc) iv = os.urandom(algo.block_size // 8) ctx = Cipher(algo, MODE(iv), default_backend()).encryptor() ciphertext = ctx.update(data) + ctx.finalize() # 4) 0x04 || R || AsymmetricEncrypt(shared-secret, plaintext) || tag msg = b'\x04' + ephem_pubkey.to_bytes() + iv + ciphertext # the MAC of a message (called the tag) as per SEC 1, 3.5. tag = hmac_sha256(key_mac, msg[1 + PUBKEY_LEN:] + force_bytes(shared_mac_data)) return msg + tag
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 encode_rpc_request(self, method, params): return force_bytes(json.dumps(force_obj_to_text({ "jsonrpc": "2.0", "method": method, "params": params or [], "id": next(self.request_counter), })))
def sign(self, key): """Sign this transaction with a private key. A potentially already existing signature would be overridden. """ if not is_bitcoin_available() or not is_secp256k1_available(): raise ImportError( "In order to sign transactions the " "`bitcoin` and `secp256k1` packages must be installed.") from bitcoin import privtopub from secp256k1 import PrivateKey if key in (0, b'', b'\x00' * 32, b'0' * 64): raise ValueError("Zero privkey cannot sign") rawhash = keccak(rlp.encode(self, UnsignedTransaction)) if len(key) in {64, 66}: # we need a binary key key = decode_hex(key) pk = PrivateKey(key, raw=True) sig_bytes, rec_id = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(rawhash, raw=True)) signature = sig_bytes + force_bytes(chr(rec_id)) self.v = (ord(signature[64]) if is_string(signature[64]) else signature[64]) + 27 self.r = decode_big_endian_int(signature[0:32]) self.s = decode_big_endian_int(signature[32:64]) self.sender = to_normalized_address(keccak(privtopub(key)[1:])[-20:]) return self
def sign(self, key): """Sign this transaction with a private key. A potentially already existing signature would be overridden. """ if not is_bitcoin_available() or not is_secp256k1_available(): raise ImportError( "In order to sign transactions the " "`bitcoin` and `secp256k1` packages must be installed." ) from bitcoin import privtopub from secp256k1 import PrivateKey if key in (0, b'', b'\x00' * 32, b'0' * 64): raise ValueError("Zero privkey cannot sign") rawhash = keccak(rlp.encode(self, UnsignedTransaction)) if len(key) in {64, 66}: # we need a binary key key = decode_hex(key) pk = PrivateKey(key, raw=True) sig_bytes, rec_id = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(rawhash, raw=True) ) signature = sig_bytes + force_bytes(chr(rec_id)) self.v = (ord(signature[64]) if is_string(signature[64]) else signature[64]) + 27 self.r = decode_big_endian_int(signature[0:32]) self.s = decode_big_endian_int(signature[32:64]) self.sender = to_normalized_address(keccak(privtopub(key)[1:])[-20:]) return self
def test_eth_call_with_no_args(web3, wait_for_transaction, MATH_CODE, MATH_RUNTIME): txn_hash = web3.eth.sendTransaction({ "from": web3.eth.coinbase, "data": MATH_CODE, "gas": 3000000, }) wait_for_transaction(web3, txn_hash) txn_receipt = web3.eth.getTransactionReceipt(txn_hash) contract_address = txn_receipt['contractAddress'] assert force_bytes(web3.eth.getCode(contract_address)) == MATH_RUNTIME abi_signature = web3.sha3("return13()", encoding=None)[:10] # sanity assert abi_signature == '0x16216f39' actual_result_hex = web3.eth.call({ "from": web3.eth.coinbase, "to": contract_address, "data": abi_signature, }) actual_result = int(actual_result_hex, 16) assert actual_result == 13
def decode_single(typ, data): if is_hex_encoded_value(data): warnings.warn( DeprecationWarning( "Automatic inference of hex encoded data has been deprecated. " "Please adjust your code to ensure that the data argument for " "`decode_single` is a byte string")) data = decode_hex(remove_0x_prefix(data)) if is_text(data): warnings.warn( DeprecationWarning( "Automatic conversion of encoded data to bytes has been deprecated. " "Please adjust your code to ensure that the data argument for " "`decode_single` is a byte string")) data = force_bytes(data) try: base, sub, arrlist = typ except ValueError: base, sub, arrlist = process_type(typ) decoder = get_single_decoder(base, sub, arrlist) stream = BytesIO(data) return decoder(stream)
def is_hex_encoded_value(v): if v == b'': return False if not remove_0x_prefix(force_bytes(v)).lower().strip(HEX_CHARS) == b'': return False if len(remove_0x_prefix(v)) % 64 and len(remove_0x_prefix(v)) % 40: return False return True
def test_right_pad(pad_contract): """Ensure we handle trailing zero in the address correctly.""" address_bytes = get_address_as_bytes(pad_contract.call().rightPad()) hash = bitcoin.bin_sha256(address_bytes) val = pad_contract.call().getHashRightPad() val = force_bytes(val) assert hash == val
def test_send(qeth_contract, web3, capsys): (pubkey_next, privkey_next) = keygen() msghash = msg_hash(pubkey_next, b'\x00', b'\x00', b'\x00', b'\x12\x34') sig = sign(init_key[1], msghash) tx_hash1 = qeth_contract.transact().send_transaction(sig, pubkey_next, 0, "0x"+"0"*40, 0, b'\x12\x34') with capsys.disabled(): print('\nSOL Gas used:'+str(+web3.eth.getTransactionReceipt(tx_hash1)['gasUsed'])+'\n') assert eth_utils.force_bytes(qeth_contract.call().pubkey_hash()) == pubkey_next
def normalize_class_name(value): """ For `type()` calls: * Python 2 wants `str` * Python 3.4 wants `str` * Python 3.5 doesn't care. """ if sys.version_info.major == 2: return force_bytes(value) else: return force_text(value)
def encode_single(typ, arg): try: base, sub, arrlist = typ except ValueError: base, sub, arrlist = process_type(typ) if is_text(arg): arg = force_bytes(arg) encoder = get_single_encoder(base, sub, arrlist) return encoder(arg)
def _pack(cmd_id: int, payload: List[Any], privkey: datatypes.PrivateKey) -> bytes: """Create and sign a UDP message to be sent to a remote node. See https://github.com/ethereum/devp2p/blob/master/rlpx.md#node-discovery for information on how UDP packets are structured. """ cmd_id = force_bytes(chr(cmd_id)) expiration = rlp.sedes.big_endian_int.serialize(int(time.time() + EXPIRATION)) encoded_data = cmd_id + rlp.encode(payload + [expiration]) signature = privkey.sign_msg(encoded_data) message_hash = keccak(signature.to_bytes() + encoded_data) return message_hash + signature.to_bytes() + encoded_data
def test_eth_sendTransaction_auto_estimates_gas_if_not_provided(web3, wait_for_transaction, MATH_CODE, MATH_RUNTIME): txn_hash = web3.eth.sendTransaction({ "from": web3.eth.coinbase, "data": MATH_CODE, }) wait_for_transaction(web3, txn_hash) txn_receipt = web3.eth.getTransactionReceipt(txn_hash) contract_address = txn_receipt['contractAddress'] assert force_bytes(web3.eth.getCode(contract_address)) == MATH_RUNTIME
def test_eth_sendTransaction_with_data(web3, wait_for_transaction, MATH_CODE, MATH_RUNTIME): txn_hash = web3.eth.sendTransaction({ "from": web3.eth.coinbase, "data": MATH_CODE, "gas": 3000000, }) wait_for_transaction(web3, txn_hash) txn_receipt = web3.eth.getTransactionReceipt(txn_hash) contract_address = txn_receipt['contractAddress'] assert force_bytes(web3.eth.getCode(contract_address)) == MATH_RUNTIME
def decode_abi(types, data): if is_hex_encoded_value(data): warnings.warn( DeprecationWarning( "Automatic inference of hex encoded data has been deprecated. " "Please adjust your code to ensure that the data argument for " "`decode_single` is a byte string")) data = decode_hex(remove_0x_prefix(data)) if is_text(data): warnings.warn( DeprecationWarning( "Automatic conversion of encoded data to bytes has been deprecated. " "Please adjust your code to ensure that the data argument for " "`decode_abi` is a byte string")) data = force_bytes(data) processed_types = tuple(process_type(_type) for _type in types) decoder = get_multi_decoder(processed_types) stream = BytesIO(data) return decoder(stream)
) from web3.utils.caching import ( generate_cache_key, ) @to_dict def shuffle_dict(_dict): keys = list(_dict.keys()) random.shuffle(keys) for key in keys: yield key, _dict[key] encodable_text = st.text().map(lambda v: force_text(force_bytes(v, 'utf8'))) def extend_fn(children): lists_st = st.lists(children) dicts_st = st.dictionaries(encodable_text, children) return lists_st | dicts_st all_st = st.recursive( st.none() | st.integers() | st.booleans() | st.floats() | encodable_text | st.binary(), extend_fn, ) def recursive_shuffle_dict(v):
def is_prefixed(value, prefix): return value.startswith( force_bytes(prefix) if is_bytes(value) else force_text(prefix) )
def _mkpingid(self, token, node): pid = force_bytes(token) + node.pubkey.to_bytes() return pid
def random_node(): seed = force_bytes("".join(random.sample(string.ascii_lowercase, 10))) priv_key = keys.PrivateKey(keccak(seed)) return kademlia.Node(priv_key.public_key, random_address())
to_dict, ) from web3.utils.caching import ( generate_cache_key, ) @to_dict def shuffle_dict(_dict): keys = list(_dict.keys()) random.shuffle(keys) for key in keys: yield key, _dict[key] encodable_text = st.text().map(lambda v: force_text(force_bytes(v, 'utf8'))) def extend_fn(children): lists_st = st.lists(children) dicts_st = st.dictionaries(encodable_text, children) return lists_st | dicts_st all_st = st.recursive( st.none() | st.integers() | st.booleans() | st.floats() | encodable_text | st.binary(), extend_fn, )
def _mkpingid(self, token: AnyStr, node: Node) -> bytes: pid = force_bytes(token) + node.pubkey.to_bytes() return pid
def _is_prefixed(value, prefix): return value.startswith( force_bytes(prefix) if is_bytes(value) else force_text(prefix))