예제 #1
0
    def test_invalid_ss58_format_range_exceptions(self):
        with self.assertRaises(ValueError) as cm:
            ss58_encode(self.alice_keypair.public_key, ss58_format=-1)

        self.assertEqual('Invalid value for ss58_format', str(cm.exception))

        with self.assertRaises(ValueError) as cm:
            ss58_encode(self.alice_keypair.public_key, ss58_format=16384)

        self.assertEqual('Invalid value for ss58_format', str(cm.exception))
예제 #2
0
    def test_invalid_reserved_ss58_format(self):
        with self.assertRaises(ValueError) as cm:
            ss58_encode(self.alice_keypair.public_key, ss58_format=46)

        self.assertEqual('Invalid value for ss58_format', str(cm.exception))

        with self.assertRaises(ValueError) as cm:
            ss58_encode(self.alice_keypair.public_key, ss58_format=47)

        self.assertEqual('Invalid value for ss58_format', str(cm.exception))
예제 #3
0
    def test_encode_with_2_byte_prefix(self):
        public_key = ss58_decode('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua')

        self.assertEqual(
            'yGHU8YKprxHbHdEv7oUK4rzMZXtsdhcXVG2CAMyC9WhzhjH2k',
            ss58_encode(public_key, ss58_format=255)
        )
예제 #4
0
    def test_contract_event_decoding(self):
        contract_event_data = '0x0001d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d018eaf04151687' + \
                              '736326c9fea17e25fc5287613693c912909cb226aa4794f26a480000a7dcf75015000000000000000000'

        contract_event_obj = ContractEvent(
            data=ScaleBytes(contract_event_data),
            runtime_config=self.substrate.runtime_config,
            contract_metadata=self.contract_metadata)

        contract_event_obj.decode()

        self.assertEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                         ss58_encode(contract_event_obj.args[0]['value'], 42))
        self.assertEqual('5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty',
                         ss58_encode(contract_event_obj.args[1]['value'], 42))
        self.assertEqual(6000000000000000, contract_event_obj.args[2]['value'])
def show_extrinsics_of_block(substrate,
                             bh=None):  # Set block_hash to None for chaintip
    """
    variation of
    https://github.com/polkascan/py-substrate-interface/blob/master/README.md#get-extrinsics-for-a-certain-block
    """

    # Retrieve extrinsics in block
    result = substrate.get_runtime_block(block_hash=bh)

    for extrinsic in result['block']['extrinsics']:

        if 'account_id' in extrinsic:
            signed_by_address = ss58_encode(address=extrinsic['account_id'],
                                            address_type=2)
        else:
            signed_by_address = None

        print('\n{}.{} Signer={}'.format(extrinsic['call_module'],
                                         extrinsic['call_function'],
                                         signed_by_address),
              end=". ")

        # Loop through params

        numParams = len(extrinsic['params'])
        if numParams:
            print("Param/s: ", end="")
        for i, param in enumerate(extrinsic['params']):

            if param['type'] == 'Address':
                param['value'] = ss58_encode(address=param['value'],
                                             address_type=2)

            if param['type'] == 'Compact<Balance>':
                param['value'] = '{} DOT'.format(param['value'] / 10**12)

            print("{}={}".format(param['name'], param['value']), end="")
            if i + 1 < numParams:
                print(", ")

        print()
def get_escrow_address(addresses: list, *, threshold: int = 2):
    _addresses = []
    for addr in addresses:
        _addr = ss58_decode(addr)
        _addr = bytes.fromhex(_addr)
        _addresses.append(_addr)

    _addresses = sorted(_addresses)
    print(_addresses)
    escrow_addr = multisig.multi_account_id(_addresses, threshold)
    escrow_addr = binascii.hexlify(bytearray(escrow_addr)).decode("ascii")
    return ss58_encode(escrow_addr, 2)
    def setUp(self):
        self.buyer_address = ss58_encode(buyer_keypair[0], 2)
        self.seller_address = ss58_encode(seller_keypair[0], 2)
        self.admin_address = ss58_encode(admin_keypair[0], 2)
        self.seller_priv = seller_keypair[1].hex()
        self.seller_pub = ss58_decode(self.seller_address)
        self.admin_priv = admin_keypair[1].hex()
        self.admin_pub = ss58_decode(self.admin_address)

        substrate.init_runtime(block_hash=None)

        # Prepare the inner call as we will reuse it, lets not write code twice
        self.inner_call = ScaleDecoder.get_decoder_class(
            "Call", metadata=substrate.metadata_decoder)

        self.inner_call.encode({
            "call_module": "Balances",
            "call_function": "transfer",
            "call_args": {
                "dest": self.buyer_address,
                "value": settings.trade_value,
            },
        })
