def setUp(self): self.subtensor = bittensor.subtensor( network = 'nobunaga' ) self.wallet = bittensor.wallet() coldkey = Keypair.create_from_mnemonic(Keypair.generate_mnemonic()) self.wallet.set_coldkey(coldkey, encrypt=False, overwrite=True) self.wallet.set_coldkeypub(coldkey, encrypt=False, overwrite=True) self.wallet.set_hotkey(Keypair.create_from_mnemonic(Keypair.generate_mnemonic()), encrypt=False, overwrite=True) self.mock_neuron = self.subtensor._neuron_dict_to_namespace( dict({ "version":1, "ip":0, "port":0, "ip_type":0, "uid":1, "modality":0, "hotkey":'some_hotkey', "coldkey":'some_coldkey', "active":0, "last_update":0, "priority":0, "stake":1000000000000.0, "rank":0.0, "trust":0.0, "consensus":0.0, "incentive":0.0, "dividends":0.0, "emission":0.0, "bonds":[], "weights":[], "is_null":False }) ) self.neurons = self.subtensor.neurons() self.balance = Balance.from_tao(1000) assert True
def generate_wallet(coldkey: 'Keypair' = None, hotkey: 'Keypair' = None): wallet = bittensor.wallet() if not coldkey: coldkey = Keypair.create_from_mnemonic(Keypair.generate_mnemonic()) if not hotkey: hotkey = Keypair.create_from_mnemonic(Keypair.generate_mnemonic()) wallet.set_coldkey(coldkey, encrypt=False, overwrite=True) wallet.set_coldkeypub(coldkey, encrypt=False, overwrite=True) wallet.set_hotkey(hotkey, encrypt=False, overwrite=True) return wallet
def test_create_balance_transfer(self): # Create new keypair mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic, address_type=2) for substrate in [self.kusama_substrate, self.polkadot_substrate]: # Create balance transfer call call = substrate.compose_call( call_module='Balances', call_function='transfer', call_params={ 'dest': 'EaG2CRhJWPb7qmdcJvy3LiWdh26Jreu9Dx6R1rXxPmYXoDk', 'value': 2 * 10 ** 3 } ) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) self.assertEqual(extrinsic.address.value, keypair.public_key) self.assertEqual(extrinsic.call_module.name, 'Balances') self.assertEqual(extrinsic.call.name, 'transfer') # Randomly created account should always have 0 nonce, otherwise account already exists self.assertEqual(extrinsic.nonce.value, 0) try: substrate.submit_extrinsic(extrinsic) self.fail('Should raise no funds to pay fees exception') except SubstrateRequestException as e: # Extrinsic should be successful if account had balance, eitherwise 'Bad proof' error should be raised self.assertEqual(e.args[0]['data'], 'Inability to pay some fees (e.g. account balance too low)')
def setUpClass(cls): cls.kusama_substrate = SubstrateInterface( url=settings.KUSAMA_NODE_URL, ss58_format=2, type_registry_preset='kusama') cls.polkadot_substrate = SubstrateInterface( url=settings.POLKADOT_NODE_URL, ss58_format=0, type_registry_preset='polkadot') cls.substrate_v13 = SubstrateInterface(url=settings.POLKADOT_NODE_URL, ss58_format=0, type_registry_preset='polkadot') module_path = os.path.dirname(__file__) cls.metadata_fixture_dict = load_type_registry_file( os.path.join(module_path, 'fixtures', 'metadata_hex.json')) cls.metadata_v13_obj = cls.substrate_v13.runtime_config.create_scale_object( 'MetadataVersioned', data=ScaleBytes(cls.metadata_fixture_dict['V13'])) cls.metadata_v13_obj.decode() cls.substrate_v13.init_runtime() cls.substrate_v13.metadata_decoder = cls.metadata_v13_obj # Create new keypair mnemonic = Keypair.generate_mnemonic() cls.keypair = Keypair.create_from_mnemonic(mnemonic)
async def nine_nine(ctx, arg): if (ctx.channel.type == "private"): # Forbid DM in discord await ctx.send("Hold on Capt'ain, you can't send me private messages !" ) else: substrate = SubstrateInterface( url=node_rpc, address_type=42, type_registry_preset='substrate-node-template') call = substrate.compose_call(call_module='Balances', call_function='transfer', call_params={ 'dest': arg, 'value': 100 * 10**12 }) reply = "" keypair = Keypair.create_from_mnemonic(faucet_mnemonic) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) reply = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=False) await ctx.send( ctx.author.mention + " Awesome, you just received 100 dPIRL, it has no real value it's only the testnet token :) " + reply['extrinsic_hash'] + str(ctx.channel.type))
def regenerate_hotkey(self, mnemonic: Union[list, str], use_password: bool = True, overwrite: bool = False) -> 'Wallet': """ Regenerates the hotkey from passed mnemonic, encrypts it with the user's password and save the file Args: mnemonic: (Union[list, str], optional): Key mnemonic as list of words or string space separated words. use_password (bool, optional): Is the created key password protected. overwrite (bool, optional): Will this operation overwrite the hotkey under the same path <wallet path>/<wallet name>/hotkeys/<hotkey> Returns: wallet (bittensor.Wallet): this object with newly created hotkey. """ if isinstance(mnemonic, str): mnemonic = mnemonic.split() if len(mnemonic) not in [12, 15, 18, 21, 24]: raise ValueError( "Mnemonic has invalid size. This should be 12,15,18,21 or 24 words" ) keypair = Keypair.create_from_mnemonic(" ".join(mnemonic)) display_mnemonic_msg(keypair, "hotkey") self.set_hotkey(keypair, encrypt=use_password, overwrite=overwrite) return self
def transfer_token(token, _data): data_ = {} substrate = connect() _to = _data['to'] _amount = _data['amount'] caller = _data['caller'] mnemonic = _data['mnemonic'] keypair = Keypair.create_from_mnemonic(mnemonic) call = substrate.compose_call(call_module='Token', call_function='transfer', call_params={ 'token': token, 'to': _to, 'value': _amount }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) data_['extrinsic'] = extrinsic.value receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) data_['receiptExtrinsicHash'] = receipt.extrinsic_hash data_['receipBlockHash'] = receipt.block_hash return data_
def test_sign_and_verify_multi_lang(self): mnemonic = Keypair.generate_mnemonic( language_code=MnemonicLanguageCode.FRENCH) keypair = Keypair.create_from_mnemonic( mnemonic, language_code=MnemonicLanguageCode.FRENCH) signature = keypair.sign("Test123") self.assertTrue(keypair.verify("Test123", signature))
def bazaar_initiate_buy(_data): data_ = {} substrate = connect() price = _data['price'] amount = _data['amount'] seller = _data['seller'] mnemonic = _data['mnemonic'] keypair = Keypair.create_from_mnemonic(mnemonic) call = substrate.compose_call(call_module='Bazaar', call_function='initiate_buy', call_params={ 'price': price, 'amount': amount, 'seller': seller }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) data_['extrinsic'] = extrinsic.value receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) data_['receiptExtrinsicHash'] = receipt.extrinsic_hash data_['receipBlockHash'] = receipt.block_hash return data_
def test_sign_and_verify_ed25519(self): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic, crypto_type=KeypairType.ED25519) signature = keypair.sign("Test123") self.assertTrue(keypair.verify("Test123", signature))
def test_create_mortal_extrinsic(self): # Create new keypair mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic, ss58_format=2) for substrate in [self.kusama_substrate, self.polkadot_substrate]: # Create balance transfer call call = substrate.compose_call( call_module='Balances', call_function='transfer', call_params={ 'dest': 'EaG2CRhJWPb7qmdcJvy3LiWdh26Jreu9Dx6R1rXxPmYXoDk', 'value': 2 * 10**3 }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair, era={'period': 64}) try: substrate.submit_extrinsic(extrinsic) self.fail('Should raise no funds to pay fees exception') except SubstrateRequestException as e: # Extrinsic should be successful if account had balance, eitherwise 'Bad proof' error should be raised self.assertEqual( e.args[0]['data'], 'Inability to pay some fees (e.g. account balance too low)' )
def test_create_ed25519_keypair(self): mnemonic = "old leopard transfer rib spatial phone calm indicate online fire caution review" keypair = Keypair.create_from_mnemonic(mnemonic, address_type=0, crypto_type=KeypairType.ED25519) self.assertEqual(keypair.ss58_address, "16dYRUXznyhvWHS1ktUENGfNAEjCawyDzHRtN9AdFnJRc38h")
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 test_create_ecdsa_keypair_mnemonic(self): mnemonic = "old leopard transfer rib spatial phone calm indicate online fire caution review" # m/44'/60'/0'/0/0 keypair = Keypair.create_from_mnemonic(mnemonic, crypto_type=KeypairType.ECDSA) self.assertEqual("0xc6A0d8799D596BDd5C30E9ACbe2c63F37c142e35", keypair.ss58_address)
def run(): try: substrate = SubstrateInterface( url="wss://hk.listen.io/", address_type=42, type_registry_preset='default' ) import time time.sleep(1) keypair = Keypair.create_from_mnemonic("adult hunt thank force make satisfy saddle pumpkin reject very avoid goat") # print("Created address: {}".format(keypair.ss58_address)) mnemonic = Keypair.generate_mnemonic() # 接收方随机生成 keypair1 = Keypair.create_from_mnemonic(mnemonic, 2) # 可以直接调用自己定义的模块 不需要特殊处理 call = substrate.compose_call( call_module='Listen', call_function='air_drop', call_params={ # 接收方 # 'dest': '5GnGKSCitk1QPpMNugtTGX9t6TqzDGvL5BqKzLfHNsLSrwqN', 'des': keypair1.ss58_address, # 'value': 10 * 10**14 } ) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) try: result = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print("Extrinsic '{}' sent and included in block '{}'".format(result['extrinsic_hash'], result['block_hash'])) # substrate.s except SubstrateRequestException as e: print("Failed to send: {}".format(e)) except Exception as e: print(e)
def test_encrypt_decrypt_message(self): sender = Keypair.create_from_mnemonic( "nominee lift horse divert crop quantum proud between pink goose attack market", crypto_type=KeypairType.ED25519) recipient = Keypair( ss58_address="5DFZ8UzF5zeCLVPVRMkopNjVyxJNb1dHgGJYFDaVbm4CqNku", crypto_type=KeypairType.ED25519) message = "Violence is the last refuge of the incompetent - Isaac Asimov, Foundation" message_encrypted = sender.encrypt_message(message, recipient.public_key) recipient = Keypair.create_from_mnemonic( "almost desk skull craft chuckle bubble hollow innocent require physical purchase rabbit", crypto_type=KeypairType.ED25519) sender = Keypair( ss58_address="5DYUhnXkHux1rGTDaS9ACPQekbpSR2J5SyedDQNJVrk4Tn5t", crypto_type=KeypairType.ED25519) message_decrypted = recipient.decrypt_message( message_encrypted, sender.public_key).decode("utf-8") self.assertEqual(message_decrypted, message)
def verify_phone_code(phone, code, _data): result = verify_sms(phone, code) data_ = {} keypair = Keypair.create_from_mnemonic(_data['mnemonic']) if result.status == 'approved' and keypair: wallet = Wallet.objects.create(phone=phone, wallet_address=keypair.ss58_address) data_['wallet'] = wallet.id message = "Wallet: " + keypair.ss58_address + " has been generated for " + "+" + str(phone) data_['sid'] = send_sms('18454201095', '+' + str(phone), message) else: data_['status'] = 'pending' return data_
def create_MnemonicKey(self): substrate = SubstrateInterface(url=self.url, address_type=42, type_registry_preset='polkadot') # keypair=Keypair.create_from_seed("0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a") #alice账号 file_name = open('account_info.csv', encoding='utf-8') csv_lines = csv.reader(file_name) data = [] for row in csv_lines: if csv_lines.line_num == 1: continue else: data.append(row) print("data", data) for info in data: print("info", info) account = info[0] keypair = Keypair.create_from_mnemonic(self.seed_secret) # keypair = Keypair.create_from_mnemonic(info[1]) amount = info[1] print("type", type(amount)) call = substrate.compose_call( call_module='Balances', call_function='transfer', call_params={ # 接收方 'dest': account, 'value': Decimal(amount) * 10**10 }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) try: result = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print(result) print("Extrinsic '{}' sent and included in block '{}'".format( result['extrinsic_hash'], result['block_hash'])) except SubstrateRequestException as e: print(e) with open("faild_info.txt", "a") as f: f.write(account + "\n") time.sleep(5)
def generate_wallet(): mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic) data_ = { 'mnemonic': mnemonic, 'address': keypair.ss58_address, 'public_key': keypair.public_key, 'private_key': keypair.private_key, } return data_
def write_datalog(substrate, seed: str, data: str) -> str or None: """ Write any string to datalog Parameters ---------- substrate : substrate connection instance seed : mnemonic seed of account which writes datalog data : data tp be stored as datalog Returns ------- Hash of the datalog transaction """ # create keypair try: keypair = Keypair.create_from_mnemonic(seed, ss58_format=32) except Exception as e: rospy.logerr(f"Failed to create keypair for recording datalog: \n{e}") return None try: rospy.loginfo("Creating substrate call for recording datalog") call = substrate.compose_call(call_module="Datalog", call_function="record", call_params={'record': data}) rospy.loginfo( f"Successfully created a call for recording datalog:\n{call}") rospy.loginfo("Creating extrinsic for recording datalog") extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) except Exception as e: rospy.logerr( f"Failed to create an extrinsic for recording datalog: {e}") return None try: rospy.loginfo("Submitting extrinsic for recording datalog") receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) rospy.loginfo( f"Extrinsic {receipt.extrinsic_hash} for recording datalog sent and included in block" f" {receipt.block_hash}") return receipt.extrinsic_hash except Exception as e: rospy.logerr(f"Failed to submit extrinsic for recording datalog: {e}") return None
def verify_phone(phone, _data): wallets = Wallet.objects.filter(phone=phone).all() keypair = Keypair.create_from_mnemonic(_data['mnemonic']) if len(wallets) < 5 and keypair: result = send_verify_sms(phone) data_ ={ 'status': result.status, 'wallet': keypair.ss58_address } else: data_ = { 'phone': phone, 'registered': True } return data_
def get_keypair(args, config): enabled_signing_methods = config['Defaults'].keys() & {'signingseed', 'signingmnemonic', 'signinguri'} if (len(enabled_signing_methods) != 1): return None signing_method = list(enabled_signing_methods)[0] if signing_method == 'signingseed': keypair = Keypair.create_from_seed(config['Defaults'].get('signingseed')) if signing_method == 'signingmnemonic': keypair = Keypair.create_from_mnemonic(config['Defaults'].get('signingmnemonic')) if signing_method == 'signinguri': keypair = Keypair.create_from_uri(config['Defaults'].get('signinguri')) return keypair
def deserialize_keypair_from_keyfile_data( keyfile_data: bytes) -> 'bittensor.Keypair': """ Deserializes Keypair object from passed keyfile data. Args: keyfile_data ( bytest, required ): Keyfile data as bytes to be loaded. Returns: keypair (bittensor.Keypair): Keypair loaded from bytes. Raises: KeyFileError: Raised if the passed bytest cannot construct a keypair object. """ # Decode from json. keyfile_data = keyfile_data.decode() try: keyfile_dict = dict(json.loads(keyfile_data)) except: string_value = str(keyfile_data) if string_value[:2] == "0x": string_value = ss58_encode(string_value) keyfile_dict = { 'accountId': None, 'publicKey': None, 'secretPhrase': None, 'secretSeed': None, 'ss58Address': string_value } else: raise KeyFileError( 'Keypair could not be created from keyfile data: {}'.format( string_value)) if "secretSeed" in keyfile_dict and keyfile_dict['secretSeed'] != None: return Keypair.create_from_seed(keyfile_dict['secretSeed']) if "secretPhrase" in keyfile_dict and keyfile_dict['secretPhrase'] != None: return Keypair.create_from_mnemonic( mnemonic=keyfile_dict['secretPhrase']) if "ss58Address" in keyfile_dict and keyfile_dict['ss58Address'] != None: return Keypair(ss58_address=keyfile_dict['ss58Address']) else: raise KeyFileError( 'Keypair could not be created from keyfile data: {}'.format( keyfile_dict))
def get_keypair(args, config): signingseed = get_config(args, config, 'signingseed') signingmnemonic = get_config(args, config, 'signingmnemonic') signinguri = get_config(args, config, 'signinguri') ss58_format = get_ss58_address_format(get_config(args, config, 'network')) if signingseed is not None: keypair = Keypair.create_from_seed(signingseed, ss58_format) elif signingmnemonic is not None: keypair = Keypair.create_from_mnemonic(signingmnemonic, ss58_format) elif signinguri is not None: keypair = Keypair.create_from_uri(signinguri, ss58_format) else: keypair = None return keypair
def create_sell_order(ticker, _data, native=False): data_ = {} substrate = connect() if native: pair = substrate.query(module='Exchange', storage_function='PairNative', params=[str(ticker)]) else: pair = substrate.query(module='Exchange', storage_function='Pair', params=[str(ticker)]) data_['nativePair'] = native if pair: data_['pairId'] = ticker data_['pair'] = pair.value data_['pairExist'] = True else: data_['pair'] = [] data_['pairExist'] = False return data_ keypair = Keypair.create_from_mnemonic(_data['mnemonic']) if native: call_function = 'exchange_order_native_create_sell' else: call_function = 'exchange_order_create_sell' call = substrate.compose_call(call_module='Exchange', call_function=call_function, call_params={ 'pair': str(ticker), 'volume': _data['volume'], 'ratio': _data['ratio'] }) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) data_['extrinsic'] = extrinsic.value receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) data_['receiptExtrinsicHash'] = receipt.extrinsic_hash data_['receipBlockHash'] = receipt.block_hash return data_
def setUpClass(cls): cls.kusama_substrate = SubstrateInterface( url=settings.KUSAMA_NODE_URL, ss58_format=2, type_registry_preset='kusama') cls.polkadot_substrate = SubstrateInterface( url=settings.POLKADOT_NODE_URL, ss58_format=0, type_registry_preset='polkadot') module_path = os.path.dirname(__file__) cls.metadata_fixture_dict = load_type_registry_file( os.path.join(module_path, 'fixtures', 'metadata_hex.json')) # Create new keypair mnemonic = Keypair.generate_mnemonic() cls.keypair = Keypair.create_from_mnemonic(mnemonic)
def cancel_redemption(_data): data_ = {} substrate = connect() redemption_id = _data['redemptionId'] mnemonic = _data['mnemonic'] keypair = Keypair.create_from_mnemonic(mnemonic) call = substrate.compose_call(call_module='Bridge', call_function='cancel_redemption', call_params={'redemption_id': redemption_id}) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) data_['extrinsic'] = extrinsic.value receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) data_['receiptExtrinsicHash'] = receipt.extrinsic_hash data_['receipBlockHash'] = receipt.block_hash return data_
def sendPirl(mnemonic, destination, value): substrate = SubstrateInterface( url=node_rpc, address_type=42, type_registry_preset='substrate-node-template') call = substrate.compose_call( call_module='Balances', call_function='transfer', call_params={ 'dest': destination, # recipient address 'value': value * 10**12 # we send PIRLs and apply the 12 decimals }) keypair = Keypair.create_from_mnemonic(mnemonic) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) transaction = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print("extrinsic_hash: " + transaction['extrinsic_hash'], "block: " + transaction['block_hash'])
def bazaar_complete(): data_ = {} substrate = connect() trade_id = _data['trade_id'] mnemonic = _data['mnemonic'] keypair = Keypair.create_from_mnemonic(mnemonic) call = substrate.compose_call(call_module='Bazaar', call_function='compelete', call_params={'trade_id': trade_id}) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) data_['extrinsic'] = extrinsic.value receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) data_['receiptExtrinsicHash'] = receipt.extrinsic_hash data_['receipBlockHash'] = receipt.block_hash return data_
def feed(self, data: [StationData]): if self.config["frontier"]["enable"]: substrate = SubstrateInterface( url="wss://main.frontier.rpc.robonomics.network", ss58_format=32, type_registry_preset="substrate-node-template", type_registry={ "types": { "Record": "Vec<u8>", "<T as frame_system::Config>::AccountId": "AccountId", "RingBufferItem": { "type": "struct", "type_mapping": [ ["timestamp", "Compact<u64>"], ["payload", "Vec<u8>"], ], }, } }, ) keypair = Keypair.create_from_mnemonic(self.config["frontier"]["suri"]) for d in data: call = self.substrate.compose_call( call_module="Datalog", call_function="record", call_params={"record": f"{d.measurement}"}, ) extrinsic = self.substrate.create_signed_extrinsic( call=call, keypair=self.keypair ) rospy.loginfo(f"Extrincsic is: {extrinsic}") try: receipt = self.substrate.submit_extrinsic( extrinsic, wait_for_inclusion=True ) rospy.loginfo( f"Data sent to Robonomics datalog and included in block {receipt.block_hash}" ) # return except SubstrateRequestException as e: rospy.loginfo( f"Something went wrong during extrinsic submission to Robonomics: {e}" )