Cosmos: Convert pubkey to consensus address

590 Views Asked by At

I need to do a conversion using the cosmrs library, but I couldn't do it. Can anyone who has experience with this help with a sample code? Also I have a note to complete it:

Take the address from the pubkey and bech32 encode it using the correct HRP prefix

Cosmrs lib: https://docs.rs/cosmrs/latest/cosmrs/crypto/struct.PublicKey.html

Basically, a prefix should be determined and the relevant conversion process should be performed in this way. this seems a bit over my head. but for the example below, the prefix to use is cosmosvalcons

Example pubkey:

"consensus_pubkey".
{
    "consensus_pubkey": {
      "@type": "/cosmos.crypto.ed25519.PubKey",
      "key": "bDO9bUrbyg0f1pTpmjjZU5cgsweCWdwL6HUVnsKJi7k="
    }
}

I need to get an address with cosmosvalcons... prefixed from pubkey, but all I get is nothing.

1

There are 1 best solutions below

0
On

I was struggling to convert pub key to consensus address on Axelar ecosystem but I found a solution. Here is the solution:

import { sha256 } from "@cosmjs/crypto"; 
import { toBech32, fromBase64 } from "@cosmjs/encoding";


const pubKey = {
  consensus_pubkey: {
    "@type": "/cosmos.crypto.ed25519.PubKey",
    key: "ijzDoMl+TKz06uaK5H+V3IgpuvPjqeAyc/HMW4wgsy8=",
  },
};


const ed25519PubkeyRaw = fromBase64(pubKey.consensus_pubkey.key);
const addressData = sha256(ed25519PubkeyRaw).slice(0, 20);
const bech32Address = toBech32("axelarvalcons", addressData);
logger.info(bech32Address);