예제 #8
0
    def check_transfer_config( config: 'bittensor.Config'):
        if config.subtensor.network == bittensor.defaults.subtensor.network and not config.no_prompt:
            config.subtensor.network = Prompt.ask("Enter subtensor network", choices=bittensor.__networks__, default = bittensor.defaults.subtensor.network)

        if config.wallet.name == bittensor.defaults.wallet.name and not config.no_prompt:
            wallet_name = Prompt.ask("Enter wallet name", default = bittensor.defaults.wallet.name)
            config.wallet.name = str(wallet_name)

        # Get destination.
        if not config.dest:
            dest = Prompt.ask("Enter destination public key: (ss58 or ed2519)")
            if len(dest) == 48:
                try:
                    ss58_decode(dest)
                    config.dest = str(dest)
                except ValueError:
                    console.print(":cross_mark:[red] Invalid public key format[/red] [bold white]{}[/bold white]".format(dest))
                    sys.exit()
            elif len(dest) == 66 or len(dest) == 64:
                try:
                    ss58_encode(dest)
                    config.dest = str(dest)
                except ValueError:
                    console.print(":cross_mark:[red] Invalid ss58 address format[/red] [bold white]{}[/bold white]".format(dest))
                    sys.exit()
            else:
                console.print(":cross_mark:[red] Invalid address format[/red] [bold white]{}[/bold white]".format(dest))
                sys.exit()
                    
        # Get amount.
        if not config.amount:
            amount = Prompt.ask("Enter Tao amount to transfer")
            try:
                config.amount = float(amount)
            except ValueError:
                console.print(":cross_mark:[red] Invalid Tao amount[/red] [bold white]{}[/bold white]".format(amount))
                sys.exit()
예제 #9
0
def get_nominators():
    prefix = substrate.generate_storage_hash("Staking", "Nominators")
    pairs = substrate.rpc_request(method="state_getPairs",
                                  params=[prefix, head])['result']

    nominators = list(
        map(
            lambda p: ("0x" + p[0][-64:],
                       substrate.decode_scale("Nominations<AccountId>", p[1])[
                           'targets']), pairs))

    nominators = list(
        map(lambda x: (
            ss58_encode(x[0], substrate.address_type),
            x[1],
        ), nominators))

    return list(
        map(
            lambda x: (
                x[0],
                get_backing_stake_of(x[0]),
                [ss58_encode(acc, substrate.address_type) for acc in x[1]],
            ), nominators))
예제 #10
0
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))
예제 #11
0
def get_backing_stake_of(who):
    ctrl = substrate.get_runtime_state(
        module="Staking",
        storage_function="Bonded",
        params=[who],
        block_hash=head,
    )['result']

    ctrl = ss58_encode(ctrl, substrate.address_type)

    ledger = substrate.get_runtime_state(
        module="Staking",
        storage_function="Ledger",
        params=[ctrl],
        block_hash=head,
    )['result']

    return ledger['active']
예제 #12
0
    def test_create_escrow_address(self):
        buyer_addr = "CdVuGwX71W4oRbXHsLuLQxNPns23rnSSiZwZPN4etWf6XYo"
        seller_addr = "J9aQobenjZjwWtU2MsnYdGomvcYbgauCnBeb8xGrcqznvJc"
        admin_addr = "HvqnQxDQbi3LL2URh7WQfcmi8b2ZWfBhu7TEDmyyn5VK8e2"

        def kusama_addr_to_account_id(address):
            decoded_addr = ss58_decode(address)
            decoded_addr_bytes = bytes.fromhex(decoded_addr)
            return decoded_addr_bytes

        buyer_id = kusama_addr_to_account_id(buyer_addr)
        seller_id = kusama_addr_to_account_id(seller_addr)
        admin_id = kusama_addr_to_account_id(admin_addr)

        trade_addresses = sorted([buyer_id, seller_id, admin_id])

        escrow_addr = multisig.multi_account_id(trade_addresses, 2)
        escrow_addr = binascii.hexlify(bytearray(escrow_addr)).decode("ascii")

        # This address was manually generated from the Polkadot UI app
        expected_address = "HFXXfXavDuKhLLBhFQTat2aaRQ5CMMw9mwswHzWi76m6iLt"

        self.assertEqual(ss58_encode(escrow_addr, 2), expected_address)
    def test_chrome_extension_mnemonic(self):
        mnemonic = ("prefer fashion insect dizzy energy marble"
                    " forget artefact aspect short surface leave")
        seed_array = bip39.bip39_to_mini_secret(mnemonic, "")
        seed = binascii.hexlify(bytearray(seed_array)).decode("ascii")

        seed_from_mnemonic = (
            "3f686928bda5b57a0992c999aea74d65f844be234686871a2ddc6b003d586786")

        self.assertEqual(seed, seed_from_mnemonic)

        expected_publickey = (
            "8852f77f2aea5d2d5808cefa7cd49a3ed0ce1f1aa8ff2564c3cb96cb2510337d")

        keypair = sr25519.pair_from_seed(bytes.fromhex(seed_from_mnemonic))
        public_key = keypair[0].hex()

        self.assertEqual(public_key, expected_publickey)

        expected_address = "Ff4gBd7WcHgsNVhr5HGPQXQx4PzPHGtHdNVaCRK5d5KeMHh"

        address = ss58_encode(keypair[0], 2)

        self.assertEqual(address, expected_address)
