@node-dlc/messaging
Version:
DLC Messaging Protocol
325 lines • 14.5 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DlcOfferContainer = exports.DlcOfferV0 = exports.DlcOffer = exports.LOCKTIME_THRESHOLD = void 0;
const bitcoin_1 = require("@node-dlc/bitcoin");
const bufio_1 = require("@node-dlc/bufio");
const crypto_1 = require("@node-dlc/crypto");
const bitcoinjs_lib_1 = require("bitcoinjs-lib");
const secp256k1_1 = __importDefault(require("secp256k1"));
const MessageType_1 = require("../MessageType");
const deserializeTlv_1 = require("../serialize/deserializeTlv");
const getTlv_1 = require("../serialize/getTlv");
const BatchFundingGroup_1 = require("./BatchFundingGroup");
const ContractInfo_1 = require("./ContractInfo");
const FundingInput_1 = require("./FundingInput");
const OrderIrcInfo_1 = require("./OrderIrcInfo");
const OrderMetadata_1 = require("./OrderMetadata");
const OrderPositionInfo_1 = require("./OrderPositionInfo");
exports.LOCKTIME_THRESHOLD = 500000000;
class DlcOffer {
static deserialize(buf) {
const reader = new bufio_1.BufferReader(buf);
const type = Number(reader.readUInt16BE());
switch (type) {
case MessageType_1.MessageType.DlcOfferV0:
return DlcOfferV0.deserialize(buf);
default:
throw new Error(`DLC Offer message type must be DlcOfferV0`); // This is a temporary measure while protocol is being developed
}
}
}
exports.DlcOffer = DlcOffer;
/**
* DlcOffer message contains information about a node and indicates its
* desire to enter into a new contract. This is the first step toward
* creating the funding transaction and CETs.
*/
class DlcOfferV0 extends DlcOffer {
constructor() {
super(...arguments);
/**
* The type for offer_dlc_v0 message. offer_dlc_v0 = 42778
*/
this.type = DlcOfferV0.type;
this.fundingInputs = [];
}
/**
* Deserializes an offer_dlc_v0 message
* @param buf
*/
static deserialize(buf) {
const instance = new DlcOfferV0();
const reader = new bufio_1.BufferReader(buf);
reader.readUInt16BE(); // read type
instance.contractFlags = reader.readBytes(1);
instance.chainHash = reader.readBytes(32);
instance.contractInfo = ContractInfo_1.ContractInfo.deserialize((0, getTlv_1.getTlv)(reader));
instance.fundingPubKey = reader.readBytes(33);
const payoutSPKLen = reader.readUInt16BE();
instance.payoutSPK = reader.readBytes(payoutSPKLen);
instance.payoutSerialId = reader.readUInt64BE();
instance.offerCollateralSatoshis = reader.readUInt64BE();
const fundingInputsLen = reader.readUInt16BE();
for (let i = 0; i < fundingInputsLen; i++) {
instance.fundingInputs.push(FundingInput_1.FundingInput.deserialize((0, getTlv_1.getTlv)(reader)));
}
const changeSPKLen = reader.readUInt16BE();
instance.changeSPK = reader.readBytes(changeSPKLen);
instance.changeSerialId = reader.readUInt64BE();
instance.fundOutputSerialId = reader.readUInt64BE();
instance.feeRatePerVb = reader.readUInt64BE();
instance.cetLocktime = reader.readUInt32BE();
instance.refundLocktime = reader.readUInt32BE();
while (!reader.eof) {
const buf = (0, getTlv_1.getTlv)(reader);
const tlvReader = new bufio_1.BufferReader(buf);
const { type } = (0, deserializeTlv_1.deserializeTlv)(tlvReader);
switch (Number(type)) {
case MessageType_1.MessageType.OrderMetadataV0:
instance.metadata = OrderMetadata_1.OrderMetadataV0.deserialize(buf);
break;
case MessageType_1.MessageType.OrderIrcInfoV0:
instance.ircInfo = OrderIrcInfo_1.OrderIrcInfoV0.deserialize(buf);
break;
case MessageType_1.MessageType.OrderPositionInfoV0:
instance.positionInfo = OrderPositionInfo_1.OrderPositionInfo.deserialize(buf);
break;
case MessageType_1.MessageType.BatchFundingGroup:
if (!instance.batchFundingGroups) {
instance.batchFundingGroups = [];
}
instance.batchFundingGroups.push(BatchFundingGroup_1.BatchFundingGroup.deserialize(buf));
break;
default:
break;
}
}
return instance;
}
/**
* Get funding, change and payout address from DlcOffer
* @param network Bitcoin Network
* @returns {IDlcOfferV0Addresses}
*/
getAddresses(network) {
const fundingSPK = bitcoin_1.Script.p2wpkhLock((0, crypto_1.hash160)(this.fundingPubKey))
.serialize()
.slice(1);
const fundingAddress = bitcoinjs_lib_1.address.fromOutputScript(fundingSPK, network);
const changeAddress = bitcoinjs_lib_1.address.fromOutputScript(this.changeSPK, network);
const payoutAddress = bitcoinjs_lib_1.address.fromOutputScript(this.payoutSPK, network);
return {
fundingAddress,
changeAddress,
payoutAddress,
};
}
/**
* Validates correctness of all fields in DlcOffer
* https://github.com/discreetlogcontracts/dlcspecs/blob/master/Protocol.md#the-offer_dlc-message
* @throws Will throw an error if validation fails
*/
validate() {
// 1. Type is set automatically in class
// 2. contract_flags field is ignored
// 3. chain_hash must be validated as input by end user
// 4. payout_spk and change_spk must be standard script pubkeys
try {
bitcoinjs_lib_1.address.fromOutputScript(this.payoutSPK);
}
catch (e) {
throw new Error('DlcOffer payoutSPK is invalid');
}
try {
bitcoinjs_lib_1.address.fromOutputScript(this.changeSPK);
}
catch (e) {
throw new Error('DlcOffer changeSPK is invalid');
}
// 5. funding_pubkey must be a valid secp256k1 pubkey in compressed format
// https://github.com/bitcoin/bips/blob/master/bip-0137.mediawiki#background-on-ecdsa-signatures
if (secp256k1_1.default.publicKeyVerify(Buffer.from(this.fundingPubKey))) {
if (this.fundingPubKey[0] != 0x02 && this.fundingPubKey[0] != 0x03) {
throw new Error('fundingPubKey must be in compressed format');
}
}
else {
throw new Error('fundingPubKey is not a valid secp256k1 key');
}
// 6. offer_collateral_satoshis must be greater than or equal to 1000
if (this.offerCollateralSatoshis < 1000) {
throw new Error('offer_collateral_satoshis 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.
// https://en.bitcoin.it/wiki/NLockTime
// https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki#detailed-specification
// https://github.com/bitcoin/bitcoin/blob/master/src/script/script.h#L39
if (!((this.cetLocktime < exports.LOCKTIME_THRESHOLD &&
this.refundLocktime < exports.LOCKTIME_THRESHOLD) ||
(this.cetLocktime >= exports.LOCKTIME_THRESHOLD &&
this.refundLocktime >= exports.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');
}
// 9. inputSerialId must be unique for each input
const inputSerialIds = this.fundingInputs.map((input) => input.inputSerialId);
if (new Set(inputSerialIds).size !== inputSerialIds.length) {
throw new Error('inputSerialIds must be unique');
}
// 10. changeSerialId and fundOutputSerialID must be different
if (this.changeSerialId === this.fundOutputSerialId) {
throw new Error('changeSerialId and fundOutputSerialId must be different');
}
// validate contractInfo
this.contractInfo.validate();
// totalCollaterial should be > offerCollaterial (logical validation)
if (this.contractInfo.totalCollateral <= this.offerCollateralSatoshis) {
throw new Error('totalCollateral should be greater than offerCollateral');
}
// validate funding amount
const fundingAmount = this.fundingInputs.reduce((acc, fundingInput) => {
const input = fundingInput;
return acc + input.prevTx.outputs[input.prevTxVout].value.sats;
}, BigInt(0));
if (this.offerCollateralSatoshis >= fundingAmount) {
throw new Error('fundingAmount must be greater than offerCollateralSatoshis');
}
}
/**
* Converts dlc_offer_v0 to JSON
*/
toJSON() {
const tlvs = [];
if (this.metadata)
tlvs.push(this.metadata.toJSON());
if (this.ircInfo)
tlvs.push(this.ircInfo.toJSON());
if (this.positionInfo)
tlvs.push(this.positionInfo.toJSON());
if (this.batchFundingGroups)
this.batchFundingGroups.forEach((fundingInfo) => tlvs.push(fundingInfo.toJSON()));
return {
type: this.type,
contractFlags: this.contractFlags.toString('hex'),
chainHash: this.chainHash.toString('hex'),
contractInfo: this.contractInfo.toJSON(),
fundingPubKey: this.fundingPubKey.toString('hex'),
payoutSPK: this.payoutSPK.toString('hex'),
payoutSerialId: Number(this.payoutSerialId),
offerCollateralSatoshis: Number(this.offerCollateralSatoshis),
fundingInputs: this.fundingInputs.map((input) => input.toJSON()),
changeSPK: this.changeSPK.toString('hex'),
changeSerialId: Number(this.changeSerialId),
fundOutputSerialId: Number(this.fundOutputSerialId),
feeRatePerVb: Number(this.feeRatePerVb),
cetLocktime: this.cetLocktime,
refundLocktime: this.refundLocktime,
tlvs,
};
}
/**
* Serializes the offer_dlc_v0 message into a Buffer
*/
serialize() {
const writer = new bufio_1.BufferWriter();
writer.writeUInt16BE(this.type);
writer.writeBytes(this.contractFlags);
writer.writeBytes(this.chainHash);
writer.writeBytes(this.contractInfo.serialize());
writer.writeBytes(this.fundingPubKey);
writer.writeUInt16BE(this.payoutSPK.length);
writer.writeBytes(this.payoutSPK);
writer.writeUInt64BE(this.payoutSerialId);
writer.writeUInt64BE(this.offerCollateralSatoshis);
writer.writeUInt16BE(this.fundingInputs.length);
for (const fundingInput of this.fundingInputs) {
writer.writeBytes(fundingInput.serialize());
}
writer.writeUInt16BE(this.changeSPK.length);
writer.writeBytes(this.changeSPK);
writer.writeUInt64BE(this.changeSerialId);
writer.writeUInt64BE(this.fundOutputSerialId);
writer.writeUInt64BE(this.feeRatePerVb);
writer.writeUInt32BE(this.cetLocktime);
writer.writeUInt32BE(this.refundLocktime);
if (this.metadata)
writer.writeBytes(this.metadata.serialize());
if (this.ircInfo)
writer.writeBytes(this.ircInfo.serialize());
if (this.positionInfo)
writer.writeBytes(this.positionInfo.serialize());
if (this.batchFundingGroups)
this.batchFundingGroups.forEach((fundingInfo) => writer.writeBytes(fundingInfo.serialize()));
return writer.toBuffer();
}
}
exports.DlcOfferV0 = DlcOfferV0;
DlcOfferV0.type = MessageType_1.MessageType.DlcOfferV0;
class DlcOfferContainer {
constructor() {
this.offers = [];
}
/**
* Adds a DlcOffer to the container.
* @param offer The DlcOffer to add.
*/
addOffer(offer) {
this.offers.push(offer);
}
/**
* Returns all DlcOffers in the container.
* @returns An array of DlcOffer instances.
*/
getOffers() {
return this.offers;
}
/**
* Serializes all DlcOffers in the container to a Buffer.
* @returns A Buffer containing the serialized DlcOffers.
*/
serialize() {
const writer = new bufio_1.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 a DlcOfferContainer with DlcOffers.
* @param buf The Buffer to deserialize.
* @returns A DlcOfferContainer instance.
*/
static deserialize(buf) {
const reader = new bufio_1.BufferReader(buf);
const container = new DlcOfferContainer();
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 = DlcOffer.deserialize(offerBuf); // This needs to be adjusted based on actual implementation.
container.addOffer(offer);
}
return container;
}
}
exports.DlcOfferContainer = DlcOfferContainer;
//# sourceMappingURL=DlcOffer.js.map