UNPKG

2.8 kBJavaScriptView Raw
1// Copyright 2017-2023 @polkadot/types authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3
4import { U8aFixed } from '@polkadot/types-codec';
5import { BN, bnToU8a, isNumber, stringToU8a, u8aToHex, u8aToString } from '@polkadot/util';
6export const CID_AURA = stringToU8a('aura');
7export const CID_BABE = stringToU8a('BABE');
8export const CID_GRPA = stringToU8a('FRNK');
9export const CID_POW = stringToU8a('pow_');
10function getAuraAuthor(registry, bytes, sessionValidators) {
11 return sessionValidators[registry.createTypeUnsafe('RawAuraPreDigest', [bytes.toU8a(true)]).slotNumber.mod(new BN(sessionValidators.length)).toNumber()];
12}
13function getBabeAuthor(registry, bytes, sessionValidators) {
14 const digest = registry.createTypeUnsafe('RawBabePreDigestCompat', [bytes.toU8a(true)]);
15 return sessionValidators[digest.value.toNumber()];
16}
17function getBytesAsAuthor(registry, bytes) {
18 return registry.createTypeUnsafe('AccountId', [bytes]);
19}
20
21/**
22 * @name GenericConsensusEngineId
23 * @description
24 * A 4-byte identifier identifying the engine
25 */
26export class GenericConsensusEngineId extends U8aFixed {
27 constructor(registry, value) {
28 super(registry, isNumber(value) ? bnToU8a(value, {
29 isLe: false
30 }) : value, 32);
31 }
32
33 /**
34 * @description `true` if the engine matches aura
35 */
36 get isAura() {
37 return this.eq(CID_AURA);
38 }
39
40 /**
41 * @description `true` is the engine matches babe
42 */
43 get isBabe() {
44 return this.eq(CID_BABE);
45 }
46
47 /**
48 * @description `true` is the engine matches grandpa
49 */
50 get isGrandpa() {
51 return this.eq(CID_GRPA);
52 }
53
54 /**
55 * @description `true` is the engine matches pow
56 */
57 get isPow() {
58 return this.eq(CID_POW);
59 }
60
61 /**
62 * @description From the input bytes, decode into an author
63 */
64 extractAuthor(bytes, sessionValidators) {
65 if (sessionValidators != null && sessionValidators.length) {
66 if (this.isAura) {
67 return getAuraAuthor(this.registry, bytes, sessionValidators);
68 } else if (this.isBabe) {
69 return getBabeAuthor(this.registry, bytes, sessionValidators);
70 }
71 }
72
73 // For pow & Moonbeam, the bytes are the actual author
74 if (this.isPow || bytes.length === 20) {
75 return getBytesAsAuthor(this.registry, bytes);
76 }
77 return undefined;
78 }
79
80 /**
81 * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
82 */
83 toHuman() {
84 return this.toString();
85 }
86
87 /**
88 * @description Returns the base runtime type name for this instance
89 */
90 toRawType() {
91 return 'ConsensusEngineId';
92 }
93
94 /**
95 * @description Override the default toString to return a 4-byte string
96 */
97 toString() {
98 return this.isAscii ? u8aToString(this) : u8aToHex(this);
99 }
100}
\No newline at end of file