예제 #14
0
 def test_encode_2_bytes_account_index(self):
     self.assertEqual('3xygo', ss58_encode_account_index(256, ss58_format=2))
     self.assertEqual('3xygo', ss58_encode('0x0001', ss58_format=2))
예제 #15
0
 def test_encode_1_byte_account_index_with_format(self):
     self.assertEqual('g4b', ss58_encode_account_index(1, ss58_format=2))
     self.assertEqual('g4b', ss58_encode('0x01', ss58_format=2))
예제 #16
0
    def test_invalid_public_key(self):
        with self.assertRaises(ValueError) as cm:
            ss58_encode(self.alice_keypair.public_key[:30])

        self.assertEqual('Invalid length for address', str(cm.exception))
예제 #17
0
import binascii

from substrateinterface.utils.ss58 import ss58_decode
from substrateinterface.utils.ss58 import ss58_encode

from bindings import multisig

buyer_addr = "FQ2W1LrE9u6hrgv9bZzy3zq7e3JARRZm3d3UvnMREmAZCBb"
seller_addr = "DUorqgcRkXhpQvfhsXfjSZVNWRJWE5qGo7md53Cpix8BRnb"
admin_addr = "D3JaNpndKAG8PMZnsvsNE7UemYpVs44PB6kCHxW4wNSkxZh"


def kusama_addr_to_account_id(address):
    decoded_addr = ss58_decode(address)
    decoded_addr_bytes = bytes.fromhex(decoded_addr)
    return decoded_addr_bytes


buyer_id = kusama_addr_to_account_id(buyer_addr)
seller_id = kusama_addr_to_account_id(seller_addr)
admin_id = kusama_addr_to_account_id(admin_addr)

trade_addresses = sorted([buyer_id, seller_id, admin_id])

escrow_addr = multisig.multi_account_id(trade_addresses, 2)
escrow_addr = binascii.hexlify(bytearray(escrow_addr)).decode("ascii")
escrow_addr = ss58_encode(escrow_addr, 2)
print(escrow_addr)
예제 #18
0
파일: base.py 프로젝트: encouv/explorer-api
 def format_address(self, item):
     item['orig_value'] = item['value'].replace('0x', '')
     item['value'] = ss58_encode(item['value'].replace('0x', ''),
                                 SUBSTRATE_ADDRESS_TYPE)
     return item
예제 #19
0
 def test_invalid_ss58_format_range_exceptions(self):
     with self.assertRaises(ValueError):
         ss58_encode(self.alice_keypair.public_key, ss58_format=-1)
         ss58_encode(self.alice_keypair.public_key, ss58_format=16384)
예제 #20
0
 def test_encode_33_byte_address(self):
     self.assertEqual(
         'KWCv1L3QX9LDPwY4VzvLmarEmXjVJidUzZcinvVnmxAJJCBou',
         ss58_encode('0x03b9dc646dd71118e5f7fda681ad9eca36eb3ee96f344f582fbe7b5bcdebb13077')
     )
 def decompose_seed(seed):
     keypair = sr25519.pair_from_seed(bytes.fromhex(seed))
     public_key = keypair[0].hex()
     private_key = keypair[1].hex()
     address = ss58_encode(keypair[0], 2)
     return address, public_key, private_key
예제 #22
0
def get_candidates():
    prefix = substrate.generate_storage_hash("Staking", "Validators")
    pairs = substrate.rpc_request(method="state_getPairs",
                                  params=[prefix, head])['result']
    last_32_bytes = list(map(lambda p: "0x" + p[0][-64:], pairs))
    return list(map(lambda k: ss58_encode(k), last_32_bytes))
예제 #23
0
 def test_invalid_public_key(self):
     with self.assertRaises(ValueError):
         ss58_encode(self.alice_keypair.public_key[:30])
예제 #24
0
 def test_invalid_reserved_ss58_format(self):
     with self.assertRaises(ValueError):
         ss58_encode(self.alice_keypair.public_key, ss58_format=46)
         ss58_encode(self.alice_keypair.public_key, ss58_format=47)
