git.delta.rocks / unique-network / refs/commits / 59f9c8e9550a

difftreelog

source

tests/src/util/identitySetter.ts8.8 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.03//4// Pulls identities and sub-identities from a chain and then uses sudo to force upload them into another.5// Only changed or previously non-existent data are inserted.6//7// Usage: `yarn setIdentities [relay WS URL] [parachain WS URL] [sudo key]`8// Example: `yarn setIdentities wss://polkadot-rpc.dwellir.com ws://localhost:9944 escape pattern miracle train sudden cart adapt embark wedding alien lamp mesh`910import {encodeAddress} from '@polkadot/keyring';11import {usingPlaygrounds, Pallets} from './index';12import {ChainHelperBase} from './playgrounds/unique';1314const relayUrl = process.argv[2] ?? 'ws://localhost:9844';15const paraUrl = process.argv[3] ?? 'ws://localhost:9944';16const key = process.argv.length > 4 ? process.argv.slice(4).join(' ') : '//Alice';1718export function extractAccountId(key: any): string {19  return (key as any).toHuman()[0];20}2122export function extractIdentityInfo(value: any): object {23  const heart = (value as any).unwrap();24  const identity = heart.toJSON();25  identity.judgements = heart.judgements.toHuman();26  return identity;27}2829export function extractIdentity(key: any, value: any): [string, any] {30  return [extractAccountId(key), extractIdentityInfo(value)];31}3233export async function getIdentities(helper: ChainHelperBase, noneCasePredicate?: (key: any, value: any) => void) {34  const identities: [string, any][] = [];35  for(const [key, v] of await helper.getApi().query.identity.identityOf.entries()) {36    const value = v as any;37    if (value.isNone) {38      if (noneCasePredicate) noneCasePredicate(key, value);39      continue;40    }41    identities.push(extractIdentity(key, value));42  }43  return identities;44}4546// whether the existing chain data is more important than the coming47function isCurrentChainDataPriority(helper: ChainHelperBase, currentChainId: number | undefined, relayChainId: number) {48  if (!currentChainId) return false;49  // information has come from local chain, and is automatically superior50  if (currentChainId == helper.chain.getChainProperties().ss58Format) return true;51  // the lower the id, the more important it is (Polkadot has ss58 prefix = 0, Kusama has ss58 prefix = 2)52  return currentChainId < relayChainId;53}5455// construct an object with all data necessary for insertion from storage query results56export function constructSubInfo(identityAccount: string, subQuery: any, supers: any[], ss58?: number): [string, any] {57  const deposit = subQuery.toJSON()[0];58  const subIdentities = subQuery.toHuman()[1];59  subIdentities.map((sub: string) => supers.find((sup: any) => sup[0] === sub));6061  return [62    encodeAddress(identityAccount, ss58), [63      deposit,64      subIdentities.map((sub: string): [string, object] | null => {65        const sup = supers.find((sup: any) => sup[0] === sub);66        if (!sup) {67          console.error(`Error: Could not find info on super for \nsub-identity account\t${sub} of \nsuper account \t\t${identityAccount}, skipping.`);68          return null;69        }70        return [encodeAddress(sub, ss58), sup[1].toJSON()[1]];71      }).filter((x: any) => x),72    ],73  ];74}7576export async function getSubs(helper: ChainHelperBase) {77  return (await helper.getApi().query.identity.subsOf.entries()).map(([key, value]) => [extractAccountId(key), value as any]);78}7980export async function getSupers(helper: ChainHelperBase) {81  return (await helper.getApi().query.identity.superOf.entries()).map(([key, value]) => [extractAccountId(key), value as any]);82}8384// The utility for pulling identity and sub-identity data85const forceInsertIdentities = async (): Promise<void> => {86  let relaySS58Prefix = 0;87  const identitiesOnRelay: any[] = [];88  const subsOnRelay: any[] = [];89  const identitiesToRemove: string[] = [];90  await usingPlaygrounds(async helper => {91    try {92      relaySS58Prefix = helper.chain.getChainProperties().ss58Format;93      // iterate over every identity94      for(const [key, value] of await getIdentities(helper, (key, _value) => identitiesToRemove.push((key as any).toHuman()[0]))) {95        // if any of the judgements resulted in a good confirmed outcome, keep this identity96        let knownGood = false, reasonable = false;97        for (const [_id, judgement] of value.judgements) {98          if (judgement == 'KnownGood') knownGood = true;99          if (judgement == 'Reasonable') reasonable = true;100        }101        if (!(reasonable || knownGood)) continue;102        // replace the registrator id with the relay chain's ss58 format103        value.judgements = [[helper.chain.getChainProperties().ss58Format, knownGood ? 'KnownGood' : 'Reasonable']];104        identitiesOnRelay.push([key, value]);105      }106107      const sublessIdentities = [...identitiesOnRelay];108      const supersOfSubs = await getSupers(helper);109110      // iterate over every sub-identity111      for(const [key, value] of await getSubs(helper)) {112        // only get subs of the identities interesting to us113        const identityIndex = sublessIdentities.findIndex((x: any) => x[0] == key);114        if (identityIndex == -1) continue;115        sublessIdentities.splice(identityIndex, 1);116        subsOnRelay.push(constructSubInfo(key, value, supersOfSubs));117      }118119      // mark the rest of sub-identities for deletion with empty arrays120      /*for(const [account, _identity] of sublessIdentities) {121        subsOnRelay.push([account, ['0', []]]);122      }*/123    } catch (error) {124      console.error(error);125      throw Error('Error during fetching identities');126    }127  }, relayUrl);128129  await usingPlaygrounds(async (helper, privateKey) => {130    if (helper.fetchMissingPalletNames([Pallets.Identity]).length != 0) console.error('pallet-identity is not included in parachain.');131    try {132      const superuser = await privateKey(key);133      const ss58Format = helper.chain.getChainProperties().ss58Format;134      const paraIdentities = await getIdentities(helper);135      const identitiesToAdd: any[] = [];136      const paraAccountsRegistrators: {[name: string]: number} = {};137138      // cross-reference every account for changes139      for (const [key, value] of identitiesOnRelay) {140        const encodedKey = encodeAddress(key, ss58Format);141142        // only update if the identity info does not exist or is changed143        const identity = paraIdentities.find(i => i[0] === encodedKey);144        if (identity) {145          const registratorId = identity[1].judgements[0][0];146          paraAccountsRegistrators[encodedKey] = registratorId;147          if (isCurrentChainDataPriority(helper, registratorId, value.judgements[0][0])148            || JSON.stringify(value.info) === JSON.stringify(identity[1].info)) {149            continue;150          }151        }152153        identitiesToAdd.push([key, value]);154        // exercise caution - in case we have an identity and the realy doesn't, it might mean one of two things:155        // 1) it was deleted on the relay;156        // 2) it is our own identity, we don't want to delete it.157        // identitiesToRemove.push((key as any).toHuman()[0]);158      }159160      if (identitiesToRemove.length != 0)161        await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceRemoveIdentities', [identitiesToRemove]);162      if (identitiesToAdd.length != 0)163        await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identitiesToAdd]);164165      console.log(`Tried to upload ${identitiesToAdd.length} identities`166        + ` and found ${identitiesToRemove.length} identities for potential removal.`167        + ` Now there are ${(await helper.getApi().query.identity.identityOf.keys()).length}.`);168169      // fill sub-identities170      const paraSubs = await getSubs(helper);171      const supersOfSubs = await getSupers(helper);172      const subsToUpdate: any[] = [];173174      for (const [key, value] of subsOnRelay) {175        const encodedKey = encodeAddress(key, ss58Format);176        const sub = paraSubs.find(i => i[0] === encodedKey);177        if (sub) {178          // only update if the sub-identity info does not exist or is changed179          if (isCurrentChainDataPriority(helper, paraAccountsRegistrators[encodedKey], relaySS58Prefix)180            || JSON.stringify(value) === JSON.stringify(constructSubInfo(sub[0], sub[1], supersOfSubs)[1])) {181            continue;182          }183        } else if (value[1].length == 0)184          continue;185186        subsToUpdate.push([key, value]);187      }188189      if (subsToUpdate.length != 0)190        await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsToUpdate]);191192      console.log(`Also tried to update ${subsToUpdate.length} identities with their sub-identities.`193        + ` Now there are ${(await helper.getApi().query.identity.subsOf.keys()).length} identities with subs.`);194    } catch (error) {195      console.error(error);196      throw Error('Error during setting identities');197    }198  }, paraUrl);199};200201if (process.argv[1] === module.filename)202  forceInsertIdentities().catch(() => process.exit(1));