All files / src subscribe-data-packages.ts

95.78% Statements 91/95
92.59% Branches 25/27
94.11% Functions 16/17
95.78% Lines 91/95

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 3421x 1x       1x 1x 1x         1x                                                                                                                                         1x 20x 20x         20x 20x     20x 20x   20x 1x         19x 1x         18x 25x 66x                               2x       2x 12x 1x     1x   1x 1x     1x 1x 1x               18x           18x   18x     47x 47x       47x   7x           18x                 47x       46x 46x     46x 1x       45x 45x     45x 1x           44x 3x           41x   41x 17x     41x   49x     1x         40x       40x   40x   40x 7x     7x     33x 17x       17x 17x                   40x   43x                 33x 33x 56x 15x   41x                     24x   12x   12x       12x 12x     12x   12x                 12x   12x 16x       2x     14x 36x       14x 14x     12x       12x 12x 12x          
import { Mqtt5Client, MqttTopics } from "@redstone-finance/mqtt5-client";
import {
  SignedDataPackage,
  SignedDataPackagePlainObj,
} from "@redstone-finance/protocol";
import { loggerFactory, RedstoneCommon } from "@redstone-finance/utils";
import { pickDataFeedPackagesClosestToMedian } from "./pick-closest-to-median";
import {
  DataPackagesResponse,
  SignedDataPackageSchema,
} from "./request-data-packages";
 
const MAX_DELAY = RedstoneCommon.minToMs(3);
 
/**
 * defines behavior of {@link DataPackageSubscriber}
 */
export type DataPackageSubscriberParams = {
  /**
   * for production environment most of the time "redstone-primary-prod" is appropriate
   */
  dataServiceId: string;
  /**
   * array of tokens to fetch
   */
  dataPackageIds: string[];
  /**
   * ensure minimum number of signers for each token - throws if there are less signers for any token
   */
  uniqueSignersCount: number;
 
  /**
   * has to be >= uniqueSignersCount
   * specify minimal number of signers per package which have to be aggregated before publishing
   */
  minimalOffChainSignersCount: number;
 
  /**
   * time which we will wait for additional packages after minimal requirements are satisfied
   */
  waitMsForOtherSignersAfterMinimalSignersCountSatisfied: number;
 
  /**
   * if set to true, it is enough that minimal requirements are satisfied for single package and all will be published
   */
  ignoreMissingFeeds: boolean;
 
  /**
   * List of signers from which packages will be accepted
   */
  authorizedSigners: string[];
};
 
type SubscriptionCallbackFn = (dataPackages: DataPackagesResponse) => unknown;
 
/**
 * The DataPackageSubscriber class is responsible for aggregation and verification of packages broadcasted via mqtt.
 * The implementation implement MUST implements all checks from {@link requestDataPackages}
 *
 * ## Behavior
 *
 * 1. Validation:
 * - Validates incoming packages against a schema
 * - Verifies signer authorization
 * - Rejects packages with timestamps <= last published timestamp
 * - Prevents duplicate packages from the same signer for a given timestamp
 *
 * 2. Package processing:
 * - Publishes immediately if packages from all signers are received
 * - Schedules delayed publication if `minimalOffChainSignersCount` is met
 * - Uses `ignoreMissingFeeds` to determine if all or some dataPackageIds must meet criteria
 * - It NEVER publishes package with same timestamp or older then last published
 *
 * 3. Package selection:
 * - Employs `pickDataFeedPackagesClosestToMedian` to select `uniqueSignersCount` packages
 *
 * 4. Fallback mechanism (optional)
 * - Triggers if no packages are received within `maxDelayBetweenPublishes`
 * - Fetches packages via `fallbackFn` and publishes if newer than last published
 * - Runs checks at `checkInterval` frequency
 */
export class DataPackageSubscriber {
  topics: string[] = [];
  packagesPerTimestamp = new Map<
    number,
    Record<string, SignedDataPackage[] | undefined>
  >();
  subscribeCallback!: SubscriptionCallbackFn;
  lastPublishedTimestamp: number = Date.now() - MAX_DELAY;
  logger = loggerFactory("data-packages-subscriber");
 
