All files / lib/messages OracleEvent.ts

84.93% Statements 62/73
59.46% Branches 22/37
71.43% Functions 10/14
84.72% Lines 61/72

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 2511x   1x 1x   1x                                             1x 1x               163x     163x 163x 946x     163x       163x       163x   163x               257x 257x   257x 257x 257x   257x 1591x     257x 257x 257x 257x 257x   257x           474x         474x                                     16x 1x       15x         15x 1x     14x 80x           14x   14x 1x           13x 3x                   14x   10x 4x       4x 4x                                                                                               86x 482x                     694x 694x   694x 694x   694x 4060x     694x 694x 694x 694x   694x 694x   694x                          
import { BufferReader, BufferWriter } from '@node-dlc/bufio';
 
import { MessageType } from '../MessageType';
import { getTlv } from '../serialize/getTlv';
import { IDlcMessage } from './DlcMessage';
import {
  DigitDecompositionEventDescriptor,
  EnumEventDescriptor,
  EventDescriptor,
  IDigitDecompositionEventDescriptorJSON,
  IEnumEventDescriptorJSON,
} from './EventDescriptor';
 
/**
 * Oracle event containing information about an event and the way that the
 * oracle will attest to it. Updated to be rust-dlc compliant.
 *
 * For users to be able to create DLCs based on a given event, they also
 * need to obtain information about the oracle and the time at which it
 * plans on releasing a signature over the event outcome. OracleEvent
 * messages contain such information, which includes:
 *   - the nonce(s) that will be used to sign the event outcome(s)
 *   - the earliest time (UTC) at which it plans on releasing a signature
 *     over the event outcome, in epoch seconds
 *   - the event descriptor
 *   - the event ID which can be a name or categorization associated with
 *     the event by the oracle
 */
export class OracleEvent implements IDlcMessage {
  public static type = MessageType.OracleEvent;
 
  /**
   * Creates an OracleEvent from JSON data
   * @param json JSON object representing oracle event
   */
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
  public static fromJSON(json: any): OracleEvent {
    const instance = new OracleEvent();
 
    // Parse oracle nonces array
    const nonces = json.oracleNonces || json.oracle_nonces || [];
    instance.oracleNonces = nonces.map((nonce: string) =>
      Buffer.from(nonce, 'hex'),
    );
 
    instance.eventMaturityEpoch =
      json.eventMaturityEpoch || json.event_maturity_epoch || 0;
 
    // Parse event descriptor
    instance.eventDescriptor = EventDescriptor.fromJSON(
      json.eventDescriptor || json.event_descriptor,
    );
 
    instance.eventId = json.eventId || json.event_id || '';
 
    return instance;
  }
 
  /**
   * Deserializes an oracle_event message
   * @param buf
   */
  public static deserialize(buf: Buffer): OracleEvent {
    const instance = new OracleEvent();
    const reader = new BufferReader(buf);
 
    reader.readBigSize(); // read type
    instance.length = reader.readBigSize();
    const nonceCount = reader.readUInt16BE();
 
    for (let i = 0; i < nonceCount; i++) {
      instance.oracleNonces.push(reader.readBytes(32));
    }
 
    instance.eventMaturityEpoch = reader.readUInt32BE();
    instance.eventDescriptor = EventDescriptor.deserialize(getTlv(reader));
    const eventIdLength = reader.readBigSize();
    const eventIdBuf = reader.readBytes(Number(eventIdLength));
    instance.eventId = eventIdBuf.toString();
 
    return instance;
  }
 
  /**
   * The type for oracle_event message. oracle_event = 55330
   */
  public type = OracleEvent.type;
 
  public length: bigint;
 
  /** The nonces that the oracle will use to attest to the event outcome. */
  public oracleNonces: Buffer[] = [];
 
  /** The expected maturity of the contract (Unix timestamp). */
  public eventMaturityEpoch: number;
 
  /** The description of the event. */
  public eventDescriptor: EventDescriptor;
 
  /** The ID of the event. */
  public eventId: string;
 
