3

When I made use of an offchain signed extrinsic to send a transaction to a chain, I copied a snippet from others, which is like this:

use sp_core::crypto::KeyTypeId;
pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"xkey");
pub mod crypto {
    use super::KEY_TYPE;
    use sp_runtime::app_crypto::{app_crypto, sr25519};
    app_crypto!(sr25519, KEY_TYPE);
}
pub type AuthorityId = crypto::Public;

There is a KeyTypeId in the snippet, which is defined by b"xkey". In the runtime code I used this KeyTypeId and it works. But I am not quite sure about what the KeyTypeId means. I just know that the KeyTypeId bounds with a private key which is associated with an account. Who can tell me the background knowledge of all of this?

3 Answers 3

3

The idea by KeyTypeId is to have some unique identifier for a key. This is used for the "application crypto" as we call it in Substrate. Basically that just means that you should use different keys for all your different "services". When you look for example at Polkadot, there we got a key for BABE, Grandpa, im-online and some others. Some of these "services" could share the same key. However that would also mean that if you loose one key, all these services would be "hacked".

To distinguish keys in the keystore between these different services, each of them has a different KeyTypeId. One thing to note is that a KeyTypeId is not a unique identifier for a crypto type. As some services are crypto agnostic, they could use different types of crypto. However, each chain normally only has one fixed crypto per service.

TLDR: KeyTypeIds are used to distinguish different keys in the key store.

1

Here defines some well-known key type ids.

Just like its name. It's the key type's id. Which is used here.

From the algorithm level, key type id is just a 4-bytes-length slice append to the key head.


BTW, here is a minimal re-implementation of the Substrate key type id. It might looks more clearly.

1

KeyTypeId is used in creating an identifier that maps to public keys in your application. The public keys then map to private keys. Essentially, the identifier is a public value that represents the public key of an account.

From your snippet,

pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"xkey");

created a new instance of the KeyTypeId struct with the *b"xkey" value.

The KEY_TYPE identifier was then used to declare an account with the sr25519 signing algorithm using the app_crypto! macro:

app_crypto!(sr25519, KEY_TYPE);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.