From 12249c460af4955a24fbe47c14a84b7365506293 Mon Sep 17 00:00:00 2001 From: Sergey Shulepov Date: Wed, 24 Nov 2021 18:38:28 +0000 Subject: [PATCH] pvf-precheck: Add `sign` in subsystem-util Right now, most of operations that sign stuff in polkadot protocol are handled by a very convenient tool - `Signed`. However `Signed` assumes that whatever is signed is anchored to some `parent_hash` which works for most cases, but does not work for others. One instance of such a case is pre-checking (#3211). There validators submit signed votes on-chain. A vote is valid for the entire session. If we were to use `Signed` we would have to root a vote in some block of that session and during vote verification check that this block is indeed within the session. This is especially annoying since we agreed to use unsigned extrinsics to submit votes and we need to make the unsigned extrinsic validation as slim as possible. (FWIW, the definition of a pre-checking vote can be seen in the next diff in the stack) That's the reason why we opted-out from using `Signed` for pre-checking and decided to go with the manual signing approach. Almost every piece of machinery is in place except for signing which is presented in this PR. --- node/subsystem-util/src/lib.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/node/subsystem-util/src/lib.rs b/node/subsystem-util/src/lib.rs index 85201bce2e57..c0e59b1ea20e 100644 --- a/node/subsystem-util/src/lib.rs +++ b/node/subsystem-util/src/lib.rs @@ -53,7 +53,7 @@ use polkadot_primitives::v1::{ AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, EncodeAs, GroupIndex, GroupRotationInfo, Hash, Id as ParaId, OccupiedCoreAssumption, PersistedValidationData, SessionIndex, SessionInfo, Signed, SigningContext, ValidationCode, - ValidationCodeHash, ValidatorId, ValidatorIndex, + ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, }; use sp_application_crypto::AppKey; use sp_core::{traits::SpawnNamed, Public}; @@ -237,6 +237,27 @@ pub async fn signing_key_and_index( None } +/// Sign the given data with the given validator ID. +/// +/// Returns `Ok(None)` if the private key that correponds to that validator ID is not found in the +/// given keystore. Returns an error if the key could not be used for signing. +pub async fn sign( + keystore: &SyncCryptoStorePtr, + key: &ValidatorId, + data: &[u8], +) -> Result, KeystoreError> { + use std::convert::TryInto; + + let signature = + CryptoStore::sign_with(&**keystore, ValidatorId::ID, &key.into(), &data).await?; + + match signature { + Some(sig) => + Ok(Some(sig.try_into().map_err(|_| KeystoreError::KeyNotSupported(ValidatorId::ID))?)), + None => Ok(None), + } +} + /// Find the validator group the given validator index belongs to. pub fn find_validator_group( groups: &[Vec],