  constructor(
    readonly mqttClient: Mqtt5Client,
    readonly params: DataPackageSubscriberParams
  ) {
    if (params.authorizedSigners.length < params.uniqueSignersCount) {
      throw new Error(
        `Misconfiguration authorizedSigners.length=${params.authorizedSigners.length} has to be >= uniqueSignersCount=${params.uniqueSignersCount}`
      );
    }
 
    if (params.minimalOffChainSignersCount < params.uniqueSignersCount) {
      throw new Error(
        `Misconfiguration uniqueSignersCount=${params.uniqueSignersCount} has to be >=  minimalOffChainSignersCount=${params.minimalOffChainSignersCount}`
      );
    }
 
    for (const dataPackageId of params.dataPackageIds) {
      for (const signer of params.authorizedSigners) {
        this.topics.push(
          MqttTopics.encodeDataPackageTopic({
            dataPackageId,
            dataServiceId: this.params.dataServiceId,
            nodeAddress: signer,
          })
        );
      }
    }
  }
 
  enableFallback(
    fallbackFn: () => Promise<DataPackagesResponse>,
    maxDelayBetweenPublishes: number,
    checkInterval: number
  ) {
    this.logger.info(
      `Enabled fallback mode interval=${checkInterval} maxDelayBetweenPublishes=${maxDelayBetweenPublishes}`
    );
    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    return setInterval(async () => {
      if (Date.now() - this.lastPublishedTimestamp > maxDelayBetweenPublishes) {
        this.logger.warn(
          `Fallback triggered now=${Date.now()} lastPublishedTimestamp=${this.lastPublishedTimestamp}`
        );
        const dataPackages = await fallbackFn();
        const packageTimestamp =
          Object.values(dataPackages)[0]![0].dataPackage.timestampMilliseconds;
        this.logger.debug(
          `Received package from fallbackFn packageTimestamp=${packageTimestamp}`
        );
        if (packageTimestamp > this.lastPublishedTimestamp) {
          this.subscribeCallback(dataPackages);
          this.lastPublishedTimestamp = packageTimestamp;
        }
      }
    }, checkInterval);
  }
 
  async subscribe(subscribeCallback: SubscriptionCallbackFn) {
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    Iif (!subscribeCallback) {
      this.logger.warn(
        "You tried to subscribe twice using same subscriber, aborted this action"
      );
      return;
    }
    this.subscribeCallback = subscribeCallback;
 
    await this.mqttClient.subscribe(
      this.topics,
      (topic, messagePayload, error) => {
        try {
          Iif (error) {
            throw new Error(error);
          }
 
          this.processNewPackage(messagePayload);
        } catch (e) {
          this.logger.error(
            `Failed to process new package error=${RedstoneCommon.stringifyError(e)}`
          );
        }
      }
    );
    this.logger.info("Successfully subscribed to topics", this.topics);
  }
 
  unsubscribe() {
    return this.mqttClient.unsubscribe(this.topics);
  }
 
  private processNewPackage(dataPackageFromMessage: unknown) {
    //schema
    RedstoneCommon.zodAssert<SignedDataPackagePlainObj>(
      SignedDataPackageSchema,
      dataPackageFromMessage
    );
    const signedDataPackage = SignedDataPackage.fromObj(dataPackageFromMessage);
    const packageSigner = signedDataPackage.recoverSignerAddress();
 
    //authorized signer
    if (!this.params.authorizedSigners.includes(packageSigner)) {
      throw new Error("Failed to verify signature");
    }
 
    const packageTimestamp =
      signedDataPackage.dataPackage.timestampMilliseconds;
    const dataPackageId = signedDataPackage.dataPackage.dataPackageId;
 
    // check if dataPackageId is in dataPackagesIds
    if (!this.params.dataPackageIds.includes(dataPackageId)) {
      throw new Error(
        `Received package with unexpected id=${dataPackageId} expectedIds=${this.params.dataPackageIds.join(",")}`
      );
    }
 
    //timestamp
    if (packageTimestamp <= this.lastPublishedTimestamp) {
      throw new Error(
        `Package was rejected because packageTimestamp=${packageTimestamp} < lastPublishedTimestamp=${this.lastPublishedTimestamp}`
      );
    }
 
    const entryForTimestamp =
      this.packagesPerTimestamp.get(packageTimestamp) ?? {};
 
    if (!entryForTimestamp[dataPackageId]) {
      entryForTimestamp[dataPackageId] = [];
    }
 
    if (
      entryForTimestamp[dataPackageId].some(
        (dp) => dp.recoverSignerAddress() === packageSigner
      )
    ) {
      throw new Error(
        `Package was rejected because already have package from signer=${packageSigner} for timestamp=${packageTimestamp}`
      );
    }
 
    this.logger.debug(
      `Received and verified data package from=${packageSigner} timestamp=${packageTimestamp} dataPackageId=${dataPackageId}`
    );
 
    entryForTimestamp[dataPackageId].push(signedDataPackage);
 
    this.packagesPerTimestamp.set(packageTimestamp, entryForTimestamp);
 
    if (this.canBePublishedInstantly(entryForTimestamp)) {
      this.logger.debug(
        `Got packages from all signers timestamp=${packageTimestamp}, will try to publish instantly`
      );
      return this.publish(entryForTimestamp, packageTimestamp);
    }
 
    if (this.canSchedulePublish(entryForTimestamp)) {
      this.logger.debug(
        `Got packages from enough authorized signers timestamp=${packageTimestamp}, will try to publish in ${this.params.waitMsForOtherSignersAfterMinimalSignersCountSatisfied}`
      );
      // this can be scheduled multiple times but this is okey, because lastPublishedTimestamp will protect from publishing multiple times
      setTimeout(
        () => this.publish(entryForTimestamp, packageTimestamp),
        this.params.waitMsForOtherSignersAfterMinimalSignersCountSatisfied
      );
    }
  }
 