  /**
   * Validates correctness of all fields in the message according to rust-dlc specification.
   * This includes validating that the number of nonces matches the expected count for the event type.
   * https://github.com/discreetlogcontracts/dlcspecs/blob/master/Oracle.md
   * @throws Will throw an error if validation fails
   */
  public validate(): void {
    // Validate event maturity epoch
    if (this.eventMaturityEpoch < 0) {
      throw new Error('eventMaturityEpoch must be greater than or equal to 0');
    }
 
    // Validate event ID
    Iif (!this.eventId || this.eventId.length === 0) {
      throw new Error('eventId cannot be empty');
    }
 
    // Validate oracle nonces (must be 32 bytes each)
    if (this.oracleNonces.length === 0) {
      throw new Error('Must have at least one oracle nonce');
    }
 
    this.oracleNonces.forEach((nonce, index) => {
      Iif (!nonce || nonce.length !== 32) {
        throw new Error(`Oracle nonce at index ${index} must be 32 bytes`);
      }
    });
 
    // Validate expected number of nonces based on event descriptor type
    const expectedNbNonces = this.getExpectedNonceCount();
 
    if (expectedNbNonces !== this.oracleNonces.length) {
      throw new Error(
        `OracleEvent nonce count mismatch: expected ${expectedNbNonces}, got ${this.oracleNonces.length}`,
      );
    }
 
    // Validate the event descriptor itself
    if (this.eventDescriptor instanceof DigitDecompositionEventDescriptor) {
      this.eventDescriptor.validate();
    }
    // EnumEventDescriptorV0 doesn't have validation requirements beyond basic structure
  }
 
  /**
   * Returns the expected number of nonces based on the event descriptor type.
   * This matches the rust-dlc validation logic.
   */
  private getExpectedNonceCount(): number {
    if (this.eventDescriptor instanceof EnumEventDescriptor) {
      // Enum events require exactly 1 nonce
      return 1;
    } else Eif (
      this.eventDescriptor instanceof DigitDecompositionEventDescriptor
    ) {
      // Digit decomposition events require nbDigits nonces, plus 1 if signed
      const descriptor = this.eventDescriptor;
      return descriptor.isSigned
        ? descriptor.nbDigits + 1
        : descriptor.nbDigits;
    } else {
      throw new Error('Unknown event descriptor type');
    }
  }
 
  /**
   * Returns whether this event is for enumerated outcomes.
   */
  public isEnumEvent(): boolean {
    return this.eventDescriptor instanceof EnumEventDescriptor;
  }
 
  /**
   * Returns whether this event is for numerical outcomes.
   */
  public isDigitDecompositionEvent(): boolean {
    return this.eventDescriptor instanceof DigitDecompositionEventDescriptor;
  }
 
  /**
   * Returns the event descriptor as EnumEventDescriptor if it's an enum event.
   * @throws Error if not an enum event
   */
  public getEnumEventDescriptor(): EnumEventDescriptor {
    if (!this.isEnumEvent()) {
      throw new Error('Event is not an enum event');
    }
    return this.eventDescriptor as EnumEventDescriptor;
  }
 
  /**
   * Returns the event descriptor as DigitDecompositionEventDescriptor if it's a numerical event.
   * @throws Error if not a numerical event
   */
  public getDigitDecompositionEventDescriptor(): DigitDecompositionEventDescriptor {
    if (!this.isDigitDecompositionEvent()) {
      throw new Error('Event is not a digit decomposition event');
    }
    return this.eventDescriptor as DigitDecompositionEventDescriptor;
  }
 
  /**
   * Converts oracle_event to JSON
   */
  public toJSON(): IOracleEventJSON {
    return {
      oracleNonces: this.oracleNonces.map((oracle) => oracle.toString('hex')),
      eventMaturityEpoch: this.eventMaturityEpoch,
      eventDescriptor: this.eventDescriptor.toJSON(),
      eventId: this.eventId,
    };
  }
 
  /**
   * Serializes the oracle_event message into a Buffer
   */
  public serialize(): Buffer {
    const writer = new BufferWriter();
    writer.writeBigSize(this.type);
 
    const dataWriter = new BufferWriter();
    dataWriter.writeUInt16BE(this.oracleNonces.length);
 
    for (const nonce of this.oracleNonces) {
      dataWriter.writeBytes(nonce);
    }
 
    dataWriter.writeUInt32BE(this.eventMaturityEpoch);
    dataWriter.writeBytes(this.eventDescriptor.serialize());
    dataWriter.writeBigSize(this.eventId.length);
    dataWriter.writeBytes(Buffer.from(this.eventId));
 
    writer.writeBigSize(dataWriter.size);
    writer.writeBytes(dataWriter.toBuffer());
 
    return writer.toBuffer();
  }
}
 
export interface IOracleEventJSON {
  type?: number; // Made optional for rust-dlc compatibility
  oracleNonces: string[];
  eventMaturityEpoch: number;
  eventDescriptor:
    | IEnumEventDescriptorJSON
    | IDigitDecompositionEventDescriptorJSON;
  eventId: string;
}