예제 #25
0
 def test_encode_4_bytes_account_index(self):
     self.assertEqual('zswfoZa', ss58_encode_account_index(67305985, ss58_format=2))
     self.assertEqual('zswfoZa', ss58_encode('0x01020304', ss58_format=2))
def example_calls(substrate, account, block_hash=None):
    """
    Set block_hash to None for chaintip
    """

    # version information via node request
    rv=substrate.rpc_request(method="chain_getRuntimeVersion", params=[])["result"]
    v= substrate.get_version()
    print("implName=%s, transactionVersion=%s, versiontag=%s" %(rv['implName'], rv['transactionVersion'], v) )

    # Retrieve extrinsics in block
    result = substrate.get_runtime_block(block_hash=block_hash)
    
    for extrinsic in result['block']['extrinsics']:
    
        if 'account_id' in extrinsic:
            signed_by_address = ss58_encode(address=extrinsic['account_id'], address_type=2)
        else:
            signed_by_address = None
    
        print('\nModule: {}\nCall: {}\nSigned by: {}'.format(
            extrinsic['call_module'],
            extrinsic['call_function'],
            signed_by_address
        ))
    
        for param in extrinsic['params']:
    
            if param['type'] == 'Address':
                param['value'] = ss58_encode(address=param['value'], address_type=2)
    
            if param['type'] == 'Compact<Balance>':
                param['value'] = '{} DOT'.format(param['value'] / 10**12)
    
            print("Param '{}': {}".format(param['name'], param['value']))
    
    # Storage call examples
    print("\n\nCurrent Account info: {} DOT".format(
        substrate.get_runtime_state(
            module='System',
            storage_function='Account',
            params=[account]
        ).get('result')
    ))
    
    try:
        print("Balance @ {}: {} DOT".format(
            block_hash,
            substrate.get_runtime_state(
                module='Balances',
                storage_function='FreeBalance',
                params=[account],
                block_hash=block_hash
            ).get('result')
        ))
    except Exception as e:
        print ("ERROR: %s %s" %(type(e), e))
    
    # Create, sign and submit extrinsic example
    
    mnemonic = Keypair.generate_mnemonic()
    
    keypair = Keypair.create_from_mnemonic(mnemonic, 2)
    
    print("Created address: {}".format(keypair.ss58_address))
    
    call = substrate.compose_call(
        call_module='Balances',
        call_function='transfer',
        call_params={
            'dest': account,
            'value': 2 * 10**3
        }
    )
    
    extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair)
    
    try:
        # result = substrate.send_extrinsic(extrinsic)
        result = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)
    
        print('Extrinsic "{}" included in block "{}"'.format(
            result['extrinsic_hash'], result.get('block_hash')
        ))
    
    except SubstrateRequestException as e:
        print("Failed to send: {}".format(e))
예제 #27
0
 def test_encode_8_bytes_account_index(self):
     self.assertEqual('848Gh2GcGaZia', ss58_encode('0x2a2c0a0000000000', ss58_format=2))
예제 #28
0
 def test_encode_subkey_generated_pairs(self):
     for subkey_pair in self.subkey_pairs:
         self.assertEqual(
             subkey_pair['address'],
             ss58_encode(address=subkey_pair['public_key'], ss58_format=subkey_pair['ss58_format'])
         )
def get_addr_from_seed(seed: str,):
    keypair = sr25519.pair_from_seed(bytes.fromhex(seed))
    return ss58_encode(keypair[0], 2)
예제 #30
0
from substrateinterface.utils.ss58 import ss58_encode

substrate = SubstrateInterface(url="wss://kusama-rpc.polkadot.io/",
                               ss58_format=2,
                               type_registry_preset='kusama')

# Set block_hash to None for chaintip
block_hash = "0x588930468212316d8a75ede0bec0bc949451c164e2cea07ccfc425f497b077b7"

# Retrieve extrinsics in block
result = substrate.get_runtime_block(block_hash=block_hash)

for extrinsic in result['block']['extrinsics']:

    if 'account_id' in extrinsic:
        signed_by_address = ss58_encode(address=extrinsic['account_id'],
                                        ss58_format=2)
    else:
        signed_by_address = None

    print('\nModule: {}\nCall: {}\nSigned by: {}'.format(
        extrinsic['call_module'], extrinsic['call_function'],
        signed_by_address))

    for param in extrinsic['params']:

        if param['type'] == 'Address':
            param['value'] = ss58_encode(address=param['value'], ss58_format=2)

        if param['type'] == 'Compact<Balance>':
            param['value'] = '{} DOT'.format(param['value'] / 10**12)