  /** Can publish instantly only if have already packages for every data feed from every signer */
  private canBePublishedInstantly(
    entryForTimestamp: Record<string, SignedDataPackage[] | undefined>
  ) {
    return this.params.dataPackageIds.every(
      (dpId) =>
        entryForTimestamp[dpId] &&
        entryForTimestamp[dpId].length === this.params.authorizedSigners.length
    );
  }
 
  /** Check if minimalOffChainSignersCount is satisfied */
  private canSchedulePublish(
    entryForTimestamp: Record<string, SignedDataPackage[] | undefined>
  ) {
    const quantifier = this.params.ignoreMissingFeeds ? "some" : "every";
    return this.params.dataPackageIds[quantifier]((dpId) => {
      if (!entryForTimestamp[dpId]) {
        return false;
      }
      return (
        entryForTimestamp[dpId].length >=
        this.params.minimalOffChainSignersCount
      );
    });
  }
 
  private publish(
    entryForTimestamp: Record<string, SignedDataPackage[] | undefined>,
    packageTimestamp: number
  ) {
    if (packageTimestamp > this.lastPublishedTimestamp) {
      const packagesToPublish: Record<string, SignedDataPackage[]> =
        this.preparePackagesBeforePublish(entryForTimestamp);
 
      this.logger.debug(
        `Publishing packages for timestamp=${packageTimestamp}`
      );
 
      this.subscribeCallback(packagesToPublish);
      this.lastPublishedTimestamp = packageTimestamp;
 
      // clear older then last published timestamp
      this.clearOldData();
    } else {
      this.logger.debug(
        `Not publishing, because proposed packageTimestamp=${packageTimestamp} <= lastPublishedTimestamp=${this.lastPublishedTimestamp}`
      );
    }
  }
 
  private preparePackagesBeforePublish(
    entryForTimestamp: Record<string, SignedDataPackage[] | undefined>
  ) {
    const packagesToPublish: Record<string, SignedDataPackage[]> = {};
 
    for (const [dataPackageId, packages] of Object.entries(entryForTimestamp)) {
      if (
        !packages ||
        packages.length < this.params.minimalOffChainSignersCount
      ) {
        continue;
      }
 
      const potentialPackagesToPublish = pickDataFeedPackagesClosestToMedian(
        packages.map((dp) => dp.toObj()),
        this.params.uniqueSignersCount
      );
 
      if (potentialPackagesToPublish.length >= this.params.uniqueSignersCount) {
        packagesToPublish[dataPackageId] = potentialPackagesToPublish;
      }
    }
    return packagesToPublish;
  }
 
  private clearOldData() {
    for (const timestamp of this.packagesPerTimestamp.keys()) {
      if (timestamp <= this.lastPublishedTimestamp) {
        this.packagesPerTimestamp.delete(timestamp);
      }
    }
  }
}