UNPKG

3.16 kBJavaScriptView Raw
1import { U8aFixed } from '@polkadot/types-codec';
2import { BN, bnToU8a, isNumber, stringToU8a, u8aToHex, u8aToString } from '@polkadot/util';
3export const CID_AURA = /*#__PURE__*/ stringToU8a('aura');
4export const CID_BABE = /*#__PURE__*/ stringToU8a('BABE');
5export const CID_GRPA = /*#__PURE__*/ stringToU8a('FRNK');
6export const CID_POW = /*#__PURE__*/ stringToU8a('pow_');
7export const CID_NMBS = /*#__PURE__*/ stringToU8a('nmbs');
8function getAuraAuthor(registry, bytes, sessionValidators) {
9 return sessionValidators[registry.createTypeUnsafe('RawAuraPreDigest', [bytes.toU8a(true)])
10 .slotNumber
11 .mod(new BN(sessionValidators.length))
12 .toNumber()];
13}
14function getBabeAuthor(registry, bytes, sessionValidators) {
15 const digest = registry.createTypeUnsafe('RawBabePreDigestCompat', [bytes.toU8a(true)]);
16 return sessionValidators[digest.value.toNumber()];
17}
18function getBytesAsAuthor(registry, bytes) {
19 return registry.createTypeUnsafe('AccountId', [bytes]);
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)
29 ? bnToU8a(value, { isLe: false })
30 : value, 32);
31 }
32 /**
33 * @description `true` if the engine matches aura
34 */
35 get isAura() {
36 return this.eq(CID_AURA);
37 }
38 /**
39 * @description `true` is the engine matches babe
40 */
41 get isBabe() {
42 return this.eq(CID_BABE);
43 }
44 /**
45 * @description `true` is the engine matches grandpa
46 */
47 get isGrandpa() {
48 return this.eq(CID_GRPA);
49 }
50 /**
51 * @description `true` is the engine matches pow
52 */
53 get isPow() {
54 return this.eq(CID_POW);
55 }
56 /**
57 * @description `true` is the engine matches nimbus
58 */
59 get isNimbus() {
60 return this.eq(CID_NMBS);
61 }
62 /**
63 * @description From the input bytes, decode into an author
64 */
65 extractAuthor(bytes, sessionValidators) {
66 if (sessionValidators?.length) {
67 if (this.isAura) {
68 return getAuraAuthor(this.registry, bytes, sessionValidators);
69 }
70 else if (this.isBabe) {
71 return getBabeAuthor(this.registry, bytes, sessionValidators);
72 }
73 }
74 // For pow & Nimbus, the bytes are the actual author
75 if (this.isPow || this.isNimbus) {
76 return getBytesAsAuthor(this.registry, bytes);
77 }
78 return undefined;
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 * @description Returns the base runtime type name for this instance
88 */
89 toRawType() {
90 return 'ConsensusEngineId';
91 }
92 /**
93 * @description Override the default toString to return a 4-byte string
94 */
95 toString() {
96 return this.isAscii
97 ? u8aToString(this)
98 : u8aToHex(this);
99 }
100}