From 5770dbd39fc2f0f183ba8ea2674858d6701b9da3 Mon Sep 17 00:00:00 2001 From: Ava Chow Date: Mon, 22 Jul 2024 17:14:17 -0400 Subject: [PATCH] Add PSBT::ComputeLockTime() Function to compute the lock time for the transaction --- src/psbt.cpp | 40 +++++++++++++++++++++++++++++++++++++++- src/psbt.h | 1 + 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/psbt.cpp b/src/psbt.cpp index a87079610d6..6109d943182 100644 --- a/src/psbt.cpp +++ b/src/psbt.cpp @@ -61,11 +61,49 @@ bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt) return true; } +std::optional PartiallySignedTransaction::ComputeTimeLock() const +{ + if (GetVersion() >= 2) { + std::optional time_lock{0}; + std::optional height_lock{0}; + for (const PSBTInput& input : inputs) { + if (input.time_locktime.has_value() && !input.height_locktime.has_value()) { + height_lock.reset(); // Transaction can no longer have a height locktime + if (!time_lock.has_value()) { + return std::nullopt; + } + } else if (!input.time_locktime.has_value() && input.height_locktime.has_value()) { + time_lock.reset(); // Transaction can no longer have a time locktime + if (!height_lock.has_value()) { + return std::nullopt; + } + } + if (input.time_locktime && time_lock.has_value()) { + time_lock = std::max(time_lock, input.time_locktime); + } + if (input.height_locktime && height_lock.has_value()) { + height_lock = std::max(height_lock, input.height_locktime); + } + } + if (height_lock.has_value() && *height_lock > 0) { + return *height_lock; + } + if (time_lock.has_value() && *time_lock > 0) { + return *time_lock; + } + } + return fallback_locktime.value_or(0); +} + std::optional PartiallySignedTransaction::GetUnsignedTx() const { CMutableTransaction mtx; mtx.version = tx_version; - mtx.nLockTime = fallback_locktime.value_or(0); + std::optional locktime = ComputeTimeLock(); + if (!locktime) { + return std::nullopt; + } + mtx.nLockTime = *locktime; uint32_t max_sequence = CTxIn::SEQUENCE_FINAL; for (const PSBTInput& input : inputs) { CTxIn txin; diff --git a/src/psbt.h b/src/psbt.h index f46e625bce1..efb1ee1f109 100644 --- a/src/psbt.h +++ b/src/psbt.h @@ -1256,6 +1256,7 @@ public: [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt); bool AddInput(const PSBTInput& psbtin); bool AddOutput(const PSBTOutput& psbtout); + std::optional ComputeTimeLock() const; std::optional GetUnsignedTx() const; std::optional GetUniqueID() const; explicit PartiallySignedTransaction(const CMutableTransaction& tx);