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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 6x 6x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x | import { BufferReader, BufferWriter } from '@node-dlc/bufio';
import { IOrderMetadataJSON } from '..';
import { MessageType, PROTOCOL_VERSION } from '../MessageType';
import { deserializeTlv } from '../serialize/deserializeTlv';
import { getTlv } from '../serialize/getTlv';
import { bigIntToNumber, toBigInt } from '../util';
import { BatchFundingGroup, IBatchFundingGroupJSON } from './BatchFundingGroup';
import {
ContractInfo,
IContractInfoV0JSON,
IContractInfoV1JSON,
} from './ContractInfo';
import { IDlcMessage } from './DlcMessage';
import {
IOrderIrcInfoJSON,
OrderIrcInfo,
OrderIrcInfoV0,
} from './OrderIrcInfo';
import { OrderMetadata, OrderMetadataV0 } from './OrderMetadata';
import { IOrderPositionInfoJSON, OrderPositionInfo } from './OrderPositionInfo';
const LOCKTIME_THRESHOLD = 500000000;
/**
* OrderOffer message contains information about a node and indicates its
* desire to enter into a new contract. This is the first step toward
* order negotiation. This is a simpler message than DlcOffer.
*/
export class OrderOffer implements IDlcMessage {
public static type = MessageType.OrderOffer;
/**
* Creates an OrderOffer from JSON data
* @param json JSON object representing an order offer
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
public static fromJSON(json: any): OrderOffer {
const instance = new OrderOffer();
// Basic fields with field name variations
instance.protocolVersion =
json.protocolVersion || json.protocol_version || PROTOCOL_VERSION;
instance.contractFlags = Buffer.from(
json.contractFlags || json.contract_flags || '00',
'hex',
);
instance.chainHash = Buffer.from(json.chainHash || json.chain_hash, 'hex');
instance.temporaryContractId = Buffer.from(
json.temporaryContractId || json.temporary_contract_id,
'hex',
);
// Use toBigInt helper to handle BigInt values from json-bigint
instance.offerCollateral = toBigInt(
json.offerCollateral ||
json.offerCollateralSatoshis ||
json.offer_collateral,
);
instance.feeRatePerVb = toBigInt(json.feeRatePerVb || json.fee_rate_per_vb);
instance.cetLocktime = json.cetLocktime || json.cet_locktime || 0;
instance.refundLocktime = json.refundLocktime || json.refund_locktime || 0;
// Use ContractInfo.fromJSON() - proper delegation
instance.contractInfo = ContractInfo.fromJSON(
json.contractInfo || json.contract_info,
);
return instance;
}
/**
* Deserializes an order_offer message
* @param buf
*/
public static deserialize(buf: Buffer): OrderOffer {
const instance = new OrderOffer();
const reader = new BufferReader(buf);
const type = reader.readUInt16BE(); // read type
// Validate type matches expected OrderOffer type
Iif (type !== MessageType.OrderOffer) {
throw new Error(
`Invalid message type. Expected ${MessageType.OrderOffer}, got ${type}`,
);
}
// BACKWARD COMPATIBILITY: Detect old vs new format
const nextBytes = reader.buffer.subarray(
reader.position,
reader.position + 5,
);
const possibleProtocolVersion = nextBytes.readUInt32BE(0);
const possibleContractFlags = nextBytes.readUInt8(4);
// Heuristic: protocol_version should be 1, contract_flags should be 0
const isNewFormat =
possibleProtocolVersion >= 1 &&
possibleProtocolVersion <= 10 &&
possibleContractFlags === 0;
Eif (isNewFormat) {
// New format with protocol_version
instance.protocolVersion = reader.readUInt32BE();
instance.contractFlags = reader.readBytes(1);
} else {
// Old format without protocol_version
instance.protocolVersion = 1; // Default to version 1
instance.contractFlags = reader.readBytes(1);
}
instance.chainHash = reader.readBytes(32);
instance.temporaryContractId = reader.readBytes(32);
// ContractInfo is serialized as sibling type in dlcspecs PR #163 format
instance.contractInfo = ContractInfo.deserialize(
reader.buffer.subarray(reader.position),
);
// Skip past the ContractInfo we just read
const contractInfoLength = instance.contractInfo.serialize().length;
reader.position += contractInfoLength;
instance.offerCollateral = reader.readUInt64BE();
instance.feeRatePerVb = reader.readUInt64BE();
instance.cetLocktime = reader.readUInt32BE();
instance.refundLocktime = reader.readUInt32BE();
// Parse TLV stream as per dlcspecs PR #163
while (!reader.eof) {
const buf = getTlv(reader);
const tlvReader = new BufferReader(buf);
const { type } = deserializeTlv(tlvReader);
switch (Number(type)) {
case MessageType.OrderMetadataV0:
instance.metadata = OrderMetadataV0.deserialize(buf);
break;
case MessageType.OrderIrcInfoV0:
instance.ircInfo = OrderIrcInfoV0.deserialize(buf);
break;
case MessageType.OrderPositionInfo:
instance.positionInfo = OrderPositionInfo.deserialize(buf);
break;
case MessageType.BatchFundingGroup:
if (!instance.batchFundingGroups) {
instance.batchFundingGroups = [];
}
instance.batchFundingGroups.push(BatchFundingGroup.deserialize(buf));
break;
default:
// Store unknown TLVs for future compatibility
if (!instance.unknownTlvs) {
instance.unknownTlvs = [];
}
instance.unknownTlvs.push({ type: Number(type), data: buf });
break;
}
}
return instance;
}
/**
* The type for order_offer message. order_offer = 62770
*/
public type = OrderOffer.type;
// New fields as per dlcspecs PR #163
public protocolVersion: number = PROTOCOL_VERSION; // Default to current protocol version
public temporaryContractId: Buffer; // New field for contract identification
// Existing fields
public contractFlags: Buffer;
public chainHash: Buffer;
public contractInfo: ContractInfo;
public offerCollateral: bigint;
public feeRatePerVb: bigint;
public cetLocktime: number;
public refundLocktime: number;
public metadata?: OrderMetadata;
public ircInfo?: OrderIrcInfo;
public positionInfo?: OrderPositionInfo;
public batchFundingGroups?: BatchFundingGroup[];
// Store unknown TLVs for forward compatibility
public unknownTlvs?: Array<{ type: number; data: Buffer }>;
// Legacy property for backward compatibility
public get offerCollateralSatoshis(): bigint {
return this.offerCollateral;
}
public set offerCollateralSatoshis(value: bigint) {
this.offerCollateral = value;
}
public validate(): void {
// 1. Type is set automatically in class
// 2. protocol_version validation
if (this.protocolVersion !== PROTOCOL_VERSION) {
throw new Error(
`Unsupported protocol version: ${this.protocolVersion}, expected: ${PROTOCOL_VERSION}`,
);
}
// 3. temporary_contract_id validation
if (!this.temporaryContractId || this.temporaryContractId.length !== 32) {
throw new Error('temporaryContractId must be 32 bytes');
}
// 4. contract_flags field is ignored
// 5. chain_hash must be validated as input by end user
// 6. offer_collateral must be greater than or equal to 1000
if (this.offerCollateral < 1000) {
throw new Error('offer_collateral must be greater than or equal to 1000');
}
if (this.cetLocktime < 0) {
throw new Error('cet_locktime must be greater than or equal to 0');
}
if (this.refundLocktime < 0) {
throw new Error('refund_locktime must be greater than or equal to 0');
}
// 7. cet_locktime and refund_locktime must either both be unix timestamps, or both be block heights.
if (
!(
(this.cetLocktime < LOCKTIME_THRESHOLD &&
this.refundLocktime < LOCKTIME_THRESHOLD) ||
(this.cetLocktime >= LOCKTIME_THRESHOLD &&
this.refundLocktime >= LOCKTIME_THRESHOLD)
)
) {
throw new Error('cetLocktime and refundLocktime must be in same units');
}
// 8. cetLocktime must be less than refundLocktime
if (this.cetLocktime >= this.refundLocktime) {
throw new Error('cetLocktime must be less than refundLocktime');
}
// validate contractInfo
this.contractInfo.validate();
// totalCollateral should be > offerCollateral (logical validation)
if (this.contractInfo.getTotalCollateral() <= this.offerCollateral) {
throw new Error('totalCollateral should be greater than offerCollateral');
}
}
/**
* Converts order_offer to JSON
*/
public toJSON(): IOrderOfferJSON {
const tlvs = [];
Iif (this.metadata) tlvs.push(this.metadata.toJSON());
Iif (this.ircInfo) tlvs.push(this.ircInfo.toJSON());
Iif (this.positionInfo) tlvs.push(this.positionInfo.toJSON());
Iif (this.batchFundingGroups)
this.batchFundingGroups.forEach((fundingInfo) =>
tlvs.push(fundingInfo.toJSON()),
);
// Include unknown TLVs for debugging
Iif (this.unknownTlvs) {
this.unknownTlvs.forEach((tlv) =>
tlvs.push({ type: tlv.type, data: tlv.data.toString('hex') }),
);
}
return {
type: this.type,
protocolVersion: this.protocolVersion,
temporaryContractId: this.temporaryContractId.toString('hex'),
contractFlags: Number(this.contractFlags[0]),
chainHash: this.chainHash.toString('hex'),
contractInfo: this.contractInfo.toJSON(),
offerCollateral: bigIntToNumber(this.offerCollateral),
offerCollateralSatoshis: bigIntToNumber(this.offerCollateral), // Legacy field
feeRatePerVb: bigIntToNumber(this.feeRatePerVb),
cetLocktime: this.cetLocktime,
refundLocktime: this.refundLocktime,
tlvs,
};
}
/**
* Serializes the order_offer message into a Buffer
*/
public serialize(): Buffer {
const writer = new BufferWriter();
writer.writeUInt16BE(this.type);
// New fields as per dlcspecs PR #163
writer.writeUInt32BE(this.protocolVersion);
writer.writeBytes(this.contractFlags);
writer.writeBytes(this.chainHash);
writer.writeBytes(this.temporaryContractId); // New field
writer.writeBytes(this.contractInfo.serialize());
writer.writeUInt64BE(this.offerCollateral);
writer.writeUInt64BE(this.feeRatePerVb);
writer.writeUInt32BE(this.cetLocktime);
writer.writeUInt32BE(this.refundLocktime);
// TLV stream as per dlcspecs PR #163
Iif (this.metadata) writer.writeBytes(this.metadata.serialize());
Iif (this.ircInfo) writer.writeBytes(this.ircInfo.serialize());
Iif (this.positionInfo) writer.writeBytes(this.positionInfo.serialize());
Iif (this.batchFundingGroups)
this.batchFundingGroups.forEach((fundingInfo) =>
writer.writeBytes(fundingInfo.serialize()),
);
// Write unknown TLVs for forward compatibility
Iif (this.unknownTlvs) {
this.unknownTlvs.forEach((tlv) => {
writer.writeBytes(tlv.data);
});
}
return writer.toBuffer();
}
}
export interface IOrderOfferJSON {
type: number;
protocolVersion: number;
temporaryContractId: string;
contractFlags: number;
chainHash: string;
contractInfo: IContractInfoV0JSON | IContractInfoV1JSON;
offerCollateral: number;
offerCollateralSatoshis: number; // Legacy field for backward compatibility
feeRatePerVb: number;
cetLocktime: number;
refundLocktime: number;
tlvs: (
| IOrderMetadataJSON
| IOrderIrcInfoJSON
| IOrderPositionInfoJSON
| IBatchFundingGroupJSON
| unknown
)[];
}
export class OrderOfferContainer {
private offers: OrderOffer[] = [];
/**
* Adds an OrderOffer to the container.
* @param offer The OrderOffer to add.
*/
public addOffer(offer: OrderOffer): void {
this.offers.push(offer);
}
/**
* Returns all OrderOffers in the container.
* @returns An array of OrderOffer instances.
*/
public getOffers(): OrderOffer[] {
return this.offers;
}
/**
* Serializes all OrderOffers in the container to a Buffer.
* @returns A Buffer containing the serialized OrderOffers.
*/
public serialize(): Buffer {
const writer = new BufferWriter();
// Write the number of offers in the container first.
writer.writeBigSize(this.offers.length);
// Serialize each offer and write it.
this.offers.forEach((offer) => {
const serializedOffer = offer.serialize();
// Optionally, write the length of the serialized offer for easier deserialization.
writer.writeBigSize(serializedOffer.length);
writer.writeBytes(serializedOffer);
});
return writer.toBuffer();
}
/**
* Deserializes a Buffer into an OrderOfferContainer with OrderOffers.
* @param buf The Buffer to deserialize.
* @returns An OrderOfferContainer instance.
*/
public static deserialize(buf: Buffer): OrderOfferContainer {
const reader = new BufferReader(buf);
const container = new OrderOfferContainer();
const offersCount = reader.readBigSize();
for (let i = 0; i < offersCount; i++) {
// Optionally, read the length of the serialized offer if it was written during serialization.
const offerLength = reader.readBigSize();
const offerBuf = reader.readBytes(Number(offerLength));
const offer = OrderOffer.deserialize(offerBuf);
container.addOffer(offer);
}
return container;
}
}
|