def request_new_serial( region: str = "US", model: str = "Motorola RAZR v3" ) -> Tuple[str, str]: """ Requests a new authenticator This will connect to the Blizzard servers """ def base_msg(otp, region, model): ret = (otp + b"\0" * 37)[:37] ret += region.encode() or b"\0\0" ret += (model.encode() + b"\0" * 16)[:16] return b"\1" + ret otp = token_bytes(37) data = base_msg(otp, region, model) e = encrypt(data) # get the host, or fallback to default host = ENROLL_HOSTS.get(region, ENROLL_HOSTS["default"]) response = decrypt(enroll(e, host)[8:], otp) secret = b32encode(response[:20]).decode() serial = response[20:].decode() region = serial[:2] if region not in ("CN", "EU", "US"): raise ValueError("Unexpected region: %r" % (region)) return serial, secret
def generate_data_key_without_kms(): if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3: # Use new secrets module https://docs.python.org/3/library/secrets.html import secrets return secrets.token_bytes(int(256 / 8)) else: # Legacy code to generate random value try: # noinspection PyUnresolvedReferences from Crypto import Random except ImportError: pycrypto_explanation = """ For generating a secure Random sequence without KMS, pycrypto is used in case you use Python <3.6 . This does not seem to be available on your system and therefore execution needs to be aborted. In order to not use KMS in case of a Python to setup you must install the pycrypto library. For example using `pip install pycrypto` It requires to compile code in C so there are some requirements you need to satisfy. For more info check out the installation section in the source documentation at https://pypi.python.org/pypi/pycrypto Alternatively you could use KMS by setting s3Staging -> kmsGeneratedKey to True in the config file In that case make sure to generate a key using ./createKmsKey.sh <region-short-name> """ logging.fatal(pycrypto_explanation) sys.exit(-5) return Random.new().read(256 / 8)
async def authenticate( self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, ) -> bool: """(async) Authenticate a connecting client. Returns: True if authentication is successful and False otherwise. The caller is responsible for closing the connection in case of failure. """ writer.write(enums.ExtOrPortAuthTypes.SAFE_COOKIE + enums.ExtOrPortAuthTypes.END_AUTH_TYPES) client_auth_type = await reader.readexactly(1) if client_auth_type != enums.ExtOrPortAuthTypes.SAFE_COOKIE: return False client_nonce = await reader.readexactly(self.nonce_len) server_nonce = secrets.token_bytes(self.nonce_len) server_hash = self.hash(b''.join(( self.server_hash_header, client_nonce, server_nonce))) writer.write(server_hash + server_nonce) client_hash = await reader.readexactly(self.hash_len) result = hmac.compare_digest(client_hash, self.hash(b''.join(( self.client_hash_header, client_nonce, server_nonce)))) writer.write(int(result).to_bytes(1, 'big')) return result
def test_uuid_to_text_invalid_length(self, db, uuid5_examples): """ Should raise an error if binary UUID data is not 16 bytes long. """ with pytest.raises(apsw.SQLError) as exc: buf = secrets.token_bytes(15) query(db, 'SELECT uuid_to_text(?);', (buf,)) assert 'UUID must be 16 bytes' in str(exc)
def check_credentials(): user = request.forms.get('user', '') password = request.forms.get('password', '') if not pubsub.check_user(user, password): return show_main_page() token = secrets.token_bytes(32) logged_in_users.setdefault(token, user) response.set_cookie('token', token, max_age=60, secret=secret) return show_main_page(user)
def add_group(self, group_name, payment_address): """ Return new group_id in base64 """ if (self.is_group_name_exists(group_name)): raise Exception("the group \"%s\" is already present"%str(group_name)) group_id_base64 = base64.b64encode(secrets.token_bytes(32)) self.m["groups"] += [{"group_name" : group_name , "group_id" : group_id_base64.decode("ascii"), "payment_address" : payment_address}] return group_id_base64
def randomBytes(length): """ Return _length_ random bytes. :rtype: bytes """ if secrets: return secrets.token_bytes(512) else: return os.urandom(512)
def request_stage_2(target, namespace, pod, container, command): stage_2 = "" command = f"command={'&command='.join(command.split(' '))}" with open('stage_2', 'r') as stage_2_fd: stage_2 = stage_2_fd.read() key = base64.b64encode(token_bytes(20)).decode('utf-8') return stage_2.format(namespace, pod, container, command, target, key).encode('utf-8')
def encrypt(self, data): iv = token_bytes(16) aes = Cipher(algorithms.AES(self.derived_key), modes.CBC(iv), backend=default_backend()) encryptor = aes.encryptor() padder = padding.PKCS7(128).padder() padded_data = padder.update(data) + padder.finalize() encrypted_data = encryptor.update(padded_data) + encryptor.finalize() mac = hmac.digest(self.derived_key, (iv + encrypted_data), 'sha256') #logging.debug(f"IV: {to_byte_array(iv)}") #logging.debug(f"HMAC: {to_byte_array(mac)}") #logging.debug(f"DATA: {to_byte_array(encrypted_data)}") return iv + encrypted_data + mac
def test_token_defaults(self): # Test that token_* functions handle default size correctly. for func in (secrets.token_bytes, secrets.token_hex, secrets.token_urlsafe): with self.subTest(func=func): name = func.__name__ try: func() except TypeError: self.fail("%s cannot be called with no argument" % name) try: func(None) except TypeError: self.fail("%s cannot be called with None" % name) size = secrets.DEFAULT_ENTROPY self.assertEqual(len(secrets.token_bytes(None)), size) self.assertEqual(len(secrets.token_hex(None)), 2*size)
def restore(serial: str, restore_code: str) -> str: restore_code = restore_code.upper() serial = normalize_serial(serial) if len(restore_code) != 10: raise ValueError(f"invalid restore code (should be 10 characters): {restore_code}") challenge = initiate_paper_restore(serial) if len(challenge) != 32: raise ValueError("Bad challenge length (expected 32, got %i)" % (len(challenge))) code = restore_code_to_bytes(restore_code) hash = hmac.new(code, serial.encode() + challenge, digestmod=sha1).digest() otp = token_bytes(20) e = encrypt(hash + otp) response = validate_paper_restore(serial + e) secret = decrypt(response, otp) return b32encode(secret).decode()
async def test_cc_trade_with_multiple_colours(self, wallets_prefarm): # This test start with CCWallet in both wallets. wall # wallet1 {wallet_id: 2 = 70} # wallet2 {wallet_id: 2 = 30} wallet_node_a, wallet_node_b, full_node = wallets_prefarm wallet_a = wallet_node_a.wallet_state_manager.main_wallet wallet_b = wallet_node_b.wallet_state_manager.main_wallet # cc_a_2 = coloured coin, Alice, wallet id = 2 cc_a_2 = wallet_node_a.wallet_state_manager.wallets[2] cc_b_2 = wallet_node_b.wallet_state_manager.wallets[2] cc_a_3: CCWallet = await CCWallet.create_new_cc( wallet_node_a.wallet_state_manager, wallet_a, uint64(100)) for i in range(0, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) await time_out_assert(15, cc_a_3.get_confirmed_balance, 100) await time_out_assert(15, cc_a_3.get_unconfirmed_balance, 100) # store these for asserting change later cc_balance = await cc_a_2.get_unconfirmed_balance() cc_balance_2 = await cc_b_2.get_unconfirmed_balance() assert cc_a_3.cc_info.my_genesis_checker is not None red = cc_a_3.get_colour() for i in range(0, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) cc_b_3: CCWallet = await CCWallet.create_wallet_for_cc( wallet_node_b.wallet_state_manager, wallet_b, red) assert cc_a_3.cc_info.my_genesis_checker == cc_b_3.cc_info.my_genesis_checker for i in range(0, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) trade_manager_0 = wallet_node_a.wallet_state_manager.trade_manager trade_manager_1 = wallet_node_b.wallet_state_manager.trade_manager file = "test_offer_file.offer" file_path = Path(file) if file_path.exists(): file_path.unlink() # Wallet offer_dict = {1: 1000, 2: -20, 4: -50} success, trade_offer, error = await trade_manager_0.create_offer_for_ids( offer_dict, file) assert success is True assert trade_offer is not None success, offer, error = await trade_manager_1.get_discrepancies_for_offer( file_path) assert error is None assert success is True assert offer is not None assert offer["chia"] == -1000 colour_2 = cc_a_2.get_colour() colour_3 = cc_a_3.get_colour() assert offer[colour_2] == 20 assert offer[colour_3] == 50 success, trade, reason = await trade_manager_1.respond_to_offer( file_path) assert success is True for i in range(0, 10): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) await time_out_assert(15, cc_b_3.get_confirmed_balance, 50) await time_out_assert(15, cc_b_3.get_unconfirmed_balance, 50) await time_out_assert(15, cc_a_3.get_confirmed_balance, 50) await time_out_assert(15, cc_a_3.get_unconfirmed_balance, 50) await time_out_assert(15, cc_a_2.get_unconfirmed_balance, cc_balance - offer[colour_2]) await time_out_assert(15, cc_b_2.get_unconfirmed_balance, cc_balance_2 + offer[colour_2]) trade = await trade_manager_0.get_trade_by_id(trade_offer.trade_id) status: TradeStatus = TradeStatus(trade.status) assert status is TradeStatus.CONFIRMED
def get_random_bytes(length=16): """ Generate N random bytes byte string """ return secrets.token_bytes(length)
when update() has not been called """ sim_sensor = SimSensor() assert sim_sensor.age() == -1 n_iter = random.randint(100, 1000) for i in range(n_iter): result = sim_sensor.get() assert sim_sensor.low <= result <= sim_sensor.high sim_sensor.update() assert sim_sensor.age() > 0 """__________________________________________________________________________________________________________ """ @pytest.mark.parametrize("ads1x15", [ADS1115, ADS1015]) @pytest.mark.parametrize("seed", [token_bytes(8) for _ in range(8)]) @pytest.mark.parametrize("pga", random.sample(ADS1115._CONFIG_VALUES[2], 4)) @pytest.mark.parametrize("mode", ['SINGLE', 'CONTINUOUS']) def test_analog_sensor_single_read(patch_pigpio_i2c, mock_i2c_hardware, ads1x15, seed, pga, mode): """__________________________________________________________________________________________________________TEST #3 Tests the proper functioning of an AnalogSensor with random, but plausible, calibration. - Performs a sequence of observations and verifies that each matches expectations and that the age of each reading properly reflects called updates """ random.seed(seed) kwargs = { "MUX": random.choice(ads1x15._CONFIG_VALUES[1]), "PGA": pga, "MODE": mode, "DR": random.choice(ads1x15._CONFIG_VALUES[4]),
def generate_mnemonic() -> str: mnemonic_bytes = token_bytes(32) mnemonic = bytes_to_mnemonic(mnemonic_bytes) return mnemonic
def get_random_encrypted_data() -> bytes: return secrets.token_bytes(RANDOM_ENCRYPTED_DATA_SIZE)
def get_random_auth_tag() -> Nonce: return Nonce(secrets.token_bytes(NONCE_SIZE))
def random_key(length: int) -> int: # generate length random bytes tb: bytes = token_bytes(length) # convert those bytes into a bit string and return it return int.from_bytes(tb, "big")
async def run(self): """Main loop of the TelegramClient, will wait for user action""" self.add_event_handler(self.message_handler, events.NewMessage(incoming=True)) # Enter a while loop to chat as long as the user wants while True: dialog_count = 15 dialogs = await self.get_dialogs(limit=dialog_count) i = None while i is None: print_title("Dialogs window") # Display them so the user can choose for i, dialog in enumerate(dialogs, start=1): sprint("{}. {}".format(i, get_display_name(dialog.entity))) # Let the user decide who they want to talk to print() print("> Who do you want to send messages to?") print("> Available commands:") print(" !q: Quits the dialogs window and exits.") print(" !l: Logs out, terminating this session.") print() i = await async_input("Enter dialog ID or a command: ") if i == "!q": return if i == "!l": await self.log_out() return try: i = int(i if i else 0) - 1 # Ensure it is inside the bounds, otherwise retry if not 0 <= i < dialog_count: i = None except ValueError: i = None # Retrieve the selected user (or chat, or channel) entity = dialogs[i].entity # Show some information print_title('Chat with "{}"'.format(get_display_name(entity))) print("Available commands:") print(" !q: Quits the current chat.") print(" !Q: Quits the current chat and exits.") print() # And start a while loop to chat while True: msg = await async_input("Enter a message: ") # Quit if msg == "!q": break if msg == "!Q": return # Send chat message (if any) if msg: # If the receiver's aes key is not present, # fetch his public key from server and derive a aes key print("SENDING MESSAGE TO ENTITTY: ", entity.id) aes_shared_key = None for dlg in Dialog.select(): if dlg.dialog_id == entity.id: # found a entry of aes shared key. aes_shared_key = dlg.aes_shared_key break if aes_shared_key is None: # get the public key. peer_pub_key = get_public_key(entity.id) shared_key = my_ecdh_private_key.exchange( ec.ECDH(), peer_pub_key ) aes_shared_key = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=None, backend=default_backend(), ).derive(shared_key) peer = Dialog( dialog_id=entity.id, aes_shared_key=aes_shared_key ) peer.save(force_insert=True) init_vector = token_bytes(16) aes = Cipher( algorithms.AES(aes_shared_key), modes.CBC(init_vector), backend=default_backend(), ) encryptor = aes.encryptor() padder = padding.PKCS7(128).padder() padded_data = padder.update(msg.encode("utf-8")) + padder.finalize() enc_msg_bytes = encryptor.update(padded_data) + encryptor.finalize() enc_msg_bytes = init_vector + enc_msg_bytes b64_enc_txt = base64.b64encode(enc_msg_bytes).decode("utf-8") await self.send_message(entity, b64_enc_txt, link_preview=False)
from cilantro.messages import MerkleTree import secrets import zmq import asyncio from cilantro.protocol.wallets import ED25519Wallet import random # generate random transactions txs = [secrets.token_bytes(16) for i in range(64)] # build a complete merkle tree m = MerkleTree(txs) h = m.hash_of_nodes() # verify that the merkle tree can provide raw data provided a hash t = [m.data_for_hash(h) for h in m.leaves] print(txs == t) # generate the delegates with new wallets delegates = [ED25519Wallet.new() for i in range(64)] connection_list = ['inproc://{}'.format(k[1]) for k in delegates] # pretend to be a masternode by asking for pieces of data given a certain hash # 1. masternode gets the hash of the merkle tree in its entirety # 2. masternode gets a list of the nodes. added together, it should equal the hash # 3. masternode gets a list of signatures of the hash (to do) # 4. masternode asks all the delegates for pieces of the merkle root # # a. given a list of delegates, randomly select one to ask for the chunk of data # # b. if it fails, ask from another
def simulate_delegate_returning_chunk(h, fail_rate=0.1): if random.random > fail_rate: return m.data_for_hash(h) else: return secrets.token_bytes(32)
async def test_store(self): db_filename = Path("blockchain_wallet_store_test.db") if db_filename.exists(): db_filename.unlink() db_connection = await aiosqlite.connect(db_filename) store = await WalletStore.create(db_connection) try: coin_1 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) coin_2 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) coin_3 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) coin_4 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) record_replaced = WalletCoinRecord(coin_1, uint32(8), uint32(0), False, True, WalletType.STANDARD_WALLET, 0) record_1 = WalletCoinRecord(coin_1, uint32(4), uint32(0), False, True, WalletType.STANDARD_WALLET, 0) record_2 = WalletCoinRecord(coin_2, uint32(5), uint32(0), False, True, WalletType.STANDARD_WALLET, 0) record_3 = WalletCoinRecord( coin_3, uint32(5), uint32(10), True, False, WalletType.STANDARD_WALLET, 0, ) record_4 = WalletCoinRecord( coin_4, uint32(5), uint32(15), True, False, WalletType.STANDARD_WALLET, 0, ) # Test add (replace) and get assert await store.get_coin_record(coin_1.name()) is None await store.add_coin_record(record_replaced) await store.add_coin_record(record_1) await store.add_coin_record(record_2) await store.add_coin_record(record_3) await store.add_coin_record(record_4) assert await store.get_coin_record(coin_1.name()) == record_1 # Test persistance await db_connection.close() db_connection = await aiosqlite.connect(db_filename) store = await WalletStore.create(db_connection) assert await store.get_coin_record(coin_1.name()) == record_1 # Test set spent await store.set_spent(coin_1.name(), uint32(12)) assert (await store.get_coin_record(coin_1.name())).spent assert (await store.get_coin_record(coin_1.name() )).spent_block_index == 12 # No coins at height 3 assert len(await store.get_unspent_coins_at_height(3)) == 0 assert len(await store.get_unspent_coins_at_height(4)) == 1 assert len(await store.get_unspent_coins_at_height(5)) == 4 assert len(await store.get_unspent_coins_at_height(11)) == 3 assert len(await store.get_unspent_coins_at_height(12)) == 2 assert len(await store.get_unspent_coins_at_height(15)) == 1 assert len(await store.get_unspent_coins_at_height(16)) == 1 assert len(await store.get_unspent_coins_at_height()) == 1 assert len(await store.get_unspent_coins_for_wallet(0)) == 1 assert len(await store.get_unspent_coins_for_wallet(1)) == 0 coin_5 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) record_5 = WalletCoinRecord( coin_5, uint32(5), uint32(15), False, False, WalletType.STANDARD_WALLET, 1, ) await store.add_coin_record(record_5) assert len(await store.get_unspent_coins_for_wallet(1)) == 1 assert len(await store.get_spendable_for_index(100, 1)) == 1 assert len(await store.get_spendable_for_index(100, 0)) == 1 assert len(await store.get_spendable_for_index(0, 0)) == 0 coin_6 = Coin(token_bytes(32), coin_4.puzzle_hash, uint64(12312)) await store.add_coin_record(record_5) record_6 = WalletCoinRecord( coin_6, uint32(5), uint32(15), True, False, WalletType.STANDARD_WALLET, 2, ) await store.add_coin_record(record_6) assert (len(await store.get_coin_records_by_puzzle_hash( record_6.coin.puzzle_hash)) == 2) # 4 and 6 assert (len(await store.get_coin_records_by_puzzle_hash(token_bytes(32) )) == 0) assert await store.get_coin_record_by_coin_id(coin_6.name() ) == record_6 assert await store.get_coin_record_by_coin_id(token_bytes(32) ) is None # BLOCKS assert len(await store.get_lca_path()) == 0 # NOT lca block br_1 = BlockRecord( token_bytes(32), token_bytes(32), uint32(0), uint128(100), None, None, None, None, ) assert await store.get_block_record(br_1.header_hash) is None await store.add_block_record(br_1, False) assert len(await store.get_lca_path()) == 0 assert await store.get_block_record(br_1.header_hash) == br_1 # LCA genesis await store.add_block_record(br_1, True) assert await store.get_block_record(br_1.header_hash) == br_1 assert len(await store.get_lca_path()) == 1 assert (await store.get_lca_path())[br_1.header_hash] == br_1 br_2 = BlockRecord( token_bytes(32), token_bytes(32), uint32(1), uint128(100), None, None, None, None, ) await store.add_block_record(br_2, False) assert len(await store.get_lca_path()) == 1 await store.add_block_to_path(br_2.header_hash) assert len(await store.get_lca_path()) == 2 assert (await store.get_lca_path())[br_2.header_hash] == br_2 br_3 = BlockRecord( token_bytes(32), token_bytes(32), uint32(2), uint128(100), None, None, None, None, ) await store.add_block_record(br_3, True) assert len(await store.get_lca_path()) == 3 await store.remove_blocks_from_path(1) assert len(await store.get_lca_path()) == 2 await store.rollback_lca_to_block(0) assert len(await store.get_unspent_coins_at_height()) == 0 coin_7 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) coin_8 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) coin_9 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) coin_10 = Coin(token_bytes(32), token_bytes(32), uint64(12312)) record_7 = WalletCoinRecord(coin_7, uint32(0), uint32(1), True, False, WalletType.STANDARD_WALLET, 1) record_8 = WalletCoinRecord(coin_8, uint32(1), uint32(2), True, False, WalletType.STANDARD_WALLET, 1) record_9 = WalletCoinRecord(coin_9, uint32(2), uint32(3), True, False, WalletType.STANDARD_WALLET, 1) record_10 = WalletCoinRecord( coin_10, uint32(3), uint32(4), True, False, WalletType.STANDARD_WALLET, 1, ) await store.add_coin_record(record_7) await store.add_coin_record(record_8) await store.add_coin_record(record_9) await store.add_coin_record(record_10) assert len(await store.get_unspent_coins_at_height(0)) == 1 assert len(await store.get_unspent_coins_at_height(1)) == 1 assert len(await store.get_unspent_coins_at_height(2)) == 1 assert len(await store.get_unspent_coins_at_height(3)) == 1 assert len(await store.get_unspent_coins_at_height(4)) == 0 await store.add_block_record(br_2, True) await store.add_block_record(br_3, True) await store.rollback_lca_to_block(1) assert len(await store.get_unspent_coins_at_height(0)) == 1 assert len(await store.get_unspent_coins_at_height(1)) == 1 assert len(await store.get_unspent_coins_at_height(2)) == 1 assert len(await store.get_unspent_coins_at_height(3)) == 1 assert len(await store.get_unspent_coins_at_height(4)) == 1 except AssertionError: await db_connection.close() raise await db_connection.close()
async def test_cc_trade(self, wallets_prefarm): wallet_node_0, wallet_node_1, full_node = wallets_prefarm wallet_0 = wallet_node_0.wallet_state_manager.main_wallet wallet_1 = wallet_node_1.wallet_state_manager.main_wallet cc_wallet: CCWallet = await CCWallet.create_new_cc( wallet_node_0.wallet_state_manager, wallet_0, uint64(100)) for i in range(1, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) await time_out_assert(15, cc_wallet.get_confirmed_balance, 100) await time_out_assert(15, cc_wallet.get_unconfirmed_balance, 100) assert cc_wallet.cc_info.my_genesis_checker is not None colour = cc_wallet.get_colour() cc_wallet_2: CCWallet = await CCWallet.create_wallet_for_cc( wallet_node_1.wallet_state_manager, wallet_1, colour) assert cc_wallet.cc_info.my_genesis_checker == cc_wallet_2.cc_info.my_genesis_checker for i in range(0, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) # send cc_wallet 2 a coin cc_hash = await cc_wallet_2.get_new_inner_hash() tx_record = await cc_wallet.generate_signed_transaction([uint64(1)], [cc_hash]) await wallet_0.wallet_state_manager.add_pending_transaction(tx_record) for i in range(0, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) trade_manager_0 = wallet_node_0.wallet_state_manager.trade_manager trade_manager_1 = wallet_node_1.wallet_state_manager.trade_manager file = "test_offer_file.offer" file_path = Path(file) if file_path.exists(): file_path.unlink() offer_dict = {1: 10, 2: -30} success, trade_offer, error = await trade_manager_0.create_offer_for_ids( offer_dict, file) assert success is True assert trade_offer is not None success, offer, error = await trade_manager_1.get_discrepancies_for_offer( file_path) assert error is None assert success is True assert offer is not None assert offer["chia"] == -10 assert offer[colour] == 30 success, trade, reason = await trade_manager_1.respond_to_offer( file_path) assert success is True for i in range(0, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) await time_out_assert(15, cc_wallet_2.get_confirmed_balance, 31) await time_out_assert(15, cc_wallet_2.get_unconfirmed_balance, 31) trade_2 = await trade_manager_0.get_trade_by_id(trade_offer.trade_id) assert TradeStatus(trade_2.status) is TradeStatus.CONFIRMED
async def test_create_offer_with_zero_val(self, wallets_prefarm): # Wallet A Wallet B # CCWallet id 2: 50 CCWallet id 2: 50 # CCWallet id 3: 50 CCWallet id 2: 50 # Wallet A will # Wallet A will create a new CC and wallet B will create offer to buy that coin wallet_node_a, wallet_node_b, full_node = wallets_prefarm wallet_a = wallet_node_a.wallet_state_manager.main_wallet wallet_b = wallet_node_b.wallet_state_manager.main_wallet trade_manager_a: TradeManager = wallet_node_a.wallet_state_manager.trade_manager trade_manager_b: TradeManager = wallet_node_b.wallet_state_manager.trade_manager cc_a_4: CCWallet = await CCWallet.create_new_cc( wallet_node_a.wallet_state_manager, wallet_a, uint64(100)) for i in range(0, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) await time_out_assert(15, cc_a_4.get_confirmed_balance, 100) colour = cc_a_4.get_colour() cc_b_4: CCWallet = await CCWallet.create_wallet_for_cc( wallet_node_b.wallet_state_manager, wallet_b, colour) cc_balance = await cc_a_4.get_confirmed_balance() cc_balance_2 = await cc_b_4.get_confirmed_balance() offer_dict = {1: -30, cc_a_4.id(): 50} file = "test_offer_file.offer" file_path = Path(file) if file_path.exists(): file_path.unlink() success, offer, error = await trade_manager_b.create_offer_for_ids( offer_dict, file) success, trade_a, reason = await trade_manager_a.respond_to_offer( file_path) for i in range(0, buffer_blocks): await full_node.farm_new_transaction_block( FarmNewBlockProtocol(token_bytes())) await time_out_assert(15, cc_a_4.get_confirmed_balance, cc_balance - 50) await time_out_assert(15, cc_b_4.get_confirmed_balance, cc_balance_2 + 50) async def assert_func(): assert trade_a is not None trade = await trade_manager_a.get_trade_by_id(trade_a.trade_id) assert trade is not None return trade.status async def assert_func_b(): assert offer is not None trade = await trade_manager_b.get_trade_by_id(offer.trade_id) assert trade is not None return trade.status await time_out_assert(15, assert_func, TradeStatus.CONFIRMED.value) await time_out_assert(15, assert_func_b, TradeStatus.CONFIRMED.value)
def __init__(self): self._cookie = secrets.token_bytes(self.cookie_len)
async def respond_to_offer( self, file_path: Path ) -> Tuple[bool, Optional[TradeRecord], Optional[str]]: has_wallets = await self.maybe_create_wallets_for_offer(file_path) if not has_wallets: return False, None, "Unknown Error" trade_offer = None try: trade_offer_hex = file_path.read_text() trade_offer = TradeRecord.from_bytes( hexstr_to_bytes(trade_offer_hex)) except Exception as e: return False, None, f"Error: {e}" if trade_offer is not None: offer_spend_bundle: SpendBundle = trade_offer.spend_bundle coinsols = [] # [] of CoinSolutions cc_coinsol_outamounts: Dict[bytes32, List[Tuple[Any, int]]] = dict() aggsig = offer_spend_bundle.aggregated_signature cc_discrepancies: Dict[bytes32, int] = dict() chia_discrepancy = None wallets: Dict[bytes32, Any] = dict() # colour to wallet dict for coinsol in offer_spend_bundle.coin_solutions: puzzle: Program = coinsol.puzzle_reveal solution: Program = coinsol.solution # work out the deficits between coin amount and expected output for each r = cc_utils.uncurry_cc(puzzle) if r: # Calculate output amounts mod_hash, genesis_checker, inner_puzzle = r colour = bytes(genesis_checker).hex() if colour not in wallets: wallets[ colour] = await self.wallet_state_manager.get_wallet_for_colour( colour) unspent = await self.wallet_state_manager.get_spendable_coins_for_wallet( wallets[colour].id()) if coinsol.coin in [record.coin for record in unspent]: return False, None, "can't respond to own offer" innersol = solution.first() total = get_output_amount_for_puzzle_and_solution( inner_puzzle, innersol) if colour in cc_discrepancies: cc_discrepancies[colour] += coinsol.coin.amount - total else: cc_discrepancies[colour] = coinsol.coin.amount - total # Store coinsol and output amount for later if colour in cc_coinsol_outamounts: cc_coinsol_outamounts[colour].append((coinsol, total)) else: cc_coinsol_outamounts[colour] = [(coinsol, total)] else: # standard chia coin unspent = await self.wallet_state_manager.get_spendable_coins_for_wallet( 1) if coinsol.coin in [record.coin for record in unspent]: return False, None, "can't respond to own offer" if chia_discrepancy is None: chia_discrepancy = get_output_discrepancy_for_puzzle_and_solution( coinsol.coin, puzzle, solution) else: chia_discrepancy += get_output_discrepancy_for_puzzle_and_solution( coinsol.coin, puzzle, solution) coinsols.append(coinsol) chia_spend_bundle: Optional[SpendBundle] = None if chia_discrepancy is not None: chia_spend_bundle = await self.wallet_state_manager.main_wallet.create_spend_bundle_relative_chia( chia_discrepancy, []) if chia_spend_bundle is not None: for coinsol in coinsols: chia_spend_bundle.coin_solutions.append(coinsol) zero_spend_list: List[SpendBundle] = [] spend_bundle = None # create coloured coin self.log.info(cc_discrepancies) for colour in cc_discrepancies.keys(): if cc_discrepancies[colour] < 0: my_cc_spends = await wallets[colour].select_coins( abs(cc_discrepancies[colour])) else: if chia_spend_bundle is None: to_exclude: List = [] else: to_exclude = chia_spend_bundle.removals() my_cc_spends = await wallets[colour].select_coins(0) if my_cc_spends is None or my_cc_spends == set(): zero_spend_bundle: SpendBundle = await wallets[ colour].generate_zero_val_coin(False, to_exclude) if zero_spend_bundle is None: return ( False, None, "Unable to generate zero value coin. Confirm that you have chia available", ) zero_spend_list.append(zero_spend_bundle) additions = zero_spend_bundle.additions() removals = zero_spend_bundle.removals() my_cc_spends = set() for add in additions: if add not in removals and add.amount == 0: my_cc_spends.add(add) if my_cc_spends == set() or my_cc_spends is None: return False, None, "insufficient funds" # Create SpendableCC list and innersol_list with both my coins and the offered coins # Firstly get the output coin my_output_coin = my_cc_spends.pop() spendable_cc_list = [] innersol_list = [] genesis_id = genesis_coin_id_for_genesis_coin_checker( Program.from_bytes(bytes.fromhex(colour))) # Make the rest of the coins assert the output coin is consumed for coloured_coin in my_cc_spends: inner_solution = self.wallet_state_manager.main_wallet.make_solution( consumed=[my_output_coin.name()]) inner_puzzle = await self.get_inner_puzzle_for_puzzle_hash( coloured_coin.puzzle_hash) assert inner_puzzle is not None sigs = await wallets[colour].get_sigs(inner_puzzle, inner_solution, coloured_coin.name()) sigs.append(aggsig) aggsig = AugSchemeMPL.aggregate(sigs) lineage_proof = await wallets[ colour].get_lineage_proof_for_coin(coloured_coin) spendable_cc_list.append( SpendableCC(coloured_coin, genesis_id, inner_puzzle, lineage_proof)) innersol_list.append(inner_solution) # Create SpendableCC for each of the coloured coins received for cc_coinsol_out in cc_coinsol_outamounts[colour]: cc_coinsol = cc_coinsol_out[0] puzzle = cc_coinsol.puzzle_reveal solution = cc_coinsol.solution r = uncurry_cc(puzzle) if r: mod_hash, genesis_coin_checker, inner_puzzle = r inner_solution = solution.first() lineage_proof = solution.rest().rest().first() spendable_cc_list.append( SpendableCC(cc_coinsol.coin, genesis_id, inner_puzzle, lineage_proof)) innersol_list.append(inner_solution) # Finish the output coin SpendableCC with new information newinnerpuzhash = await wallets[colour].get_new_inner_hash() outputamount = sum([ c.amount for c in my_cc_spends ]) + cc_discrepancies[colour] + my_output_coin.amount inner_solution = self.wallet_state_manager.main_wallet.make_solution( primaries=[{ "puzzlehash": newinnerpuzhash, "amount": outputamount }]) inner_puzzle = await self.get_inner_puzzle_for_puzzle_hash( my_output_coin.puzzle_hash) assert inner_puzzle is not None lineage_proof = await wallets[colour].get_lineage_proof_for_coin( my_output_coin) spendable_cc_list.append( SpendableCC(my_output_coin, genesis_id, inner_puzzle, lineage_proof)) innersol_list.append(inner_solution) sigs = await wallets[colour].get_sigs(inner_puzzle, inner_solution, my_output_coin.name()) sigs.append(aggsig) aggsig = AugSchemeMPL.aggregate(sigs) if spend_bundle is None: spend_bundle = spend_bundle_for_spendable_ccs( CC_MOD, Program.from_bytes(bytes.fromhex(colour)), spendable_cc_list, innersol_list, [aggsig], ) else: new_spend_bundle = spend_bundle_for_spendable_ccs( CC_MOD, Program.from_bytes(bytes.fromhex(colour)), spendable_cc_list, innersol_list, [aggsig], ) spend_bundle = SpendBundle.aggregate( [spend_bundle, new_spend_bundle]) # reset sigs and aggsig so that they aren't included next time around sigs = [] aggsig = AugSchemeMPL.aggregate(sigs) my_tx_records = [] if zero_spend_list is not None and spend_bundle is not None: zero_spend_list.append(spend_bundle) spend_bundle = SpendBundle.aggregate(zero_spend_list) if spend_bundle is None: return False, None, "spend_bundle missing" # Add transaction history for this trade now = uint64(int(time.time())) if chia_spend_bundle is not None: spend_bundle = SpendBundle.aggregate( [spend_bundle, chia_spend_bundle]) # debug_spend_bundle(spend_bundle) if chia_discrepancy < 0: tx_record = TransactionRecord( confirmed_at_height=uint32(0), created_at_time=now, to_puzzle_hash=token_bytes(), amount=uint64(abs(chia_discrepancy)), fee_amount=uint64(0), confirmed=False, sent=uint32(10), spend_bundle=chia_spend_bundle, additions=chia_spend_bundle.additions(), removals=chia_spend_bundle.removals(), wallet_id=uint32(1), sent_to=[], trade_id=std_hash(spend_bundle.name() + bytes(now)), type=uint32(TransactionType.OUTGOING_TRADE.value), name=chia_spend_bundle.name(), ) else: tx_record = TransactionRecord( confirmed_at_height=uint32(0), created_at_time=uint64(int(time.time())), to_puzzle_hash=token_bytes(), amount=uint64(abs(chia_discrepancy)), fee_amount=uint64(0), confirmed=False, sent=uint32(10), spend_bundle=chia_spend_bundle, additions=chia_spend_bundle.additions(), removals=chia_spend_bundle.removals(), wallet_id=uint32(1), sent_to=[], trade_id=std_hash(spend_bundle.name() + bytes(now)), type=uint32(TransactionType.INCOMING_TRADE.value), name=chia_spend_bundle.name(), ) my_tx_records.append(tx_record) for colour, amount in cc_discrepancies.items(): wallet = wallets[colour] if chia_discrepancy > 0: tx_record = TransactionRecord( confirmed_at_height=uint32(0), created_at_time=uint64(int(time.time())), to_puzzle_hash=token_bytes(), amount=uint64(abs(amount)), fee_amount=uint64(0), confirmed=False, sent=uint32(10), spend_bundle=spend_bundle, additions=spend_bundle.additions(), removals=spend_bundle.removals(), wallet_id=wallet.id(), sent_to=[], trade_id=std_hash(spend_bundle.name() + bytes(now)), type=uint32(TransactionType.OUTGOING_TRADE.value), name=spend_bundle.name(), ) else: tx_record = TransactionRecord( confirmed_at_height=uint32(0), created_at_time=uint64(int(time.time())), to_puzzle_hash=token_bytes(), amount=uint64(abs(amount)), fee_amount=uint64(0), confirmed=False, sent=uint32(10), spend_bundle=spend_bundle, additions=spend_bundle.additions(), removals=spend_bundle.removals(), wallet_id=wallet.id(), sent_to=[], trade_id=std_hash(spend_bundle.name() + bytes(now)), type=uint32(TransactionType.INCOMING_TRADE.value), name=token_bytes(), ) my_tx_records.append(tx_record) tx_record = TransactionRecord( confirmed_at_height=uint32(0), created_at_time=uint64(int(time.time())), to_puzzle_hash=token_bytes(), amount=uint64(0), fee_amount=uint64(0), confirmed=False, sent=uint32(0), spend_bundle=spend_bundle, additions=spend_bundle.additions(), removals=spend_bundle.removals(), wallet_id=uint32(0), sent_to=[], trade_id=std_hash(spend_bundle.name() + bytes(now)), type=uint32(TransactionType.OUTGOING_TRADE.value), name=spend_bundle.name(), ) now = uint64(int(time.time())) trade_record: TradeRecord = TradeRecord( confirmed_at_index=uint32(0), accepted_at_time=now, created_at_time=now, my_offer=False, sent=uint32(0), spend_bundle=offer_spend_bundle, tx_spend_bundle=spend_bundle, additions=spend_bundle.additions(), removals=spend_bundle.removals(), trade_id=std_hash(spend_bundle.name() + bytes(now)), status=uint32(TradeStatus.PENDING_CONFIRM.value), sent_to=[], ) await self.save_trade(trade_record) await self.wallet_state_manager.add_pending_transaction(tx_record) for tx in my_tx_records: await self.wallet_state_manager.add_transaction(tx) return True, trade_record, None
def generate_random_feed_id(): private_key = secrets.token_bytes(32) signing_key = SigningKey(private_key) public_key_feed_id = signing_key.verify_key.encode() return public_key_feed_id
def make_content(): yield lambda amount: secrets.token_bytes(amount)
from flask import ( Flask, abort, g, redirect, render_template, request, session, url_for, ) from flask_sqlalchemy import SQLAlchemy # -------------------------------------------------------- Configuration app = Flask(__name__) secret_key = os.environ.get("CHATBOT_SECRET_KEY", secrets.token_bytes(32)) db_path = Path(__file__).parent / "chatbot.db" app.config.update( TEMPLATES_AUTO_RELOAD=True, SECRET_KEY=secret_key, SESSION_COOKIE_SAMESITE="Lax", SQLALCHEMY_DATABASE_URI=f"sqlite:///{db_path}", SQLALCHEMY_TRACK_MODIFICATIONS=False, REPLY_DELAY_MS=int(os.environ.get("CHATBOT_REPLY_DELAY_MS", 2500)), ) db = SQLAlchemy(app) # ------------------------------------------------------------- Database class User(db.Model):
def random_key(length): tb = token_bytes(length) return int.from_bytes(tb, "big")
def get_random_id_nonce() -> IDNonce: return IDNonce(secrets.token_bytes(ID_NONCE_SIZE))
def encrypt(self, data: bytes) -> bytes: padding_length = max(0, 255 - len(data)) m = int.from_bytes(data + secrets.token_bytes(padding_length), 'big') x = pow(m, self.e, self.n) return to_bytes(x)
async def test_basic_store(self): assert sqlite3.threadsafety == 1 blocks = bt.get_consecutive_blocks(test_constants, 9, [], 9, b"0") blocks_alt = bt.get_consecutive_blocks(test_constants, 3, [], 9, b"1") db_filename = Path("blockchain_test.db") db_filename_2 = Path("blockchain_test_2.db") db_filename_3 = Path("blockchain_test_3.db") if db_filename.exists(): db_filename.unlink() if db_filename_2.exists(): db_filename_2.unlink() if db_filename_3.exists(): db_filename_3.unlink() connection = await aiosqlite.connect(db_filename) connection_2 = await aiosqlite.connect(db_filename_2) connection_3 = await aiosqlite.connect(db_filename_3) db = await FullNodeStore.create(connection) db_2 = await FullNodeStore.create(connection_2) try: # Add/get candidate block assert db.get_candidate_block(0) is None partial = ( blocks[5].transactions_generator, blocks[5].transactions_filter, blocks[5].header.data, blocks[5].proof_of_space, ) db.add_candidate_block(blocks[5].header_hash, *partial) assert db.get_candidate_block(blocks[5].header_hash) == partial db.clear_candidate_blocks_below(uint32(8)) assert db.get_candidate_block(blocks[5].header_hash) is None # Proof of time heights chall_iters = (bytes32(bytes([1] * 32)), uint32(32532535)) chall_iters_2 = (bytes32(bytes([3] * 32)), uint32(12522535)) assert db.get_proof_of_time_heights(chall_iters) is None db.add_proof_of_time_heights(chall_iters, 5) db.add_proof_of_time_heights(chall_iters_2, 7) db.clear_proof_of_time_heights_below(6) assert db.get_proof_of_time_heights(chall_iters) is None assert db.get_proof_of_time_heights(chall_iters_2) is not None # Add/get unfinished block i = 1 for block in blocks: key = (block.header_hash, uint64(1000)) # Different database should have different data await db_2.add_unfinished_block(key, block) assert await db.get_unfinished_block(key) is None await db.add_unfinished_block(key, block) assert await db.get_unfinished_block(key) == block assert len(await db.get_unfinished_blocks()) == i i += 1 await db.clear_unfinished_blocks_below(uint32(5)) assert len(await db.get_unfinished_blocks()) == 5 # Set/get unf block leader assert db.get_unfinished_block_leader() == (0, (1 << 64) - 1) db.set_unfinished_block_leader(key) assert db.get_unfinished_block_leader() == key assert db.get_disconnected_block( blocks[0].prev_header_hash) is None # Disconnected blocks for block in blocks: db.add_disconnected_block(block) db.get_disconnected_block(block.prev_header_hash) == block db.clear_disconnected_blocks_below(uint32(5)) assert db.get_disconnected_block( blocks[4].prev_header_hash) is None h_hash_1 = bytes32(token_bytes(32)) assert not db.seen_unfinished_block(h_hash_1) assert db.seen_unfinished_block(h_hash_1) await db.clear_seen_unfinished_blocks() assert not db.seen_unfinished_block(h_hash_1) except Exception: await connection.close() await connection_2.close() await connection_3.close() db_filename.unlink() db_filename_2.unlink() raise # Different database should have different data db_3 = await FullNodeStore.create(connection_3) assert db_3.get_unfinished_block_leader() == (0, (1 << 64) - 1) await connection.close() await connection_2.close() await connection_3.close() db_filename.unlink() db_filename_2.unlink() db_filename_3.unlink()
def test_token_bytes(self): # Test token_bytes. for n in (1, 8, 17, 100): with self.subTest(n=n): self.assertIsInstance(secrets.token_bytes(n), bytes) self.assertEqual(len(secrets.token_bytes(n)), n)
def generate_aes_key(key_bits: int) -> bytes: return secrets.token_bytes(key_bits // 8)
def generate_id(self): """Generate a unique session id.""" id = base64.b64encode( secrets.token_bytes(12) + self.sequence_number.to_bytes(3, 'big')) self.sequence_number = (self.sequence_number + 1) & 0xffffff return id.decode('utf-8').replace('/', '_').replace('+', '-')
def __init__(self, name='__main__', app=None, rows: int = 1, columns: int = 1, sidebar: bool = False, title: str = 'Bowtie App', theme: Optional[str] = None, background_color: str = 'White', socketio: str = '', debug: bool = False) -> None: """Create a Bowtie App. Parameters ---------- name : str, optional Use __name__ or leave as default if using a single module. Consult the Flask docs on "import_name" for details on more complex apps. app : Flask app, optional If you are defining your own Flask app, pass it in here. You only need this if you are doing other stuff with Flask outside of bowtie. row : int, optional Number of rows in the grid. columns : int, optional Number of columns in the grid. sidebar : bool, optional Enable a sidebar for control components. title : str, optional Title of the HTML. theme : str, optional Color for Ant Design components. background_color : str, optional Background color of the control pane. socketio : string, optional Socket.io path prefix, only change this for advanced deployments. debug : bool, optional Enable debugging in Flask. Disable in production! """ self.title = title self.theme = theme self._init: Optional[Callable] = None self._socketio_path = socketio self._schedules: List[Scheduler] = [] self._subscriptions: Dict[Event, List[Tuple[List[Event], Callable]]] = defaultdict(list) self._pages: Dict[Pager, Callable] = {} self._uploads: Dict[int, Callable] = {} self._root = View(rows=rows, columns=columns, sidebar=sidebar, background_color=background_color) self._routes: List[Route] = [] self._package_dir = Path(os.path.dirname(__file__)) self._jinjaenv = Environment( loader=FileSystemLoader(str(self._package_dir / 'templates')), trim_blocks=True, lstrip_blocks=True ) if app is None: self.app = Flask(name) else: self.app = app self.app.debug = debug self._socketio = SocketIO(self.app, binary=True, path=socketio + 'socket.io') self.app.secret_key = secrets.token_bytes() self.add_route(view=self._root, path='/', exact=True) # https://buxty.com/b/2012/05/custom-template-folders-with-flask/ templates = Path(__file__).parent / 'templates' self.app.jinja_loader = ChoiceLoader([ self.app.jinja_loader, FileSystemLoader(str(templates)), ]) self._build_dir = self.app.root_path / _DIRECTORY self.app.before_first_request(self._endpoints)
def generate_token() -> bytes: """ Generate a random token used for identification of clients and tunnels """ return secrets.token_bytes(base.CLIENT_NAME_SIZE)
async def _receive_handshake(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: msg = await self.wait(reader.read(ENCRYPTED_AUTH_MSG_LEN), timeout=REPLY_TIMEOUT) ip, socket, *_ = writer.get_extra_info("peername") remote_address = Address(ip, socket) self.logger.debug("Receiving handshake from %s", remote_address) got_eip8 = False try: ephem_pubkey, initiator_nonce, initiator_pubkey = decode_authentication( msg, self.privkey) except DecryptionError as e: self.logger.debug("Failed to decrypt handshake: %s", e) return # # Try to decode as EIP8 # got_eip8 = True # msg_size = big_endian_to_int(msg[:2]) # remaining_bytes = msg_size - ENCRYPTED_AUTH_MSG_LEN + 2 # msg += await self.wait( # reader.read(remaining_bytes), # timeout=REPLY_TIMEOUT) # try: # ephem_pubkey, initiator_nonce, initiator_pubkey = decode_authentication( # msg, self.privkey) # except DecryptionError as e: # self.logger.debug("Failed to decrypt handshake: %s", e) # return initiator_remote = Node(initiator_pubkey, remote_address) responder = HandshakeResponder(initiator_remote, self.privkey, got_eip8, self.cancel_token) responder_nonce = secrets.token_bytes(HASH_LEN) auth_ack_msg = responder.create_auth_ack_message(responder_nonce) auth_ack_ciphertext = responder.encrypt_auth_ack_message(auth_ack_msg) # Use the `writer` to send the reply to the remote writer.write(auth_ack_ciphertext) await self.wait(writer.drain()) # Call `HandshakeResponder.derive_shared_secrets()` and use return values to create `Peer` aes_secret, mac_secret, egress_mac, ingress_mac = responder.derive_secrets( initiator_nonce=initiator_nonce, responder_nonce=responder_nonce, remote_ephemeral_pubkey=ephem_pubkey, auth_init_ciphertext=msg, auth_ack_ciphertext=auth_ack_ciphertext) connection = PeerConnection( reader=reader, writer=writer, aes_secret=aes_secret, mac_secret=mac_secret, egress_mac=egress_mac, ingress_mac=ingress_mac, ) # Create and register peer in peer_pool peer = self.peer_pool.get_peer_factory().create_peer( remote=initiator_remote, connection=connection, inbound=True, ) if self.peer_pool.is_full: await peer.disconnect(DisconnectReason.too_many_peers) return elif not self.peer_pool.is_valid_connection_candidate(peer.remote): await peer.disconnect(DisconnectReason.useless_peer) return total_peers = len(self.peer_pool) inbound_peer_count = len([ peer for peer in self.peer_pool.connected_nodes.values() if peer.inbound ]) # if self.chain_config.node_type != 4 and total_peers > 1 and inbound_peer_count / total_peers > DIAL_IN_OUT_RATIO: # # make sure to have at least 1/4 outbound connections # await peer.disconnect(DisconnectReason.too_many_peers) # else: # We use self.wait() here as a workaround for # https://github.com/ethereum/py-evm/issues/670. await self.wait(self.do_handshake(peer))
def __init__(self, verify: bytes, secret=None): self.verify = verify if secret is None: secret = token_bytes(128) self.secret = secret print(repr(self))
def new(self): """Set up a new vault, with a new salt""" with open(self.filename,'wb') as f: f.write(secrets.token_bytes(SALT_SIZE))
def make_random(num_bytes): make_rfc3261(token(token_bytes(num_bytes)))
def encrypt(self, plain: bytes) -> bytes: padding = secrets.token_bytes((-len(plain)) % 16) return b''.join(self.encrypt_block(plain_block) for plain_block in Bytedata(plain + padding).blocks(16))
def generate_token(cls): return token_bytes(64)
def test_fewer_than_256_bits_is_error(): try: hj.JWTClient(secrets.token_bytes(31)) assert False except ValueError as err: assert re.search('found secret key with 31 bytes', str(err))
def create_plots(args, root_path, use_datetime=True, test_private_keys: Optional[List] = None): config_filename = config_path_for_filename(root_path, "config.yaml") if args.tmp2_dir is None: args.tmp2_dir = args.final_dir farmer_public_key: G1Element if args.farmer_public_key is not None: farmer_public_key = G1Element.from_bytes( bytes.fromhex(args.farmer_public_key)) else: farmer_public_key = get_default_farmer_public_key() pool_public_key: G1Element if args.pool_public_key is not None: pool_public_key = bytes.fromhex(args.pool_public_key) else: pool_public_key = get_default_pool_public_key() if args.num is not None: num = args.num else: num = 1 log.info( f"Creating {num} plots of size {args.size}, pool public key: " f"{bytes(pool_public_key).hex()} farmer public key: {bytes(farmer_public_key).hex()}" ) tmp_dir_created = False if not args.tmp_dir.exists(): mkdir(args.tmp_dir) tmp_dir_created = True tmp2_dir_created = False if not args.tmp2_dir.exists(): mkdir(args.tmp2_dir) tmp2_dir_created = True mkdir(args.final_dir) finished_filenames = [] config = load_config(root_path, config_filename) plot_filenames = get_plot_filenames(config["harvester"]) for i in range(num): # Generate a random master secret key if test_private_keys is not None: assert len(test_private_keys) == num sk: PrivateKey = test_private_keys[i] else: sk = AugSchemeMPL.key_gen(token_bytes(32)) # The plot public key is the combination of the harvester and farmer keys plot_public_key = ProofOfSpace.generate_plot_public_key( master_sk_to_local_sk(sk).get_g1(), farmer_public_key) # The plot id is based on the harvester, farmer, and pool keys plot_id: bytes32 = ProofOfSpace.calculate_plot_id( pool_public_key, plot_public_key) if args.plotid is not None: log.info(f"Debug plot ID: {args.plotid}") plot_id: bytes32 = bytes32(bytes.fromhex(args.plotid)) plot_memo: bytes32 = stream_plot_info(pool_public_key, farmer_public_key, sk) if args.memo is not None: log.info(f"Debug memo: {args.memo}") plot_memo: bytes32 = bytes.fromhex(args.memo) dt_string = datetime.now().strftime("%Y-%m-%d-%H-%M") if use_datetime: filename: str = f"plot-k{args.size}-{dt_string}-{plot_id}.plot" else: filename = f"plot-k{args.size}-{plot_id}.plot" full_path: Path = args.final_dir / filename if args.final_dir.resolve() not in plot_filenames: if (str(args.final_dir.resolve()) not in config["harvester"]["plot_directories"]): # Adds the directory to the plot directories if it is not present config = add_plot_directory(str(args.final_dir.resolve()), root_path) if not full_path.exists(): log.info(f"Starting plot {i + 1}/{num}") # Creates the plot. This will take a long time for larger plots. plotter: DiskPlotter = DiskPlotter() plotter.create_plot_disk( str(args.tmp_dir), str(args.tmp2_dir), str(args.final_dir), filename, args.size, plot_memo, plot_id, args.buffer, ) finished_filenames.append(filename) else: log.info(f"Plot {filename} already exists") log.info("Summary:") if tmp_dir_created: try: args.tmp_dir.rmdir() except Exception: log.info( f"warning: did not remove primary temporary folder {args.tmp_dir}, it may not be empty." ) if tmp2_dir_created: try: args.tmp2_dir.rmdir() except Exception: log.info( f"warning: did not remove secondary temporary folder {args.tmp2_dir}, it may not be empty." ) log.info(f"Created a total of {len(finished_filenames)} new plots") for filename in finished_filenames: log.info(filename)
from secrets import token_bytes SESSIONS = 0 LISTENERS = 0 args = None ipc_pass = token_bytes(15)
def __init__(self): self.data = dict() self.key = secrets.token_bytes(8)
def _make_context( self, negotiate_message: Optional[NegotiateMessage] = None ) -> Generator[Union[NegotiateMessage, AuthenticateMessage], ChallengeMessage, None]: """ Initiate an NTLM authentication procedure. :param negotiate_message: An NTLM negotiate message that will be used instead of a defaultly-constructed one. :return: An NTLM authenticate message. """ if not (3 <= self.lm_compatibility_level <= 5): raise NotImplementedError negotiate_message: NegotiateMessage = negotiate_message or NegotiateMessage( negotiate_flags=NegotiateFlags( negotiate_unicode=True, request_target=True, negotiate_sign=True, negotiate_seal=True, negotiate_ntlm=True, negotiate_always_sign=True, negotiate_extended_sessionsecurity=True, negotiate_128=True, negotiate_key_exch=True, negotiate_56=True ) ) challenge_message: ChallengeMessage = yield negotiate_message self.neg_flg: NegotiateFlags = challenge_message.negotiate_flags nt_challenge_response, lm_challenge_response, session_base_key = produce_lmv2_and_ntlmv2_response( response_key_nt=self._produce_response_key_nt(), response_key_lm=self._produce_response_key_lm(), server_challenge=challenge_message.challenge, # NOTE: I have `target_info` as optional in `ChallengeMessage`... server_name=self._make_server_name( challenge_message_target_info=deepcopy(challenge_message.target_info) ), time=next( av_pair for av_pair in challenge_message.target_info if isinstance(av_pair, TimestampAVPair) ).filetime ) key_exchange_key: bytes = session_base_key if challenge_message.negotiate_flags.negotiate_key_exch: self.exported_session_key: bytes = token_bytes(nbytes=16) self.encrypted_random_session_key: bytes = ARC4.new( key=key_exchange_key ).encrypt(plaintext=self.exported_session_key) else: self.exported_session_key: bytes = key_exchange_key self.encrypted_random_session_key: bytes = b'' self._make_keys_and_cipher_handles() yield self._make_authenticate_message( lm_challenge_response=lm_challenge_response, nt_challenge_response=nt_challenge_response, negotiate_message=negotiate_message, challenge_message=challenge_message )
def test_basic_sharing_random(): secret = secrets.token_bytes(16) mnemonics = shamir.generate_mnemonics(1, [(3, 5)], secret)[0] assert shamir.combine_mnemonics(mnemonics[:3]) == shamir.combine_mnemonics( mnemonics[2:])
def generate_key(): import secrets return secrets.token_bytes(64)
def hash_password(password: str, salt: Optional[bytes] = None) -> HashAndSalt: pepper = b'alchemists discovered that gold came from earth air fire and water' salt = salt or secrets.token_bytes(16) salted_pass = salt + password.encode('utf-8') return hashlib.pbkdf2_hmac('sha512', salted_pass, pepper, 100000), salt