async def get_uid_for_pubkey__does_not_exist(): client.connect() await client.is_connected() random = Keypair.create_from_mnemonic(Keypair.generate_mnemonic()) uid = await client.get_uid_for_pubkey(random.public_key) assert uid is None
def new_neuron(): # 1. Init Config item. config = { 'session': { 'datapath': 'data/', 'learning_rate': 0.01, 'momentum': 0.9, 'batch_size_train': 64, 'batch_size_test': 64, 'log_interval': 10, 'sync_interval': 100, 'priority_interval': 100, 'name': 'mnist', 'trial_id': '1608070667' }, 'synapse': { 'target_dim': 10 }, 'dendrite': { 'key_dim': 100, 'topk': 10, 'stale_emit_filter': 10000, 'pass_gradients': True, 'timeout': 0.5, 'do_backoff': True, 'max_backoff': 100 }, 'axon': { 'local_port': 8091, 'external_ip': '191.97.53.53', 'max_workers': 5, 'max_gradients': 1000 }, 'nucleus': { 'max_workers': 5, 'queue_timeout': 5, 'queue_maxsize': 1000 }, 'metagraph': { 'chain_endpoint': '206.189.254.5:12345', 'stale_emit_filter': 10000 }, 'meta_logger': { 'log_dir': 'data/' }, 'neuron': { 'keyfile': None, 'keypair': None } } config = Munch.fromDict(config) logger.info(Config.toString(config)) mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic) neuron = Neuron(config) neuron.keypair = keypair return neuron
def test_sign_and_verify_scale_bytes(self): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic) data = ScaleBytes('0x1234') signature = keypair.sign(data) self.assertTrue(keypair.verify(data, signature))
def __save_keypair(keypair: Keypair, path: str): path = os.path.expanduser(path) with open(path, 'w') as file: json.dump(keypair.toDict(), file) file.close() os.chmod(path, stat.S_IWUSR | stat.S_IRUSR)
def test_verify_unsupported_crypto_type(self): keypair = Keypair.create_from_private_key( ss58_address='16ADqpMa4yzfmWs3nuTSMhfZ2ckeGtvqhPWCNqECEGDcGgU2', private_key='0x1f1995bdf3a17b60626a26cfe6f564b337d46056b7a1281b64c649d592ccda0a9cffd34d9fb01cae1fba61aeed184c817442a2186d5172416729a4b54dd4b84e', crypto_type=3 ) self.assertRaises(ConfigurationError, keypair.verify, "0x1234", '0x1234')
def test_only_provide_public_key(self): keypair = Keypair( public_key='0xe4359ad3e2716c539a1d663ebd0a51bdc5c98a12e663bb4c4402db47828c9446', address_type=0 ) self.assertEqual(keypair.ss58_address, '16ADqpMa4yzfmWs3nuTSMhfZ2ckeGtvqhPWCNqECEGDcGgU2')
def test_hdkd_path_gt_32_bytes(self): derivation_address = '5GR5pfZeNs1uQiSWVxZaQiZou3wdZiX894eqgvfNfHbEh7W2' derivation_path = '//PathNameLongerThan32BytesWhichShouldBeHashed' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_hdkd_nested_soft_hard_path(self): derivation_address = '5Cwc8tShrshDJUp1P1M21dKUTcYQpV9GcfSa4hUBNmMdV3Cx' derivation_path = '/Bob//test' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_hdkd_nested_hard_soft_path(self): derivation_address = '5CJGwWiKXSE16WJaxBdPZhWqUYkotgenLUALv7ZvqQ4TXeqf' derivation_path = '//Bob/test' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def test_hdkd_default_to_dev_mnemonic(self): derivation_address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' derivation_path = '//Alice' derived_keypair = Keypair.create_from_uri(derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
async def test_get_current_block(setup_chain): keypair = Keypair.create_from_uri("//Alice") client = connect(keypair, setup_chain) await client.is_connected() result = await client.get_current_block() assert result >= 0
async def test_connect_success(): socket = "localhost:9944" keypair = Keypair.create_from_uri('//Alice') client = WSClient(socket, keypair) client.connect() result = await client.is_connected() assert result == True
async def test_connect_failed(): socket = 'localhost:9999' keypair = Keypair.create_from_uri('//Alice') client = WSClient(socket, keypair) client.connect() result = await client.is_connected() assert result == False
def test_hdkd_hard_path(self): mnemonic = 'old leopard transfer rib spatial phone calm indicate online fire caution review' derivation_address = '5FEiH8iuDUw271xbqWTWuB6WrDjv5dnCeDX1CyHubAniXDNN' derivation_path = '//Alice' derived_keypair = Keypair.create_from_uri(mnemonic + derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
async def test_get_balance_success(setup_chain): hotkeypair = Keypair.create_from_uri("//Alice") client = connect(hotkeypair, setup_chain) await client.is_connected() result = await client.get_balance(hotkeypair.ss58_address) assert int(result) == pow(10, 9)
def test_hdkd_soft_path(self): mnemonic = 'old leopard transfer rib spatial phone calm indicate online fire caution review' derivation_address = '5GNXbA46ma5dg19GXdiKi5JH3mnkZ8Yea3bBtZAvj7t99P9i' derivation_path = '/Alice' derived_keypair = Keypair.create_from_uri(mnemonic + derivation_path) self.assertEqual(derivation_address, derived_keypair.ss58_address)
def load_keypair_from_data(data) -> Keypair: try: data = json.loads(data) if "secretSeed" not in data: raise KeyFileError("Keyfile corrupt") return Keypair.create_from_seed(data['secretSeed']) except BaseException as e: logger.debug(e) raise KeyFileError("Keyfile corrupt")
def test_dendrite_backoff(): _config = Munch.fromDict(config.copy()) _config.dendrite.do_backoff = True _config.dendrite.max_backoff = 1 _mnemonic = Keypair.generate_mnemonic() _keypair = Keypair.create_from_mnemonic(_mnemonic) _dendrite = bittensor.dendrite.Dendrite(_config, metagraph) _neuron_pb2 = bittensor_pb2.Neuron( version=bittensor.__version__, public_key=_keypair.public_key, address='0.0.0.0', port=12345, ) # Add a quick sleep here, it appears that this test is intermittent, likely based on the asyncio operations of past tests. # This forces the test to sleep a little while until the dust settles. # Bandaid patch, TODO(unconst): fix this. time.sleep(5) # Normal call. x = torch.rand(3, 3, bittensor.__network_dim__) out, ops = _dendrite.forward_tensor([_neuron_pb2], [x]) assert ops[0].item() == bittensor_pb2.ReturnCode.Unavailable assert list(out[0].shape) == [3, 3, bittensor.__network_dim__] # Backoff call. x = torch.rand(3, 3, bittensor.__network_dim__) out, ops = _dendrite.forward_tensor([_neuron_pb2], [x]) assert ops[0].item() == bittensor_pb2.ReturnCode.Backoff assert list(out[0].shape) == [3, 3, bittensor.__network_dim__] # Normal call. x = torch.rand(3, 3, bittensor.__network_dim__) out, ops = _dendrite.forward_tensor([_neuron_pb2], [x]) assert ops[0].item() == bittensor_pb2.ReturnCode.Unavailable assert list(out[0].shape) == [3, 3, bittensor.__network_dim__] # Backoff call. x = torch.rand(3, 3, bittensor.__network_dim__) out, ops = _dendrite.forward_tensor([_neuron_pb2], [x]) assert ops[0].item() == bittensor_pb2.ReturnCode.Backoff assert list(out[0].shape) == [3, 3, bittensor.__network_dim__]
async def test_transfer_success(setup_chain): coldkey_alice = Keypair.create_from_uri("//Alice") coldkey_bob = Keypair.create_from_uri("//Bob") client = connect(coldkey_alice, setup_chain) await client.is_connected() balance_alice = await client.get_balance(coldkey_alice.ss58_address) balance_bob = await client.get_balance(coldkey_bob.ss58_address) result = await client.transfer(coldkey_bob.public_key, Balance(pow(10, 4))) assert result is not None assert 'extrinsic_hash' in result # Wait until extrinsic is processed await asyncio.sleep(10) balance_alice_new = await client.get_balance(coldkey_alice.ss58_address) balance_bob_new = await client.get_balance(coldkey_bob.ss58_address) assert balance_alice_new < balance_alice assert balance_bob_new > balance_bob
async def test_subscribe_success(setup_chain): hotkeypair = generate_keypair() client = connect(hotkeypair, setup_chain) coldkeypair = Keypair.create_from_uri("//Alice") await client.is_connected() await client.subscribe("8.8.8.8", 6666, 0, coldkeypair.public_key) await asyncio.sleep( 10 ) # Sleep for at least one block to give extrinsic the chance to be put onto the blockchain uid = await client.get_uid_for_pubkey(hotkeypair.public_key) assert uid is not None
def validate_generate_mnemonic(mnemonic): if len(mnemonic) not in [12, 15, 18, 21, 24]: print( colored( "Mnemonic has invalid size. This should be 12,15,18,21 or 24 words", 'red')) quit() try: keypair = Keypair.create_from_mnemonic(" ".join(mnemonic)) return keypair except ValueError as e: print(colored(str(e), "red")) quit()
async def test_get_stake_for_uid___has_no_stake(setup_chain): hotkeyp = generate_keypair() coldkeyp = Keypair.create_from_uri("//Alice") client = connect(hotkeyp, setup_chain) await client.is_connected() await client.subscribe("8.8.8.8", 667, 0, coldkeyp.public_key) await asyncio.sleep(10) uid = await client.get_uid_for_pubkey(hotkeyp.public_key) result = await client.get_stake_for_uid(uid) assert int(result) == 0
async def test_set_weights_success(setup_chain): hotkeypair_alice = Keypair.create_from_uri("//Alice") hotkeypair_bob = Keypair.create_from_uri("//Bob") coldkeypair = generate_keypair() client_alice = connect(hotkeypair_alice, setup_chain) client_bob = connect(hotkeypair_bob, setup_chain) await client_alice.is_connected() await client_bob.is_connected() # Subscribe both alice and bob await client_alice.subscribe("8.8.8.8", 666, 0, coldkeypair.public_key) await client_bob.subscribe("8.8.8.8", 666, 0, coldkeypair.public_key) await asyncio.sleep(10) alice_uid = await client_alice.get_uid_for_pubkey( hotkeypair_alice.public_key) bob_uid = await client_bob.get_uid_for_pubkey(hotkeypair_bob.public_key) w_uids = [alice_uid, bob_uid] w_vals = [pow(2, 31) - 1, pow(2, 31) - 1] # 50/50 distro result = await client_alice.set_weights(w_uids, w_vals, wait_for_inclusion=False) assert result is not None assert "extrinsic_hash" in result await asyncio.sleep(10) result = await client_alice.weight_uids_for_uid(alice_uid) assert result == w_uids result = await client_alice.weight_vals_for_uid(alice_uid) assert result == w_vals
async def test_get_active(setup_chain): keypair = Keypair.create_from_uri("//Alice") client = connect(keypair, setup_chain) await client.is_connected() # Subscribe at least one await client.subscribe("8.8.8.8", 666, 0, keypair.public_key) await asyncio.sleep(10) result = await client.get_active() assert isinstance(result, List) assert len(result) > 0 elem = result[0] assert isinstance(elem[0], str) assert elem[0][:2] == "0x" assert len(elem[0][2:]) == 64 assert isinstance(elem[1], int)
async def test_add_stake_success(setup_chain): coldkeypair = Keypair.create_from_uri("//Alice") hotkeypair = generate_keypair() client = connect(hotkeypair, setup_chain) await client.is_connected() # Subscribe a new neuron with the hotkey await client.subscribe("8.8.8.8", 6666, 0, coldkeypair.public_key) await asyncio.sleep(10) # Now switch the connection the use the coldkey client = connect(coldkeypair, setup_chain) await client.is_connected() # Get the uid of the new neuron uid = await client.get_uid_for_pubkey(hotkeypair.public_key) assert uid is not None # Get the amount of stake, should be 0 result = await client.get_stake_for_uid(uid) assert int(result) == int(Balance(0)) # Add stake to new neuron result = await client.add_stake(Balance(4000), hotkeypair.public_key) assert result is not None assert 'extrinsic_hash' in result # Wait for the extrinsic to complete await asyncio.sleep(10) # Get the amount of stake result = await client.get_stake_for_uid(uid) assert int(result) == int(Balance(4000))
def __create_keypair() -> Keypair: return Keypair.create_from_mnemonic(Keypair.generate_mnemonic())
def gen_new_key(words): mnemonic = Keypair.generate_mnemonic(words) keypair = Keypair.create_from_mnemonic(mnemonic) return keypair
def generate_keypair(): return Keypair.create_from_mnemonic(Keypair.generate_mnemonic())
async def test_unstake_success(setup_chain): coldkeypair = Keypair.create_from_uri("//Alice") hotkeypair = generate_keypair() hotkey_client = connect(hotkeypair, setup_chain) await hotkey_client.is_connected() # Subscribe a new neuron with the hotkey await hotkey_client.subscribe("8.8.8.8", 6666, 0, coldkeypair.public_key) await asyncio.sleep(10) # Now switch the connection the use the coldkey coldkey_client = connect(coldkeypair, setup_chain) await coldkey_client.is_connected() # Get the uid of the new neuron uid = await coldkey_client.get_uid_for_pubkey(hotkeypair.public_key) logger.error(uid) assert uid is not None # Get the amount of stake, should be 0 result = await coldkey_client.get_stake_for_uid(uid) assert int(result) == int(Balance(0)) # Get the balance for the cold key, we use this for later comparison balance = await coldkey_client.get_balance(coldkeypair.public_key) # Add stake to new neuron result = await coldkey_client.add_stake(Balance(4000), hotkeypair.public_key) logger.info(result) assert result is not None assert 'extrinsic_hash' in result # Wait for the extrinsic to complete await asyncio.sleep(10) # Get current balance, should be 4000 less than first balance result = await coldkey_client.get_balance(coldkeypair.ss58_address) assert int(result) == int(balance) - 4000 # Get the amount of stake, should be 4000 result = await coldkey_client.get_stake_for_uid(uid) assert int(result) == int(Balance(4000)) # Now do the actual unstake # Reconnect with coldkey account coldkey_client = connect(coldkeypair, setup_chain) await coldkey_client.is_connected() # Do unstake result = await coldkey_client.unstake(Balance(4000), hotkeypair.public_key) assert result is not None assert 'extrinsic_hash' in result await asyncio.sleep(10) # Check if balance is the same as what we started with new_balance = await coldkey_client.get_balance(coldkeypair.ss58_address) assert int(new_balance) == int(balance)
async def test_connect_success(setup_chain): logger.error(setup_chain) hotkeypair = Keypair.create_from_uri("//Alice") client = connect(hotkeypair, setup_chain) result = await client.is_connected() assert result is True