UNPKG

lotus-sdk

Version:

Central repository for several classes of tools for integrating with, and building for, the Lotusia ecosystem

53 lines (52 loc) 2.41 kB
import { MessageChannel, MessageAuthority, getMessageChannelConfig, } from './message-channels.js'; export { MessageChannel, MessageAuthority } from './message-channels.js'; export class ChannelViolationError extends Error { constructor(messageType, expectedChannel, actualChannel) { super(`Channel violation: ${messageType} received on ${actualChannel}, expected ${expectedChannel}`); this.name = 'ChannelViolationError'; } } export class AuthorityViolationError extends Error { constructor(messageType, requiredAuthority, senderPeerId) { super(`Authority violation: ${messageType} requires ${requiredAuthority} authority, sent by ${senderPeerId}`); this.name = 'AuthorityViolationError'; } } export class MessageValidator { validateChannel(messageType, sourceChannel) { const config = getMessageChannelConfig(messageType); if (config.channel !== sourceChannel) { throw new ChannelViolationError(messageType, config.channel, sourceChannel); } } validateAuthority(messageType, senderPeerId, coordinatorPeerId) { const config = getMessageChannelConfig(messageType); if (config.authority === MessageAuthority.ANY) { return; } if (config.authority === MessageAuthority.COORDINATOR && coordinatorPeerId) { if (senderPeerId !== coordinatorPeerId) { throw new AuthorityViolationError(messageType, MessageAuthority.COORDINATOR, senderPeerId); } } if (config.authority === MessageAuthority.PARTICIPANT && coordinatorPeerId && senderPeerId === coordinatorPeerId) { throw new AuthorityViolationError(messageType, MessageAuthority.PARTICIPANT, senderPeerId); } } validateMessage(messageType, sourceChannel, senderPeerId, coordinatorPeerId) { this.validateChannel(messageType, sourceChannel); this.validateAuthority(messageType, senderPeerId, coordinatorPeerId); } shouldUseDirect(messageType) { return (getMessageChannelConfig(messageType).channel === MessageChannel.DIRECT); } shouldUseGossipSub(messageType) { return (getMessageChannelConfig(messageType).channel === MessageChannel.GOSSIPSUB); } getRequiredChannel(messageType) { return getMessageChannelConfig(messageType).channel; } }