Detect Keys, inject SessionKeys (#3380)

This commit is contained in:
Jaco Greeff
2021-04-08 14:07:39 +02:00
committed by GitHub
parent 43e87603e2
commit ed5f2673ce
5 changed files with 141 additions and 27 deletions
+86 -19
View File
@@ -2,15 +2,18 @@
// SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { bool } from '@polkadot/types';
import type { bool, Raw } from '@polkadot/types';
import type { Releases } from '@polkadot/types/interfaces';
import type { InterfaceTypes } from '@polkadot/types/types';
import { assert, compactFromU8a } from '@polkadot/util';
import { combineLatest, Observable, of } from '@polkadot/x-rxjs';
import { map, take } from '@polkadot/x-rxjs/operators';
// the order and types needs to map with the all array setup below
type Extracted = [bool | null, bool | null, bool | null, Releases | null];
type ExtractedQ = [bool | null, bool | null, bool | null, Releases | null];
type ExtractedR = [Raw | null];
type DetectedKeys = keyof Pick<InterfaceTypes, 'AccountInfo' | 'ValidatorPrefs'>;
@@ -18,11 +21,21 @@ type DetectedValues = keyof InterfaceTypes;
interface DetectedTypes extends Record<DetectedKeys, DetectedValues> {
AccountInfo: 'AccountInfoWithRefCount' | 'AccountInfoWithDualRefCount' | 'AccountInfoWithTripleRefCount',
Keys: 'SessionKeys1' | 'SessionKeys2' | 'SessionKeys3' | 'SessionKeys4' | 'SessionKeys5' | 'SessionKeys6' | 'SessionKeys7' | 'SessionKeys8' | 'SessionKeys9' | 'SessionKeys10';
RefCount: 'u8' | 'u32',
ValidatorPrefs: 'ValidatorPrefsWithBlocked' | 'ValidatorPrefsWithCommission';
}
function mapCapabilities ([systemRefcount32, systemRefcountDual, systemRefcountTriple, stakingVersion]: Extracted): Partial<DetectedTypes> {
interface AvailableMap<T> {
filtered: T[];
included: boolean[];
}
interface Constants {
accountIdLength: number;
}
function mapCapabilities ({ accountIdLength }: Constants, [systemRefcount32, systemRefcountDual, systemRefcountTriple, stakingVersion]: ExtractedQ, [keys]: ExtractedR): Partial<DetectedTypes> {
const types: Partial<DetectedTypes> = {};
// AccountInfo
@@ -47,36 +60,90 @@ function mapCapabilities ([systemRefcount32, systemRefcountDual, systemRefcountT
}
}
// Keys
if (keys) {
try {
const [offset, numItems] = compactFromU8a(keys);
const tupleLength = (keys.length - offset) / numItems.toNumber();
const numIds = tupleLength / accountIdLength;
const numIdsRound = Math.floor(numIds);
assert(numIds >= 2 && numIds <= 11, `Detected ${numIds} in Keys, should be >= 2 and <= 11`);
if (numIdsRound !== numIds) {
// Beefy?
if ((((numIdsRound - 1) * accountIdLength) + 33) === tupleLength) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
types.Keys = `SessionKeys${numIdsRound - 1}B`;
} else {
assert(false, `Expected integer number of keys, found ${numIds.toFixed(2)}`);
}
} else {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
types.Keys = `SessionKeys${numIds - 1}`;
}
} catch (error) {
console.error(error);
}
}
return types;
}
function filterEntries <T> (entries: T[]): AvailableMap<T> {
const included = entries.map((c) => !!c);
const filtered = entries.filter((_, index) => included[index]);
return { filtered, included };
}
function extractResults <R, T = unknown> (results: unknown[], map: AvailableMap<T>): R {
let offset = -1;
return map.included.map((isIncluded) =>
isIncluded
? results[++offset]
: null
) as unknown as R;
}
/**
* @description Query the chain for the specific capabilities
*/
export function detectedCapabilities (api: ApiInterfaceRx, blockHash?: Uint8Array | string | undefined): Observable<Partial<DetectedTypes>> {
const all = [
const queries = filterEntries([
api.query.system?.upgradedToU32RefCount,
api.query.system?.upgradedToDualRefCount,
api.query.system?.upgradedToTripleRefCount,
api.query.staking?.storageVersion
];
const included = all.map((c) => !!c);
const filtered = all.filter((_, index) => included[index]);
]);
const keyed = filterEntries([
api.query.session?.queuedKeys
]);
return (
filtered.length
return combineLatest([
queries.filtered.length
? blockHash
? combineLatest(filtered.map((c) => c.at(blockHash)))
: api.queryMulti(filtered)
? combineLatest(queries.filtered.map((c) => c.at(blockHash)))
: api.queryMulti(queries.filtered)
: of([]),
keyed.filtered.length
? blockHash
? combineLatest(keyed.filtered.map((k) => api.rpc.state.getStorage.raw(k.key(), blockHash)))
: combineLatest(keyed.filtered.map((k) => api.rpc.state.getStorage.raw(k.key())))
: of([])
).pipe(
map((results): Partial<DetectedTypes> => {
let offset = -1;
return mapCapabilities(
included.map((isIncluded) => isIncluded ? results[++offset] : null) as Extracted
);
}),
]).pipe(
map(([qResults, rResults]): Partial<DetectedTypes> =>
mapCapabilities(
{
accountIdLength: api.registry.createType('AccountId').encodedLength
},
extractResults<ExtractedQ>(qResults, queries),
extractResults<ExtractedR>(rResults, keyed)
)
),
take(1)
);
}