3

I'm generating a Public key from PolkadotJS as follows

    const keyring = new Keyring({ type: "sr25519" });
    const account = keyring.addFromUri("//Bob", { name: "Bob default" });
    
    // encoded public key 
    let public_key = keyring.encodeAddress(account.publicKey, 42);
    console.log(public_key);

I am adding the type of public_key as "public_key": "Vec<u8>",

I am reading the public key from Substrate Node as follows

// pk_raw is a Vec<u8> array 
let pk =  str::from_utf8(pk_raw.as_ref()).unwrap() 
// the above returns `5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty`

I need to generate the public key from this value. I tried with the followings

ed25519::Public::try_from(&*pk_raw).unwrap(); 
// above throws error since the data length is not equals to 32

fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        if data.len() == 32 {
            let mut inner = [0u8; 32];
            inner.copy_from_slice(data);
            Ok(Public(inner))
        } else {
            Err(())
        }
    }

Is there a way to generate the public key using 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty from Substrate Rust Side?

not 0x12
  • 19,360
  • 22
  • 67
  • 133

1 Answers1

4

You can use something like this:

use sp_core::crypto::Ss58Codec;

ed25519::Public::from_ss58check("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty").expect("Valid address")
bkchr
  • 621
  • 2
  • 5
  • This throws the following error let e = ed25519::Public::from_ss58check("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"). | ^^^^^^^^^^^^^^ function or associated item not found in sp_core::ed25519::Public It cannot find `from_ss58check` – not 0x12 Dec 21 '21 at 19:35
  • 1
    Have you imported the trait? https://github.com/paritytech/substrate/blob/master/primitives/core/src/ed25519.rs#L150-L157 here it is called as well. – bkchr Dec 22 '21 at 08:33