Skip to main content

hns_swap/
lib.rs

1#![doc = "HIP-0001 name swaps, signed marketplace listings, and HNS HTLC primitives."]
2
3mod htlc;
4mod listing;
5
6pub use htlc::{
7    HNS_HTLC_HASHLOCK_SIZE, HNS_HTLC_PREIMAGE_SIZE, HNS_HTLC_SIGHASH, HNS_HTLC_VERSION, HnsHtlc,
8    HnsHtlcPreimage, HnsHtlcSpend, MAX_HNS_HTLC_DESCRIPTOR_SIZE,
9};
10pub use listing::{
11    FIXED_PRICE_LISTING_VERSION, FixedPriceListing, LISTING_CANCELLATION_VERSION,
12    ListingCancellation, MARKETPLACE_SIGNATURE_SIZE, MAX_FIXED_PRICE_LISTING_SIZE,
13    MAX_LISTING_CANCELLATION_SIZE,
14};
15
16use blake2::Blake2bVar;
17use blake2::digest::{Update, VariableOutput};
18use hns_covenants::{
19    Covenant, CovenantKind, FinalizeCovenant, TransferCovenant, hash_name, validate_name,
20};
21use hns_encoding::{Decoder, Encoder};
22use hns_primitives::{BlockHash, Dollarydoos, OfferId, TransactionHash};
23use hns_script::{
24    HIP1_SELLER_SIGHASH, LOCKTIME_FLAG, LOCKTIME_MASK, OP_9, OP_10, OP_CHECKSIG, OP_ELSE, OP_ENDIF,
25    OP_EQUAL, OP_IF, OP_TYPE, SIGHASH_ANYONE_CAN_PAY, SIGHASH_SINGLE, signature_hash,
26};
27use hns_transaction::{
28    Address, Coin, Input, Outpoint, Output, Transaction, Witness, build_transfer_output,
29    build_transfer_transaction,
30};
31use k256::ecdsa::signature::hazmat::{PrehashSigner, PrehashVerifier};
32use k256::ecdsa::{Signature, SigningKey, VerifyingKey};
33use sha3::{Digest, Sha3_256};
34use thiserror::Error;
35
36pub const SHAKEDEX_PROTOCOL_VERSION: u16 = 2;
37pub const MAX_SWAP_PROOF_SIZE: usize = 4 * 1024;
38pub const MAX_AUCTION_STEPS: usize = 512;
39pub const MAX_AUCTION_BUNDLE_SIZE: usize = 1024 * 1024;
40pub const HSD_LOCKTIME_MULTIPLIER: u64 = 512;
41pub const MAX_HSD_TIME_LOCK: u64 = 1_u64 << 40;
42pub const SWAP_LOCK_SCRIPT_SIZE: usize = 44;
43pub const COMPACT_SIGNATURE_SIZE: usize = 65;
44/// Seller hash mode for transferring a locked name to an explicit recovery
45/// recipient before its later consensus FINALIZE.
46pub const SHAKEDEX_RECOVERY_SIGHASH: u32 = SIGHASH_SINGLE | SIGHASH_ANYONE_CAN_PAY;
47
48/// An HSD median-time lock encoded at 512-second consensus granularity.
49///
50/// `effective_time_seconds` is the earliest represented Unix time. For
51/// safety-deadline construction use [`encode_time_lock_not_before`], which
52/// rounds upward and therefore never makes a refund executable before the
53/// promised Unix deadline.
54#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55pub struct HsdTimeLock {
56    pub encoded: u32,
57    pub effective_time_seconds: u64,
58}
59
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct NetworkBinding {
62    pub magic: u32,
63    pub genesis: BlockHash,
64}
65
66#[derive(Clone, Debug, Eq, PartialEq)]
67pub struct SwapProof {
68    pub network: NetworkBinding,
69    pub locking_outpoint: Outpoint,
70    pub name: Vec<u8>,
71    pub seller_public_key: [u8; 33],
72    pub payment_address: Address,
73    pub price: Dollarydoos,
74    /// Shakedex v2 stores wall-clock seconds and lets HSD encode its
75    /// 512-second absolute-locktime granularity when reconstructing the TX.
76    pub lock_time_seconds: u64,
77    pub signature: Option<[u8; COMPACT_SIGNATURE_SIZE]>,
78    pub fee_address: Option<Address>,
79    pub fee: Dollarydoos,
80}
81
82/// Canonical spend branches of a HIP-0001/Shakedex v2 name lock.
83#[derive(Clone, Copy, Debug, Eq, PartialEq)]
84pub enum ShakedexSpendKind {
85    /// Seller-authorized transfer to the buyer named by the TRANSFER covenant.
86    Fulfillment,
87    /// Seller-authorized cancellation TRANSFER to an explicit recovery address.
88    Recovery,
89}
90
91/// Listing-independent identity and recovery authority for one Shakedex name
92/// lock.
93///
94/// A wallet can reconstruct this descriptor from a seed-derived
95/// `HnsShakedex` public key, an explicit network binding, and a discovered
96/// canonical FINALIZE coin without retaining any offer price, payment address,
97/// marketplace fee, deadline, or seller presign.
98#[derive(Clone, Debug, Eq, PartialEq)]
99pub struct ShakedexLockDescriptor {
100    pub network: NetworkBinding,
101    pub locking_outpoint: Outpoint,
102    pub name: Vec<u8>,
103    pub seller_public_key: [u8; 33],
104}
105
106impl ShakedexLockDescriptor {
107    pub fn new(
108        network: NetworkBinding,
109        locking_outpoint: Outpoint,
110        name: Vec<u8>,
111        seller_public_key: [u8; 33],
112    ) -> Result<Self, SwapError> {
113        let descriptor = Self {
114            network,
115            locking_outpoint,
116            name,
117            seller_public_key,
118        };
119        descriptor.validate()?;
120        Ok(descriptor)
121    }
122
123    /// Reconstruct a descriptor from an explicit network binding, exact
124    /// on-chain Shakedex lock, and seed-derived seller public key.
125    pub fn from_locking_coin(
126        network: NetworkBinding,
127        locking_coin: &Coin,
128        seller_public_key: [u8; 33],
129    ) -> Result<Self, SwapError> {
130        if locking_coin.covenant.kind != CovenantKind::Finalize {
131            return Err(SwapError::LockingCoinNotFinalize);
132        }
133        let finalize = FinalizeCovenant::try_from(&locking_coin.covenant)
134            .map_err(|_| SwapError::InvalidShakedexLockingCovenant)?;
135        let descriptor = Self::new(
136            network,
137            locking_coin.outpoint,
138            finalize.name,
139            seller_public_key,
140        )?;
141        descriptor.verify_locking_coin(locking_coin)?;
142        Ok(descriptor)
143    }
144
145    pub fn validate(&self) -> Result<(), SwapError> {
146        if self.locking_outpoint.is_null() {
147            return Err(SwapError::NullShakedexLockingOutpoint);
148        }
149        if !validate_name(&self.name) {
150            return Err(SwapError::InvalidName);
151        }
152        VerifyingKey::from_sec1_bytes(&self.seller_public_key)
153            .map_err(|_| SwapError::InvalidPublicKey)?;
154        Ok(())
155    }
156
157    pub fn lock_script(&self) -> Result<[u8; SWAP_LOCK_SCRIPT_SIZE], SwapError> {
158        self.validate()?;
159        Ok(create_lock_script(&self.seller_public_key))
160    }
161
162    pub fn lock_script_identifier(&self) -> Result<[u8; 32], SwapError> {
163        self.validate()?;
164        Ok(lock_script_hash(&self.seller_public_key))
165    }
166
167    pub fn verify_locking_coin(&self, locking_coin: &Coin) -> Result<(), SwapError> {
168        self.validate()?;
169        if locking_coin.outpoint.is_null() {
170            return Err(SwapError::NullShakedexLockingOutpoint);
171        }
172        if locking_coin.coinbase {
173            return Err(SwapError::CoinbaseShakedexLockingCoin);
174        }
175        if locking_coin.outpoint != self.locking_outpoint {
176            return Err(SwapError::OutpointMismatch);
177        }
178        if locking_coin.covenant.kind != CovenantKind::Finalize {
179            return Err(SwapError::LockingCoinNotFinalize);
180        }
181        if locking_coin.covenant.item(2) != Some(self.name.as_slice()) {
182            return Err(SwapError::NameMismatch);
183        }
184        let expected_name_hash = hash_name(&self.name)?;
185        if locking_coin.covenant.item_name_hash(0) != Some(expected_name_hash) {
186            return Err(SwapError::NameHashMismatch);
187        }
188        FinalizeCovenant::try_from(&locking_coin.covenant)
189            .map_err(|_| SwapError::InvalidShakedexLockingCovenant)?;
190        if locking_coin.address.version != 0
191            || locking_coin.address.hash.as_slice() != lock_script_hash(&self.seller_public_key)
192        {
193            return Err(SwapError::LockScriptMismatch);
194        }
195        Ok(())
196    }
197
198    pub fn verify_for_network(
199        &self,
200        expected_network: NetworkBinding,
201        locking_coin: &Coin,
202    ) -> Result<(), SwapError> {
203        if self.network != expected_network {
204            return Err(SwapError::NetworkMismatch);
205        }
206        self.verify_locking_coin(locking_coin)
207    }
208
209    /// Build the unsigned seller recovery TRANSFER without consulting an
210    /// offer. Funding inputs are required so the name's locked value remains
211    /// exact while the wallet pays transaction fees independently.
212    pub fn recovery_transaction(
213        &self,
214        locking_coin: &Coin,
215        recovery_recipient: &Address,
216        funding_inputs: Vec<Input>,
217        funding_outputs: Vec<Output>,
218    ) -> Result<Transaction, SwapError> {
219        self.verify_locking_coin(locking_coin)?;
220        if funding_inputs.is_empty() {
221            return Err(SwapError::MissingShakedexRecoveryFundingInputs);
222        }
223        if funding_inputs
224            .iter()
225            .any(|input| input.previous_output == locking_coin.outpoint)
226        {
227            return Err(SwapError::DuplicateShakedexSellerInput);
228        }
229        let transaction = build_transfer_transaction(
230            locking_coin,
231            recovery_recipient,
232            funding_inputs,
233            funding_outputs,
234        )?;
235        verify_recovery_layout(self, &transaction, locking_coin, recovery_recipient, false)?;
236        Ok(transaction)
237    }
238
239    /// Return the fixed `SIGHASH_SINGLE | ANYONECANPAY` digest for an exact
240    /// listing-independent recovery TRANSFER.
241    pub fn recovery_signature_hash(
242        &self,
243        transaction: &Transaction,
244        locking_coin: &Coin,
245        recovery_recipient: &Address,
246    ) -> Result<[u8; 32], SwapError> {
247        verify_recovery_layout(self, transaction, locking_coin, recovery_recipient, false)?;
248        Ok(signature_hash(
249            transaction,
250            0,
251            &create_lock_script(&self.seller_public_key),
252            locking_coin.value.get(),
253            SHAKEDEX_RECOVERY_SIGHASH,
254        )?)
255    }
256
257    /// Assemble the exact seller-signed TRANSFER witness.
258    pub fn recovery_witness(
259        &self,
260        signature: &[u8; COMPACT_SIGNATURE_SIZE],
261    ) -> Result<Witness, SwapError> {
262        self.validate()?;
263        validate_shakedex_signature(signature, SHAKEDEX_RECOVERY_SIGHASH as u8)?;
264        Ok(Witness {
265            items: vec![
266                signature.to_vec(),
267                create_lock_script(&self.seller_public_key).to_vec(),
268            ],
269        })
270    }
271
272    /// Return the exact no-signature witness for the script's FINALIZE branch:
273    /// one item containing only the lock script.
274    pub fn finalize_witness(&self) -> Result<Witness, SwapError> {
275        self.validate()?;
276        Ok(Witness {
277            items: vec![create_lock_script(&self.seller_public_key).to_vec()],
278        })
279    }
280
281    /// Authenticate a listing-independent recovery TRANSFER to the caller's
282    /// explicit recipient.
283    pub fn verify_recovery(
284        &self,
285        transaction: &Transaction,
286        locking_coin: &Coin,
287        recovery_recipient: &Address,
288    ) -> Result<(), SwapError> {
289        verify_recovery_layout(self, transaction, locking_coin, recovery_recipient, true)?;
290        let signature: &[u8; COMPACT_SIGNATURE_SIZE] = transaction.inputs[0].witness.items[0]
291            .as_slice()
292            .try_into()
293            .map_err(|_| SwapError::InvalidSignature)?;
294        let signature_value =
295            validate_shakedex_signature(signature, SHAKEDEX_RECOVERY_SIGHASH as u8)?;
296        let public_key = VerifyingKey::from_sec1_bytes(&self.seller_public_key)
297            .map_err(|_| SwapError::InvalidPublicKey)?;
298        public_key
299            .verify_prehash(
300                &self.recovery_signature_hash(transaction, locking_coin, recovery_recipient)?,
301                &signature_value,
302            )
303            .map_err(|_| SwapError::InvalidSignature)
304    }
305}
306
307impl SwapProof {
308    pub fn validate(&self) -> Result<(), SwapError> {
309        if !validate_name(&self.name) {
310            return Err(SwapError::InvalidName);
311        }
312        VerifyingKey::from_sec1_bytes(&self.seller_public_key)
313            .map_err(|_| SwapError::InvalidPublicKey)?;
314        self.payment_address.validate()?;
315        if self.price.get() == 0 {
316            return Err(SwapError::ZeroPrice);
317        }
318        encode_time_lock(self.lock_time_seconds)?;
319        match (&self.fee_address, self.fee.get()) {
320            (None, 0) => {}
321            (Some(address), fee) if fee > 0 => address.validate()?,
322            _ => return Err(SwapError::InvalidFee),
323        }
324        if let Some(signature) = self.signature
325            && signature[64] != HIP1_SELLER_SIGHASH as u8
326        {
327            return Err(SwapError::WrongSellerHashType(signature[64]));
328        }
329        Ok(())
330    }
331
332    pub fn encode(&self) -> Result<Vec<u8>, SwapError> {
333        self.validate()?;
334        let mut encoder = Encoder::new();
335        encoder.put_u16_le(SHAKEDEX_PROTOCOL_VERSION);
336        encoder.put_u32_le(self.network.magic);
337        encoder.put_bytes(self.network.genesis.as_bytes());
338        encoder.put_bytes(&self.locking_outpoint.encode());
339        encoder.put_varbytes(&self.name);
340        encoder.put_bytes(&self.seller_public_key);
341        encode_address(&self.payment_address, &mut encoder);
342        encoder.put_u64_le(self.price.get());
343        encoder.put_u64_le(self.lock_time_seconds);
344        match self.signature {
345            Some(signature) => {
346                encoder.put_u8(1);
347                encoder.put_bytes(&signature);
348            }
349            None => encoder.put_u8(0),
350        }
351        encoder.put_u64_le(self.fee.get());
352        match &self.fee_address {
353            Some(address) => {
354                encoder.put_u8(1);
355                encode_address(address, &mut encoder);
356            }
357            None => encoder.put_u8(0),
358        }
359        let encoded = encoder.into_bytes();
360        if encoded.len() > MAX_SWAP_PROOF_SIZE {
361            return Err(SwapError::ProofTooLarge(encoded.len()));
362        }
363        Ok(encoded)
364    }
365
366    /// Project the listing-independent lock and recovery authority committed
367    /// by this proof.
368    pub fn lock_descriptor(&self) -> Result<ShakedexLockDescriptor, SwapError> {
369        if !validate_name(&self.name) {
370            return Err(SwapError::InvalidName);
371        }
372        ShakedexLockDescriptor::new(
373            self.network,
374            self.locking_outpoint,
375            self.name.clone(),
376            self.seller_public_key,
377        )
378    }
379
380    pub fn decode(input: &[u8]) -> Result<Self, SwapError> {
381        if input.len() > MAX_SWAP_PROOF_SIZE {
382            return Err(SwapError::ProofTooLarge(input.len()));
383        }
384        let mut decoder = Decoder::new(input);
385        let version = decoder.read_u16_le()?;
386        if version != SHAKEDEX_PROTOCOL_VERSION {
387            return Err(SwapError::UnsupportedVersion(version));
388        }
389        let network = NetworkBinding {
390            magic: decoder.read_u32_le()?,
391            genesis: BlockHash::new(decoder.read_array()?),
392        };
393        let locking_outpoint = Outpoint {
394            transaction_hash: TransactionHash::new(decoder.read_array()?),
395            index: decoder.read_u32_le()?,
396        };
397        let name = decoder.read_varbytes(63, "swap name")?;
398        let seller_public_key = decoder.read_array()?;
399        let payment_address = decode_address(&mut decoder)?;
400        let price = Dollarydoos::new(decoder.read_u64_le()?);
401        let lock_time_seconds = decoder.read_u64_le()?;
402        let signature = match decoder.read_u8()? {
403            0 => None,
404            1 => Some(decoder.read_array()?),
405            _ => return Err(SwapError::InvalidPresenceFlag("signature")),
406        };
407        let fee = Dollarydoos::new(decoder.read_u64_le()?);
408        let fee_address = match decoder.read_u8()? {
409            0 => None,
410            1 => Some(decode_address(&mut decoder)?),
411            _ => return Err(SwapError::InvalidPresenceFlag("fee address")),
412        };
413        decoder.finish()?;
414        let proof = Self {
415            network,
416            locking_outpoint,
417            name,
418            seller_public_key,
419            payment_address,
420            price,
421            lock_time_seconds,
422            signature,
423            fee_address,
424            fee,
425        };
426        proof.validate()?;
427        Ok(proof)
428    }
429
430    pub fn offer_id(&self) -> Result<OfferId, SwapError> {
431        let signature = self.signature.ok_or(SwapError::UnsignedProof)?;
432        let mut encoded = self.encode()?;
433        debug_assert!(
434            encoded
435                .windows(signature.len())
436                .any(|part| part == signature)
437        );
438        encoded.extend_from_slice(b"HIP-0001/Shakedex-v2/offer");
439        Ok(OfferId::new(blake2b_256(&encoded)))
440    }
441
442    pub fn sign(&mut self, locking_coin: &Coin, signing_key: &SigningKey) -> Result<(), SwapError> {
443        let public_key = signing_key.verifying_key().to_sec1_point(true);
444        if public_key.as_bytes() != self.seller_public_key {
445            return Err(SwapError::SigningKeyMismatch);
446        }
447        self.signature = None;
448        let transaction = self.presigned_transaction(locking_coin)?;
449        let script = create_lock_script(&self.seller_public_key);
450        let digest = signature_hash(
451            &transaction,
452            0,
453            &script,
454            locking_coin.value.get(),
455            HIP1_SELLER_SIGHASH,
456        )?;
457        let signature: Signature = signing_key
458            .sign_prehash(&digest)
459            .map_err(|_| SwapError::SignatureFailure)?;
460        let signature = signature.normalize_s();
461        let mut encoded = [0_u8; COMPACT_SIGNATURE_SIZE];
462        encoded[..64].copy_from_slice(&signature.to_bytes());
463        encoded[64] = HIP1_SELLER_SIGHASH as u8;
464        self.signature = Some(encoded);
465        self.verify(locking_coin)
466    }
467
468    pub fn verify(&self, locking_coin: &Coin) -> Result<(), SwapError> {
469        self.validate()?;
470        verify_locking_coin(self, locking_coin)?;
471        let encoded_signature = self.signature.ok_or(SwapError::UnsignedProof)?;
472        let signature = Signature::from_slice(&encoded_signature[..64])
473            .map_err(|_| SwapError::InvalidSignature)?;
474        if signature != signature.normalize_s() {
475            return Err(SwapError::HighSignature);
476        }
477        let transaction = self.presigned_transaction(locking_coin)?;
478        let script = create_lock_script(&self.seller_public_key);
479        let digest = signature_hash(
480            &transaction,
481            0,
482            &script,
483            locking_coin.value.get(),
484            HIP1_SELLER_SIGHASH,
485        )?;
486        let public_key = VerifyingKey::from_sec1_bytes(&self.seller_public_key)
487            .map_err(|_| SwapError::InvalidPublicKey)?;
488        public_key
489            .verify_prehash(&digest, &signature)
490            .map_err(|_| SwapError::InvalidSignature)
491    }
492
493    pub fn verify_for_network(
494        &self,
495        expected_network: NetworkBinding,
496        locking_coin: &Coin,
497    ) -> Result<(), SwapError> {
498        if self.network != expected_network {
499            return Err(SwapError::NetworkMismatch);
500        }
501        self.verify(locking_coin)
502    }
503
504    pub fn presigned_transaction(&self, locking_coin: &Coin) -> Result<Transaction, SwapError> {
505        self.validate()?;
506        verify_locking_coin(self, locking_coin)?;
507        let script = create_lock_script(&self.seller_public_key);
508        let witness = self
509            .signature
510            .map_or_else(Witness::default, |signature| Witness {
511                items: vec![signature.to_vec(), script.to_vec()],
512            });
513        let mut outputs = vec![Output {
514            value: Dollarydoos::new(0),
515            address: Address::new(0, vec![0; 20])?,
516            covenant: Covenant {
517                kind: CovenantKind::Transfer,
518                items: Vec::new(),
519            },
520        }];
521        if self.fee.get() > 0 {
522            outputs.push(Output {
523                value: self.fee,
524                address: self.fee_address.clone().ok_or(SwapError::InvalidFee)?,
525                covenant: Covenant::default(),
526            });
527        }
528        outputs.push(Output {
529            value: self.price,
530            address: self.payment_address.clone(),
531            covenant: Covenant::default(),
532        });
533        Ok(Transaction {
534            version: 0,
535            inputs: vec![Input {
536                previous_output: self.locking_outpoint,
537                sequence: u32::MAX - 1,
538                witness,
539            }],
540            outputs,
541            locktime: encode_time_lock(self.lock_time_seconds)?,
542        })
543    }
544
545    /// Return the exact seller digest committed by the HIP-0001 presign.
546    ///
547    /// Canonical fulfillments keep the seller input at index zero and the
548    /// seller payment as the final output. Callers cannot select a different
549    /// hash mode or input position through this API.
550    pub fn seller_signature_hash(
551        &self,
552        transaction: &Transaction,
553        locking_coin: &Coin,
554    ) -> Result<[u8; 32], SwapError> {
555        self.validate()?;
556        verify_locking_coin(self, locking_coin)?;
557        let seller_input =
558            transaction
559                .inputs
560                .first()
561                .ok_or(SwapError::InvalidShakedexFulfillment(
562                    "seller input is missing",
563                ))?;
564        if seller_input.previous_output != locking_coin.outpoint {
565            return Err(SwapError::OutpointMismatch);
566        }
567        Ok(signature_hash(
568            transaction,
569            0,
570            &create_lock_script(&self.seller_public_key),
571            locking_coin.value.get(),
572            HIP1_SELLER_SIGHASH,
573        )?)
574    }
575
576    /// Build the canonical buyer fulfillment around wallet-funded inputs and
577    /// outputs without exposing HIP-0001 layout or seller-sighash choices.
578    ///
579    /// `buyer_inputs` and `buyer_outputs` are supplied by the wallet funding
580    /// layer. They are appended after the seller input and before the seller
581    /// payment respectively. The wallet remains responsible for signing those
582    /// inputs and for ordinary transaction balance/fee policy.
583    pub fn fulfillment_transaction(
584        &self,
585        locking_coin: &Coin,
586        name_recipient: &Address,
587        mut buyer_inputs: Vec<Input>,
588        buyer_outputs: Vec<Output>,
589    ) -> Result<Transaction, SwapError> {
590        self.verify(locking_coin)?;
591        name_recipient.validate()?;
592        if buyer_inputs.is_empty() {
593            return Err(SwapError::MissingShakedexBuyerInputs);
594        }
595        if buyer_inputs
596            .iter()
597            .any(|input| input.previous_output == locking_coin.outpoint)
598        {
599            return Err(SwapError::DuplicateShakedexSellerInput);
600        }
601
602        let mut transaction = self.presigned_transaction(locking_coin)?;
603        let transfer =
604            transaction
605                .outputs
606                .first_mut()
607                .ok_or(SwapError::InvalidShakedexFulfillment(
608                    "transfer output is missing",
609                ))?;
610        *transfer = build_transfer_output(locking_coin, name_recipient)?;
611
612        transaction.inputs.append(&mut buyer_inputs);
613        let payment = transaction
614            .outputs
615            .pop()
616            .ok_or(SwapError::InvalidShakedexFulfillment(
617                "seller payment is missing",
618            ))?;
619        transaction.outputs.extend(buyer_outputs);
620        transaction.outputs.push(payment);
621        self.verify_fulfillment(&transaction, locking_coin)?;
622        Ok(transaction)
623    }
624
625    /// Verify the seller-authorized part and exact canonical layout of a
626    /// Shakedex buyer fulfillment. Buyer input signatures, fee sufficiency,
627    /// and chain state remain consensus/wallet responsibilities.
628    pub fn verify_fulfillment(
629        &self,
630        transaction: &Transaction,
631        locking_coin: &Coin,
632    ) -> Result<(), SwapError> {
633        self.verify(locking_coin)?;
634        if transaction.version != 0
635            || transaction.locktime != encode_time_lock(self.lock_time_seconds)?
636            || transaction.inputs.len() < 2
637        {
638            return Err(SwapError::InvalidShakedexFulfillment(
639                "transaction header or buyer funding layout differs",
640            ));
641        }
642        let seller_input = &transaction.inputs[0];
643        if seller_input.previous_output != locking_coin.outpoint
644            || seller_input.sequence != u32::MAX - 1
645        {
646            return Err(SwapError::InvalidShakedexFulfillment(
647                "seller input is not canonical index zero",
648            ));
649        }
650        if transaction.inputs[1..]
651            .iter()
652            .any(|input| input.previous_output == locking_coin.outpoint)
653        {
654            return Err(SwapError::DuplicateShakedexSellerInput);
655        }
656
657        let [encoded_signature, witness_script] = seller_input.witness.items.as_slice() else {
658            return Err(SwapError::InvalidShakedexFulfillment(
659                "seller witness layout differs",
660            ));
661        };
662        let expected_signature = self.signature.ok_or(SwapError::UnsignedProof)?;
663        if encoded_signature.as_slice() != expected_signature.as_slice()
664            || witness_script.as_slice() != create_lock_script(&self.seller_public_key).as_slice()
665        {
666            return Err(SwapError::InvalidShakedexFulfillment(
667                "seller witness differs from the presign",
668            ));
669        }
670
671        let transfer = transaction
672            .outputs
673            .first()
674            .ok_or(SwapError::InvalidShakedexFulfillment(
675                "transfer output is missing",
676            ))?;
677        let recipient = transfer_recipient(transfer, self, locking_coin)?;
678        if transfer != &build_transfer_output(locking_coin, &recipient)? {
679            return Err(SwapError::InvalidShakedexFulfillment(
680                "transfer output differs from the locked name",
681            ));
682        }
683
684        let payment = transaction
685            .outputs
686            .last()
687            .ok_or(SwapError::InvalidShakedexFulfillment(
688                "seller payment is missing",
689            ))?;
690        if payment.value != self.price
691            || payment.address != self.payment_address
692            || payment.covenant != Covenant::default()
693        {
694            return Err(SwapError::InvalidShakedexFulfillment(
695                "seller payment is not the final output",
696            ));
697        }
698        if self.fee.get() > 0 {
699            let fee = transaction
700                .outputs
701                .get(1)
702                .ok_or(SwapError::InvalidShakedexFulfillment(
703                    "marketplace fee output is missing",
704                ))?;
705            if fee.value != self.fee
706                || Some(&fee.address) != self.fee_address.as_ref()
707                || fee.covenant != Covenant::default()
708            {
709                return Err(SwapError::InvalidShakedexFulfillment(
710                    "marketplace fee output differs",
711                ));
712            }
713        }
714
715        verify_seller_signature(self, transaction, locking_coin)
716    }
717
718    /// Build the unsigned canonical first-stage recovery transfer. The seller
719    /// signs [`Self::recovery_signature_hash`] and installs the result with
720    /// [`Self::recovery_witness`]; the recipient later finalizes after the
721    /// Handshake transfer lock.
722    pub fn recovery_transaction(
723        &self,
724        locking_coin: &Coin,
725        recovery_recipient: &Address,
726        funding_inputs: Vec<Input>,
727        funding_outputs: Vec<Output>,
728    ) -> Result<Transaction, SwapError> {
729        self.lock_descriptor()?.recovery_transaction(
730            locking_coin,
731            recovery_recipient,
732            funding_inputs,
733            funding_outputs,
734        )
735    }
736
737    /// Return the fixed `SIGHASH_SINGLE | ANYONECANPAY` digest for an exact
738    /// first-stage recovery transfer.
739    pub fn recovery_signature_hash(
740        &self,
741        transaction: &Transaction,
742        locking_coin: &Coin,
743        recovery_recipient: &Address,
744    ) -> Result<[u8; 32], SwapError> {
745        self.lock_descriptor()?.recovery_signature_hash(
746            transaction,
747            locking_coin,
748            recovery_recipient,
749        )
750    }
751
752    /// Assemble the exact recovery witness after enforcing compact low-S
753    /// encoding and the fixed recovery hash type.
754    pub fn recovery_witness(
755        &self,
756        signature: &[u8; COMPACT_SIGNATURE_SIZE],
757    ) -> Result<Witness, SwapError> {
758        self.lock_descriptor()?.recovery_witness(signature)
759    }
760
761    /// Authenticate a first-stage recovery transfer to the caller's explicit
762    /// recipient. No recipient is inferred from a marketplace listing.
763    pub fn verify_recovery(
764        &self,
765        transaction: &Transaction,
766        locking_coin: &Coin,
767        recovery_recipient: &Address,
768    ) -> Result<(), SwapError> {
769        self.lock_descriptor()?
770            .verify_recovery(transaction, locking_coin, recovery_recipient)
771    }
772
773    /// Classify and authenticate a seller-authorized transfer of the exact
774    /// locked name coin. Recovery is recognized only when the caller supplies
775    /// its independently selected expected recipient.
776    pub fn classify_spend(
777        &self,
778        transaction: &Transaction,
779        locking_coin: &Coin,
780        expected_recovery_recipient: Option<&Address>,
781    ) -> Result<ShakedexSpendKind, SwapError> {
782        let seller_input = transaction
783            .inputs
784            .first()
785            .ok_or(SwapError::UnrecognizedShakedexSpend)?;
786        let [signature, witness_script] = seller_input.witness.items.as_slice() else {
787            return Err(SwapError::UnrecognizedShakedexSpend);
788        };
789        if witness_script.as_slice() != create_lock_script(&self.seller_public_key).as_slice() {
790            return Err(SwapError::UnrecognizedShakedexSpend);
791        }
792        let signature: &[u8; COMPACT_SIGNATURE_SIZE] = signature
793            .as_slice()
794            .try_into()
795            .map_err(|_| SwapError::InvalidSignature)?;
796        match u32::from(signature[64]) {
797            HIP1_SELLER_SIGHASH => {
798                self.verify_fulfillment(transaction, locking_coin)?;
799                Ok(ShakedexSpendKind::Fulfillment)
800            }
801            SHAKEDEX_RECOVERY_SIGHASH => {
802                let recipient = expected_recovery_recipient
803                    .ok_or(SwapError::MissingShakedexRecoveryRecipient)?;
804                self.verify_recovery(transaction, locking_coin, recipient)?;
805                Ok(ShakedexSpendKind::Recovery)
806            }
807            _ => Err(SwapError::UnrecognizedShakedexSpend),
808        }
809    }
810
811    pub fn is_executable(&self, parent_median_time: u64) -> Result<bool, SwapError> {
812        let encoded = encode_time_lock(self.lock_time_seconds)?;
813        let threshold = u64::from(encoded & LOCKTIME_MASK)
814            .checked_mul(HSD_LOCKTIME_MULTIPLIER)
815            .ok_or(SwapError::ArithmeticOverflow)?;
816        Ok(threshold < parent_median_time)
817    }
818}
819
820pub fn create_lock_script(public_key: &[u8; 33]) -> [u8; SWAP_LOCK_SCRIPT_SIZE] {
821    let mut script = [0_u8; SWAP_LOCK_SCRIPT_SIZE];
822    script[0] = OP_TYPE;
823    script[1] = OP_9;
824    script[2] = OP_EQUAL;
825    script[3] = OP_IF;
826    script[4] = 33;
827    script[5..38].copy_from_slice(public_key);
828    script[38] = OP_CHECKSIG;
829    script[39] = OP_ELSE;
830    script[40] = OP_TYPE;
831    script[41] = OP_10;
832    script[42] = OP_EQUAL;
833    script[43] = OP_ENDIF;
834    script
835}
836
837pub fn lock_script_hash(public_key: &[u8; 33]) -> [u8; 32] {
838    let script = create_lock_script(public_key);
839    let mut hasher = Sha3_256::new();
840    Digest::update(&mut hasher, script);
841    hasher.finalize().into()
842}
843
844pub fn encode_time_lock(seconds: u64) -> Result<u32, SwapError> {
845    if seconds >= MAX_HSD_TIME_LOCK {
846        return Err(SwapError::LockTimeOutOfRange(seconds));
847    }
848    let units = u32::try_from(seconds / HSD_LOCKTIME_MULTIPLIER)
849        .map_err(|_| SwapError::LockTimeOutOfRange(seconds))?;
850    Ok(LOCKTIME_FLAG | units)
851}
852
853/// Encode a safety deadline so the represented HSD median time is never
854/// earlier than `seconds`.
855///
856/// This ceiling conversion is intentionally distinct from
857/// [`encode_time_lock`], whose floor conversion preserves Shakedex v2 wire
858/// compatibility.
859pub fn encode_time_lock_not_before(seconds: u64) -> Result<HsdTimeLock, SwapError> {
860    if seconds == 0 || seconds >= MAX_HSD_TIME_LOCK {
861        return Err(SwapError::LockTimeOutOfRange(seconds));
862    }
863    let units = seconds
864        .checked_add(HSD_LOCKTIME_MULTIPLIER - 1)
865        .ok_or(SwapError::ArithmeticOverflow)?
866        / HSD_LOCKTIME_MULTIPLIER;
867    if units > u64::from(LOCKTIME_MASK) {
868        return Err(SwapError::LockTimeOutOfRange(seconds));
869    }
870    let units = u32::try_from(units).map_err(|_| SwapError::LockTimeOutOfRange(seconds))?;
871    Ok(HsdTimeLock {
872        encoded: LOCKTIME_FLAG | units,
873        effective_time_seconds: u64::from(units)
874            .checked_mul(HSD_LOCKTIME_MULTIPLIER)
875            .ok_or(SwapError::ArithmeticOverflow)?,
876    })
877}
878
879#[derive(Clone, Copy, Debug, Eq, PartialEq)]
880pub struct DutchStep {
881    pub price: Dollarydoos,
882    pub lock_time_seconds: u64,
883}
884
885pub fn canonical_reverse_dutch_schedule(
886    start_price: Dollarydoos,
887    end_price: Dollarydoos,
888    start_time_seconds: u64,
889    end_time_seconds: u64,
890    steps: usize,
891) -> Result<Vec<DutchStep>, SwapError> {
892    if !(2..=MAX_AUCTION_STEPS).contains(&steps) {
893        return Err(SwapError::InvalidStepCount(steps));
894    }
895    if start_price < end_price || end_price.get() == 0 {
896        return Err(SwapError::InvalidPriceSchedule);
897    }
898    if start_time_seconds >= end_time_seconds
899        || start_time_seconds % HSD_LOCKTIME_MULTIPLIER != 0
900        || end_time_seconds % HSD_LOCKTIME_MULTIPLIER != 0
901    {
902        return Err(SwapError::InvalidLockSchedule);
903    }
904    let intervals = u64::try_from(steps - 1).map_err(|_| SwapError::ArithmeticOverflow)?;
905    let duration = end_time_seconds - start_time_seconds;
906    if duration / HSD_LOCKTIME_MULTIPLIER < intervals {
907        return Err(SwapError::InvalidLockSchedule);
908    }
909    let price_delta = start_price.get() - end_price.get();
910    let mut schedule = Vec::with_capacity(steps);
911    for index in 0..steps {
912        let index = u64::try_from(index).map_err(|_| SwapError::ArithmeticOverflow)?;
913        let lock_units = (start_time_seconds / HSD_LOCKTIME_MULTIPLIER)
914            + (duration / HSD_LOCKTIME_MULTIPLIER)
915                .checked_mul(index)
916                .ok_or(SwapError::ArithmeticOverflow)?
917                / intervals;
918        let price_reduction =
919            u64::try_from(u128::from(price_delta) * u128::from(index) / u128::from(intervals))
920                .map_err(|_| SwapError::ArithmeticOverflow)?;
921        schedule.push(DutchStep {
922            price: Dollarydoos::new(start_price.get() - price_reduction),
923            lock_time_seconds: lock_units
924                .checked_mul(HSD_LOCKTIME_MULTIPLIER)
925                .ok_or(SwapError::ArithmeticOverflow)?,
926        });
927    }
928    if schedule.first().map(|step| step.price) != Some(start_price)
929        || schedule.last().map(|step| step.price) != Some(end_price)
930        || schedule.first().map(|step| step.lock_time_seconds) != Some(start_time_seconds)
931        || schedule.last().map(|step| step.lock_time_seconds) != Some(end_time_seconds)
932    {
933        return Err(SwapError::NonCanonicalSchedule);
934    }
935    for pair in schedule.windows(2) {
936        if pair[0].price < pair[1].price
937            || encode_time_lock(pair[0].lock_time_seconds)?
938                >= encode_time_lock(pair[1].lock_time_seconds)?
939        {
940            return Err(SwapError::NonCanonicalSchedule);
941        }
942    }
943    Ok(schedule)
944}
945
946#[derive(Clone, Debug, Eq, PartialEq)]
947pub struct DutchAuction {
948    proofs: Vec<SwapProof>,
949}
950
951impl DutchAuction {
952    pub fn new(proofs: Vec<SwapProof>) -> Result<Self, SwapError> {
953        if proofs.is_empty() || proofs.len() > MAX_AUCTION_STEPS {
954            return Err(SwapError::InvalidStepCount(proofs.len()));
955        }
956        let first = &proofs[0];
957        first.validate()?;
958        let mut bundle_size = 0_usize;
959        for proof in &proofs {
960            proof.validate()?;
961            if proof.signature.is_none() {
962                return Err(SwapError::UnsignedProof);
963            }
964            if proof.network != first.network
965                || proof.locking_outpoint != first.locking_outpoint
966                || proof.name != first.name
967                || proof.seller_public_key != first.seller_public_key
968                || proof.payment_address != first.payment_address
969                || proof.fee_address != first.fee_address
970            {
971                return Err(SwapError::InconsistentAuction);
972            }
973            bundle_size = bundle_size
974                .checked_add(proof.encode()?.len())
975                .ok_or(SwapError::ArithmeticOverflow)?;
976            if bundle_size > MAX_AUCTION_BUNDLE_SIZE {
977                return Err(SwapError::BundleTooLarge(bundle_size));
978            }
979        }
980        for pair in proofs.windows(2) {
981            if pair[0].price < pair[1].price
982                || encode_time_lock(pair[0].lock_time_seconds)?
983                    >= encode_time_lock(pair[1].lock_time_seconds)?
984            {
985                return Err(SwapError::NonCanonicalSchedule);
986            }
987        }
988        Ok(Self { proofs })
989    }
990
991    pub fn new_verified(
992        proofs: Vec<SwapProof>,
993        expected_network: NetworkBinding,
994        locking_coin: &Coin,
995    ) -> Result<Self, SwapError> {
996        let auction = Self::new(proofs)?;
997        auction.verify_all_for_network(expected_network, locking_coin)?;
998        Ok(auction)
999    }
1000
1001    pub fn proofs(&self) -> &[SwapProof] {
1002        &self.proofs
1003    }
1004
1005    pub fn best_executable(
1006        &self,
1007        parent_median_time: u64,
1008    ) -> Result<Option<&SwapProof>, SwapError> {
1009        for proof in self.proofs.iter().rev() {
1010            if proof.is_executable(parent_median_time)? {
1011                return Ok(Some(proof));
1012            }
1013        }
1014        Ok(None)
1015    }
1016
1017    pub fn verify_all_for_network(
1018        &self,
1019        expected_network: NetworkBinding,
1020        locking_coin: &Coin,
1021    ) -> Result<(), SwapError> {
1022        for proof in &self.proofs {
1023            proof.verify_for_network(expected_network, locking_coin)?;
1024        }
1025        Ok(())
1026    }
1027}
1028
1029fn verify_locking_coin(proof: &SwapProof, coin: &Coin) -> Result<(), SwapError> {
1030    proof.lock_descriptor()?.verify_locking_coin(coin)
1031}
1032
1033fn transfer_recipient(
1034    transfer: &Output,
1035    proof: &SwapProof,
1036    locking_coin: &Coin,
1037) -> Result<Address, SwapError> {
1038    let transfer_fields = TransferCovenant::try_from(&transfer.covenant).map_err(|_| {
1039        SwapError::InvalidShakedexFulfillment("TRANSFER covenant does not bind the locked name")
1040    })?;
1041    let locking_finalize = FinalizeCovenant::try_from(&locking_coin.covenant)
1042        .map_err(|_| SwapError::InvalidShakedexLockingCovenant)?;
1043    if transfer_fields.name_hash != hash_name(&proof.name)?
1044        || transfer_fields.name_hash != locking_finalize.name_hash
1045        || transfer_fields.start_height != locking_finalize.start_height
1046    {
1047        return Err(SwapError::InvalidShakedexFulfillment(
1048            "TRANSFER covenant does not bind the locked name",
1049        ));
1050    }
1051    Ok(Address::new(
1052        transfer_fields.recipient_version,
1053        transfer_fields.recipient_hash,
1054    )?)
1055}
1056
1057fn verify_seller_signature(
1058    proof: &SwapProof,
1059    transaction: &Transaction,
1060    locking_coin: &Coin,
1061) -> Result<(), SwapError> {
1062    let encoded_signature = proof.signature.ok_or(SwapError::UnsignedProof)?;
1063    let signature =
1064        Signature::from_slice(&encoded_signature[..64]).map_err(|_| SwapError::InvalidSignature)?;
1065    if signature != signature.normalize_s() {
1066        return Err(SwapError::HighSignature);
1067    }
1068    let public_key = VerifyingKey::from_sec1_bytes(&proof.seller_public_key)
1069        .map_err(|_| SwapError::InvalidPublicKey)?;
1070    public_key
1071        .verify_prehash(
1072            &proof.seller_signature_hash(transaction, locking_coin)?,
1073            &signature,
1074        )
1075        .map_err(|_| SwapError::InvalidSignature)
1076}
1077
1078fn validate_shakedex_signature(
1079    encoded: &[u8; COMPACT_SIGNATURE_SIZE],
1080    expected_hash_type: u8,
1081) -> Result<Signature, SwapError> {
1082    if encoded[64] != expected_hash_type {
1083        return Err(SwapError::WrongShakedexSpendHashType {
1084            actual: encoded[64],
1085            expected: expected_hash_type,
1086        });
1087    }
1088    let signature =
1089        Signature::from_slice(&encoded[..64]).map_err(|_| SwapError::InvalidSignature)?;
1090    if signature != signature.normalize_s() {
1091        return Err(SwapError::HighSignature);
1092    }
1093    Ok(signature)
1094}
1095
1096fn verify_recovery_layout(
1097    descriptor: &ShakedexLockDescriptor,
1098    transaction: &Transaction,
1099    locking_coin: &Coin,
1100    recovery_recipient: &Address,
1101    require_witness: bool,
1102) -> Result<(), SwapError> {
1103    descriptor.verify_locking_coin(locking_coin)?;
1104    recovery_recipient.validate()?;
1105    if transaction.version != 0 || transaction.locktime != 0 || transaction.inputs.len() < 2 {
1106        return Err(SwapError::InvalidShakedexRecovery(
1107            "transaction header or funding layout differs",
1108        ));
1109    }
1110    let seller_input = &transaction.inputs[0];
1111    if seller_input.previous_output != locking_coin.outpoint || seller_input.sequence != u32::MAX {
1112        return Err(SwapError::InvalidShakedexRecovery(
1113            "seller input is not canonical index zero",
1114        ));
1115    }
1116    if transaction.inputs[1..]
1117        .iter()
1118        .any(|input| input.previous_output == locking_coin.outpoint)
1119    {
1120        return Err(SwapError::DuplicateShakedexSellerInput);
1121    }
1122    if require_witness {
1123        let [_, witness_script] = seller_input.witness.items.as_slice() else {
1124            return Err(SwapError::InvalidShakedexRecovery(
1125                "seller witness layout differs",
1126            ));
1127        };
1128        if witness_script.as_slice() != create_lock_script(&descriptor.seller_public_key).as_slice()
1129        {
1130            return Err(SwapError::InvalidShakedexRecovery(
1131                "seller witness script differs",
1132            ));
1133        }
1134    } else if !seller_input.witness.items.is_empty() {
1135        let [_, witness_script] = seller_input.witness.items.as_slice() else {
1136            return Err(SwapError::InvalidShakedexRecovery(
1137                "seller witness is neither absent nor canonical",
1138            ));
1139        };
1140        if witness_script.as_slice() != create_lock_script(&descriptor.seller_public_key).as_slice()
1141        {
1142            return Err(SwapError::InvalidShakedexRecovery(
1143                "seller witness script differs",
1144            ));
1145        }
1146    }
1147    let transfer = transaction
1148        .outputs
1149        .first()
1150        .ok_or(SwapError::InvalidShakedexRecovery(
1151            "recovery TRANSFER output is missing",
1152        ))?;
1153    if transfer != &build_transfer_output(locking_coin, recovery_recipient)? {
1154        return Err(SwapError::InvalidShakedexRecovery(
1155            "recovery TRANSFER output differs",
1156        ));
1157    }
1158    Ok(())
1159}
1160
1161fn encode_address(address: &Address, encoder: &mut Encoder) {
1162    encoder.put_u8(address.version);
1163    encoder.put_u8(address.hash.len() as u8);
1164    encoder.put_bytes(&address.hash);
1165}
1166
1167fn decode_address(decoder: &mut Decoder<'_>) -> Result<Address, SwapError> {
1168    let version = decoder.read_u8()?;
1169    let length = usize::from(decoder.read_u8()?);
1170    let hash = decoder.read_bounded_vec(length, 40)?;
1171    Ok(Address::new(version, hash)?)
1172}
1173
1174pub(crate) fn blake2b_256(input: &[u8]) -> [u8; 32] {
1175    let mut hasher = Blake2bVar::new(32).expect("valid BLAKE2b output length");
1176    hasher.update(input);
1177    let mut output = [0_u8; 32];
1178    hasher
1179        .finalize_variable(&mut output)
1180        .expect("valid BLAKE2b output buffer");
1181    output
1182}
1183
1184#[derive(Debug, Error)]
1185pub enum SwapError {
1186    #[error(transparent)]
1187    Decode(#[from] hns_encoding::DecodeError),
1188    #[error(transparent)]
1189    Covenant(#[from] hns_covenants::CovenantError),
1190    #[error(transparent)]
1191    Script(#[from] hns_script::ScriptError),
1192    #[error(transparent)]
1193    Transaction(#[from] hns_transaction::TransactionError),
1194    #[error(transparent)]
1195    NameTransaction(#[from] hns_transaction::NameTransactionError),
1196    #[error("unsupported swap proof version {0}")]
1197    UnsupportedVersion(u16),
1198    #[error("swap proof is {0} bytes, exceeding the configured bound")]
1199    ProofTooLarge(usize),
1200    #[error("auction bundle is {0} bytes, exceeding the configured bound")]
1201    BundleTooLarge(usize),
1202    #[error("invalid presence flag for {0}")]
1203    InvalidPresenceFlag(&'static str),
1204    #[error("invalid Handshake name")]
1205    InvalidName,
1206    #[error("invalid compressed secp256k1 public key")]
1207    InvalidPublicKey,
1208    #[error("price must be nonzero")]
1209    ZeroPrice,
1210    #[error("fee and fee address are inconsistent")]
1211    InvalidFee,
1212    #[error("lock time {0} seconds is outside HSD's 40-bit time range")]
1213    LockTimeOutOfRange(u64),
1214    #[error("seller signature uses hash type 0x{0:02x}, expected 0x84")]
1215    WrongSellerHashType(u8),
1216    #[error("swap proof is unsigned")]
1217    UnsignedProof,
1218    #[error("swap proof is bound to a different Handshake network")]
1219    NetworkMismatch,
1220    #[error("signing key does not match the advertised seller public key")]
1221    SigningKeyMismatch,
1222    #[error("signature operation failed")]
1223    SignatureFailure,
1224    #[error("invalid seller signature")]
1225    InvalidSignature,
1226    #[error("high-S seller signature is noncanonical")]
1227    HighSignature,
1228    #[error("locking coin outpoint differs from the proof")]
1229    OutpointMismatch,
1230    #[error("Shakedex locking outpoint is HSD's null outpoint")]
1231    NullShakedexLockingOutpoint,
1232    #[error("Shakedex locking coin cannot be a coinbase output")]
1233    CoinbaseShakedexLockingCoin,
1234    #[error("locking coin is not a FINALIZE covenant")]
1235    LockingCoinNotFinalize,
1236    #[error("locking coin name differs from the proof")]
1237    NameMismatch,
1238    #[error("locking coin name hash differs from the proof")]
1239    NameHashMismatch,
1240    #[error("locking coin is not committed to the canonical swap script")]
1241    LockScriptMismatch,
1242    #[error("Shakedex fulfillment requires at least one buyer funding input")]
1243    MissingShakedexBuyerInputs,
1244    #[error("Shakedex recovery requires at least one external funding input")]
1245    MissingShakedexRecoveryFundingInputs,
1246    #[error("Shakedex transfer repeats the seller locking outpoint")]
1247    DuplicateShakedexSellerInput,
1248    #[error("Shakedex locking coin has a malformed FINALIZE covenant")]
1249    InvalidShakedexLockingCovenant,
1250    #[error("invalid canonical Shakedex fulfillment: {0}")]
1251    InvalidShakedexFulfillment(&'static str),
1252    #[error("transaction is not a canonical Shakedex fulfillment or recovery")]
1253    UnrecognizedShakedexSpend,
1254    #[error("Shakedex recovery classification requires an explicit expected recipient")]
1255    MissingShakedexRecoveryRecipient,
1256    #[error("invalid canonical Shakedex recovery: {0}")]
1257    InvalidShakedexRecovery(&'static str),
1258    #[error("Shakedex spend signature hash type is 0x{actual:02x}; expected 0x{expected:02x}")]
1259    WrongShakedexSpendHashType { actual: u8, expected: u8 },
1260    #[error("auction step count {0} is outside its bound")]
1261    InvalidStepCount(usize),
1262    #[error("reverse-Dutch prices are invalid")]
1263    InvalidPriceSchedule,
1264    #[error("reverse-Dutch lock times are invalid")]
1265    InvalidLockSchedule,
1266    #[error("reverse-Dutch schedule is not canonical")]
1267    NonCanonicalSchedule,
1268    #[error("auction steps do not describe the same listing")]
1269    InconsistentAuction,
1270    #[error("fixed-price listing sequence must be nonzero")]
1271    ZeroListingSequence,
1272    #[error("fixed-price listing version {0} is unsupported")]
1273    UnsupportedListingVersion(u16),
1274    #[error("fixed-price listing expiration must be later than its creation time")]
1275    InvalidListingLifetime,
1276    #[error("fixed-price listing is {0} bytes, exceeding the configured bound")]
1277    ListingTooLarge(usize),
1278    #[error("fixed-price listing must contain a signed Shakedex presign")]
1279    UnsignedListingProof,
1280    #[error("fixed-price listing is unsigned")]
1281    UnsignedListing,
1282    #[error("fixed-price listing hash does not match its canonical contents")]
1283    ListingHashMismatch,
1284    #[error("fixed-price listing has not reached its creation time")]
1285    ListingNotYetActive,
1286    #[error("fixed-price listing has expired")]
1287    ListingExpired,
1288    #[error("listing cancellation sequence must be nonzero")]
1289    ZeroCancellationSequence,
1290    #[error("listing cancellation version {0} is unsupported")]
1291    UnsupportedCancellationVersion(u16),
1292    #[error("listing cancellation expiration must be later than its creation time")]
1293    InvalidCancellationLifetime,
1294    #[error("listing cancellation is {0} bytes, exceeding the configured bound")]
1295    CancellationTooLarge(usize),
1296    #[error("listing cancellation is unsigned")]
1297    UnsignedCancellation,
1298    #[error("listing cancellation hash does not match its canonical contents")]
1299    CancellationHashMismatch,
1300    #[error("listing cancellation does not identify the supplied listing")]
1301    CancellationListingMismatch,
1302    #[error("listing cancellation sequence is not newer than the listing sequence")]
1303    CancellationSequenceNotNewer,
1304    #[error("listing cancellation expires before the listing")]
1305    CancellationExpiresTooEarly,
1306    #[error("listing cancellation has not reached its creation time")]
1307    CancellationNotYetActive,
1308    #[error("listing cancellation has expired")]
1309    CancellationExpired,
1310    #[error("marketplace signature has noncanonical high-S form")]
1311    HighMarketplaceSignature,
1312    #[error("HTLC descriptor version {0} is unsupported")]
1313    UnsupportedHtlcVersion(u16),
1314    #[error("HNS HTLC descriptor is {0} bytes, exceeding the configured bound")]
1315    HtlcTooLarge(usize),
1316    #[error("HNS HTLC value must be nonzero")]
1317    ZeroHtlcValue,
1318    #[error("HNS HTLC hashlock must be nonzero")]
1319    ZeroHtlcHashlock,
1320    #[error("HNS HTLC receiver and refund public keys must be distinct")]
1321    HtlcKeyReuse,
1322    #[error("HNS HTLC refund locktime must be nonzero")]
1323    ZeroHtlcRefundLocktime,
1324    #[error("HNS HTLC funding output has the wrong value")]
1325    HtlcValueMismatch,
1326    #[error("HNS HTLC funding output has the wrong script address")]
1327    HtlcAddressMismatch,
1328    #[error("HNS HTLC funding output must use the NONE covenant")]
1329    HtlcCovenantMismatch,
1330    #[error("HNS HTLC funding output index {requested} is outside {outputs} outputs")]
1331    HtlcFundingOutputIndex { requested: usize, outputs: usize },
1332    #[error("HNS HTLC spend input index {requested} is outside {inputs} inputs")]
1333    HtlcSpendInputIndex { requested: usize, inputs: usize },
1334    #[error("HNS HTLC spend input does not reference the supplied funding coin")]
1335    HtlcOutpointMismatch,
1336    #[error("HNS HTLC witness signature uses invalid hash type 0x{0:02x}")]
1337    InvalidHtlcSignatureHashType(u8),
1338    #[error("HNS HTLC witness signature is malformed")]
1339    InvalidHtlcSignature,
1340    #[error("HNS HTLC witness signature has noncanonical high-S form")]
1341    HighHtlcSignature,
1342    #[error("HNS HTLC preimage does not match the descriptor hashlock")]
1343    HtlcPreimageMismatch,
1344    #[error("HNS HTLC witness does not have a canonical redeem or refund layout")]
1345    InvalidHtlcWitness,
1346    #[error("arithmetic overflow")]
1347    ArithmeticOverflow,
1348}
1349
1350#[cfg(test)]
1351mod tests {
1352    use hns_covenants::NameState;
1353    use hns_primitives::Height;
1354    use hns_script::{K256SignatureVerifier, ScriptFlags, verify_witness_program};
1355    use hns_transaction::{build_finalize_transaction, verify_finalize_at_index_zero};
1356
1357    use super::*;
1358
1359    const PROTOCOL_V1_FIXTURES: &str = include_str!("../fixtures/protocol-v1/hns-swap-v1.txt");
1360
1361    fn fixture_bytes(name: &str) -> Vec<u8> {
1362        let value = PROTOCOL_V1_FIXTURES
1363            .lines()
1364            .filter_map(|line| line.split_once('='))
1365            .find_map(|(key, value)| (key == name).then_some(value))
1366            .unwrap_or_else(|| panic!("missing fixture {name}"));
1367        hex::decode(value).expect("fixture hex")
1368    }
1369
1370    fn fixture_address(name: &str) -> Address {
1371        let encoded = fixture_bytes(name);
1372        let length = usize::from(encoded[1]);
1373        assert_eq!(encoded.len(), length + 2);
1374        Address::new(encoded[0], encoded[2..].to_vec()).expect("fixture address")
1375    }
1376
1377    fn unsigned_proof(signing_key: &SigningKey) -> SwapProof {
1378        let public_key = signing_key.verifying_key().to_sec1_point(true);
1379        SwapProof {
1380            network: NetworkBinding {
1381                magic: 0x5b6e_c393,
1382                genesis: BlockHash::new([0x11; 32]),
1383            },
1384            locking_outpoint: Outpoint {
1385                transaction_hash: TransactionHash::new([0x22; 32]),
1386                index: 3,
1387            },
1388            name: b"handshake".to_vec(),
1389            seller_public_key: public_key.as_bytes().try_into().expect("33 bytes"),
1390            payment_address: Address::new(0, vec![0x33; 20]).expect("address"),
1391            price: Dollarydoos::new(1_000_000),
1392            lock_time_seconds: 512,
1393            signature: None,
1394            fee_address: None,
1395            fee: Dollarydoos::new(0),
1396        }
1397    }
1398
1399    fn locking_coin(proof: &SwapProof) -> Coin {
1400        Coin {
1401            outpoint: proof.locking_outpoint,
1402            value: Dollarydoos::new(42),
1403            height: Height::new(10),
1404            coinbase: false,
1405            address: Address::new(0, lock_script_hash(&proof.seller_public_key).to_vec())
1406                .expect("address"),
1407            covenant: FinalizeCovenant::new(
1408                proof.name.clone(),
1409                Height::new(1),
1410                false,
1411                Height::new(0),
1412                0,
1413                BlockHash::new([0x44; 32]),
1414            )
1415            .expect("finalize")
1416            .to_covenant()
1417            .expect("covenant"),
1418        }
1419    }
1420
1421    #[test]
1422    fn shakedex_v2_script_layout_and_seller_signature_verify() {
1423        let signing_key = SigningKey::from_slice(&[7; 32]).expect("key");
1424        let mut proof = unsigned_proof(&signing_key);
1425        let expected = format!(
1426            "d059876321{}ac67d05a8768",
1427            hex::encode(proof.seller_public_key)
1428        );
1429        assert_eq!(
1430            hex::encode(create_lock_script(&proof.seller_public_key)),
1431            expected
1432        );
1433        let coin = locking_coin(&proof);
1434        let descriptor = ShakedexLockDescriptor::from_locking_coin(
1435            proof.network,
1436            &coin,
1437            proof.seller_public_key,
1438        )
1439        .expect("discovered lock descriptor");
1440        assert!(matches!(
1441            ShakedexLockDescriptor::new(
1442                proof.network,
1443                Outpoint::NULL,
1444                proof.name.clone(),
1445                proof.seller_public_key,
1446            ),
1447            Err(SwapError::NullShakedexLockingOutpoint)
1448        ));
1449        let mut coinbase_lock = coin.clone();
1450        coinbase_lock.coinbase = true;
1451        assert!(matches!(
1452            ShakedexLockDescriptor::from_locking_coin(
1453                proof.network,
1454                &coinbase_lock,
1455                proof.seller_public_key,
1456            ),
1457            Err(SwapError::CoinbaseShakedexLockingCoin)
1458        ));
1459        assert_eq!(
1460            descriptor,
1461            proof.lock_descriptor().expect("proof descriptor")
1462        );
1463        assert_eq!(
1464            descriptor
1465                .finalize_witness()
1466                .expect("FINALIZE witness")
1467                .items,
1468            vec![create_lock_script(&proof.seller_public_key).to_vec()]
1469        );
1470        proof.sign(&coin, &signing_key).expect("signed proof");
1471        proof.verify(&coin).expect("valid proof");
1472        let encoded = proof.encode().expect("encoded");
1473        assert_eq!(SwapProof::decode(&encoded).expect("decoded"), proof);
1474        assert_ne!(proof.offer_id().expect("offer"), OfferId::default());
1475
1476        let mut tampered = proof.clone();
1477        tampered.price = Dollarydoos::new(proof.price.get() + 1);
1478        assert!(tampered.verify(&coin).is_err());
1479    }
1480
1481    #[test]
1482    fn exact_v1_shakedex_fulfillment_and_recovery_vectors_are_consumed() {
1483        let proof = SwapProof::decode(&fixture_bytes("swap_proof")).expect("swap proof fixture");
1484        assert_eq!(
1485            proof.encode().expect("swap proof encoding"),
1486            fixture_bytes("swap_proof")
1487        );
1488        assert_eq!(
1489            proof.offer_id().expect("offer id").as_bytes().as_slice(),
1490            fixture_bytes("swap_proof_offer_id").as_slice()
1491        );
1492        let coin = locking_coin(&proof);
1493        proof.verify(&coin).expect("fixture seller presign");
1494
1495        let presigned = Transaction::decode(&fixture_bytes("swap_proof_presigned_transaction"))
1496            .expect("presigned transaction fixture");
1497        assert_eq!(
1498            proof
1499                .seller_signature_hash(&presigned, &coin)
1500                .expect("seller sighash")
1501                .as_slice(),
1502            fixture_bytes("swap_proof_seller_sighash").as_slice()
1503        );
1504        assert_eq!(
1505            presigned
1506                .transaction_hash()
1507                .expect("presigned txid")
1508                .as_bytes()
1509                .as_slice(),
1510            fixture_bytes("swap_proof_presigned_txid").as_slice()
1511        );
1512
1513        let buyer_input = Input {
1514            previous_output: Outpoint {
1515                transaction_hash: TransactionHash::new([0x66; 32]),
1516                index: 1,
1517            },
1518            sequence: u32::MAX,
1519            witness: Witness::default(),
1520        };
1521        let buyer_output = Output {
1522            value: Dollarydoos::new(2_000_000),
1523            address: Address::new(0, vec![0x77; 20]).expect("buyer change"),
1524            covenant: Covenant::default(),
1525        };
1526        let fulfillment = proof
1527            .fulfillment_transaction(
1528                &coin,
1529                &fixture_address("fulfillment_recipient_address"),
1530                vec![buyer_input.clone()],
1531                vec![buyer_output.clone()],
1532            )
1533            .expect("canonical fulfillment");
1534        assert_eq!(
1535            fulfillment.encode().expect("fulfillment encoding"),
1536            fixture_bytes("fulfillment_transaction")
1537        );
1538        assert_eq!(
1539            fulfillment
1540                .transaction_hash()
1541                .expect("fulfillment txid")
1542                .as_bytes()
1543                .as_slice(),
1544            fixture_bytes("fulfillment_txid").as_slice()
1545        );
1546        assert_eq!(
1547            proof
1548                .classify_spend(&fulfillment, &coin, None)
1549                .expect("fulfillment classification"),
1550            ShakedexSpendKind::Fulfillment
1551        );
1552
1553        let recovery_recipient = fixture_address("recovery_recipient_address");
1554        assert!(matches!(
1555            proof.recovery_transaction(&coin, &recovery_recipient, Vec::new(), Vec::new()),
1556            Err(SwapError::MissingShakedexRecoveryFundingInputs)
1557        ));
1558        let mut recovery = proof
1559            .recovery_transaction(
1560                &coin,
1561                &recovery_recipient,
1562                vec![buyer_input],
1563                vec![buyer_output],
1564            )
1565            .expect("canonical recovery");
1566        let exact_recovery = Transaction::decode(&fixture_bytes("recovery_transaction"))
1567            .expect("recovery transaction fixture");
1568        recovery.inputs[0].witness = exact_recovery.inputs[0].witness.clone();
1569        assert_eq!(recovery, exact_recovery);
1570        assert_eq!(
1571            proof
1572                .recovery_signature_hash(&recovery, &coin, &recovery_recipient)
1573                .expect("recovery sighash")
1574                .as_slice(),
1575            fixture_bytes("recovery_sighash").as_slice()
1576        );
1577        assert_eq!(
1578            recovery
1579                .transaction_hash()
1580                .expect("recovery txid")
1581                .as_bytes()
1582                .as_slice(),
1583            fixture_bytes("recovery_txid").as_slice()
1584        );
1585        assert_eq!(
1586            proof
1587                .classify_spend(&recovery, &coin, Some(&recovery_recipient))
1588                .expect("recovery classification"),
1589            ShakedexSpendKind::Recovery
1590        );
1591
1592        let transfer_coin = Coin {
1593            outpoint: Outpoint {
1594                transaction_hash: recovery
1595                    .transaction_hash()
1596                    .expect("recovery transaction hash"),
1597                index: 0,
1598            },
1599            value: recovery.outputs[0].value,
1600            height: Height::new(20),
1601            coinbase: false,
1602            address: recovery.outputs[0].address.clone(),
1603            covenant: recovery.outputs[0].covenant.clone(),
1604        };
1605        let mut state = NameState::null(hash_name(&proof.name).expect("name hash"));
1606        state.name = proof.name.clone();
1607        state.height = Height::new(1);
1608        state.owner = transfer_coin.outpoint;
1609        state.value = transfer_coin.value;
1610        state.transfer = transfer_coin.height;
1611        state.registered = true;
1612        let renewal_block = BlockHash::new([0x99; 32]);
1613        let descriptor = proof.lock_descriptor().expect("lock descriptor");
1614        let mut finalize = build_finalize_transaction(
1615            &transfer_coin,
1616            &state,
1617            renewal_block,
1618            Vec::new(),
1619            Vec::new(),
1620        )
1621        .expect("recovery FINALIZE");
1622        finalize.inputs[0].witness = descriptor.finalize_witness().expect("FINALIZE witness");
1623        assert_eq!(
1624            finalize.encode().expect("FINALIZE encoding"),
1625            fixture_bytes("recovery_finalize_transaction")
1626        );
1627        assert_eq!(
1628            finalize
1629                .witness_encode()
1630                .expect("FINALIZE witness encoding"),
1631            fixture_bytes("recovery_finalize_witness")
1632        );
1633        assert_eq!(
1634            finalize
1635                .transaction_hash()
1636                .expect("FINALIZE transaction hash")
1637                .as_bytes()
1638                .as_slice(),
1639            fixture_bytes("recovery_finalize_txid").as_slice()
1640        );
1641        verify_finalize_at_index_zero(&finalize, &transfer_coin, &state, renewal_block)
1642            .expect("canonical recovery FINALIZE");
1643        verify_witness_program(
1644            &finalize,
1645            0,
1646            &transfer_coin,
1647            ScriptFlags::STANDARD,
1648            &K256SignatureVerifier,
1649        )
1650        .expect("Shakedex FINALIZE branch");
1651
1652        let mut wrong_renewal = finalize.clone();
1653        wrong_renewal.outputs[0].covenant.items[6][0] ^= 1;
1654        assert!(
1655            verify_finalize_at_index_zero(&wrong_renewal, &transfer_coin, &state, renewal_block,)
1656                .is_err()
1657        );
1658        let mut wrong_script = finalize.clone();
1659        wrong_script.inputs[0].witness.items[0][0] ^= 1;
1660        assert_eq!(
1661            wrong_script
1662                .transaction_hash()
1663                .expect("same transaction hash"),
1664            finalize
1665                .transaction_hash()
1666                .expect("FINALIZE transaction hash")
1667        );
1668        assert!(
1669            verify_witness_program(
1670                &wrong_script,
1671                0,
1672                &transfer_coin,
1673                ScriptFlags::STANDARD,
1674                &K256SignatureVerifier,
1675            )
1676            .is_err()
1677        );
1678        let mut extra_witness_item = finalize.clone();
1679        extra_witness_item.inputs[0]
1680            .witness
1681            .items
1682            .insert(0, Vec::new());
1683        assert!(
1684            verify_witness_program(
1685                &extra_witness_item,
1686                0,
1687                &transfer_coin,
1688                ScriptFlags::STANDARD,
1689                &K256SignatureVerifier,
1690            )
1691            .is_err()
1692        );
1693
1694        let mut recovery_without_offer = proof.clone();
1695        recovery_without_offer.signature = None;
1696        recovery_without_offer.price = Dollarydoos::new(0);
1697        recovery_without_offer.lock_time_seconds = MAX_HSD_TIME_LOCK;
1698        recovery_without_offer.fee = Dollarydoos::new(1);
1699        recovery_without_offer.fee_address = None;
1700        recovery_without_offer
1701            .verify_recovery(&recovery, &coin, &recovery_recipient)
1702            .expect("seller recovery does not depend on listing terms or a presign");
1703        ShakedexLockDescriptor::from_locking_coin(proof.network, &coin, proof.seller_public_key)
1704            .expect("reconstructed descriptor")
1705            .verify_recovery(&recovery, &coin, &recovery_recipient)
1706            .expect("seller recovery does not depend on listing terms");
1707        assert!(matches!(
1708            proof.classify_spend(&recovery, &coin, None),
1709            Err(SwapError::MissingShakedexRecoveryRecipient)
1710        ));
1711    }
1712
1713    #[test]
1714    fn safety_time_encoding_uses_ceiling_while_shakedex_stays_wire_compatible() {
1715        assert_eq!(
1716            encode_time_lock(800).expect("Shakedex floor"),
1717            LOCKTIME_FLAG | 1
1718        );
1719        assert_eq!(
1720            encode_time_lock_not_before(800).expect("safety ceiling"),
1721            HsdTimeLock {
1722                encoded: LOCKTIME_FLAG | 2,
1723                effective_time_seconds: 1_024,
1724            }
1725        );
1726    }
1727
1728    #[test]
1729    fn lower_dutch_price_cannot_execute_before_its_locktime() {
1730        let schedule = canonical_reverse_dutch_schedule(
1731            Dollarydoos::new(100),
1732            Dollarydoos::new(10),
1733            10 * 512,
1734            20 * 512,
1735            3,
1736        )
1737        .expect("schedule");
1738        assert_eq!(schedule[0].price.get(), 100);
1739        assert_eq!(schedule[2].price.get(), 10);
1740        let signing_key = SigningKey::from_slice(&[8; 32]).expect("key");
1741        let mut proofs = Vec::new();
1742        for step in schedule {
1743            let mut proof = unsigned_proof(&signing_key);
1744            proof.price = step.price;
1745            proof.lock_time_seconds = step.lock_time_seconds;
1746            let coin = locking_coin(&proof);
1747            proof.sign(&coin, &signing_key).expect("signed proof");
1748            proofs.push(proof);
1749        }
1750        let coin = locking_coin(&proofs[0]);
1751        let auction =
1752            DutchAuction::new_verified(proofs, unsigned_proof(&signing_key).network, &coin)
1753                .expect("auction");
1754        assert!(auction.best_executable(10 * 512).expect("query").is_none());
1755        assert_eq!(
1756            auction
1757                .best_executable(10 * 512 + 1)
1758                .expect("query")
1759                .expect("first")
1760                .price
1761                .get(),
1762            100
1763        );
1764        assert_eq!(
1765            auction
1766                .best_executable(20 * 512)
1767                .expect("query")
1768                .expect("middle")
1769                .price
1770                .get(),
1771            55
1772        );
1773        assert_eq!(
1774            auction
1775                .best_executable(20 * 512 + 1)
1776                .expect("query")
1777                .expect("last")
1778                .price
1779                .get(),
1780            10
1781        );
1782    }
1783
1784    #[test]
1785    fn proof_parser_rejects_trailing_bytes_wrong_network_coin_and_high_s() {
1786        let signing_key = SigningKey::from_slice(&[9; 32]).expect("key");
1787        let mut proof = unsigned_proof(&signing_key);
1788        let coin = locking_coin(&proof);
1789        proof.sign(&coin, &signing_key).expect("signed proof");
1790        let mut encoded = proof.encode().expect("encoded");
1791        encoded.push(0);
1792        assert!(SwapProof::decode(&encoded).is_err());
1793
1794        let mut wrong_coin = coin.clone();
1795        wrong_coin.outpoint.index += 1;
1796        assert!(proof.verify(&wrong_coin).is_err());
1797
1798        let mut wrong_network = proof.clone();
1799        wrong_network.network.magic ^= 1;
1800        assert!(
1801            wrong_network
1802                .verify_for_network(proof.network, &coin)
1803                .is_err()
1804        );
1805        assert_ne!(
1806            proof.offer_id().expect("id"),
1807            wrong_network.offer_id().expect("id")
1808        );
1809    }
1810}