| | 1 | | using NBitcoin; |
| | 2 | |
|
| | 3 | | namespace NLightning.Infrastructure.Bitcoin.Transactions; |
| | 4 | |
|
| | 5 | | using Comparers; |
| | 6 | | using Domain.Money; |
| | 7 | | using Domain.Protocol.Constants; |
| | 8 | | using Outputs; |
| | 9 | |
|
| | 10 | | public abstract class BaseTransaction |
| | 11 | | { |
| | 12 | | #region Private Fields |
| | 13 | | private readonly bool _hasAnchorOutput; |
| | 14 | | private readonly TransactionBuilder _builder; |
| 176 | 15 | | private readonly List<(Coin, Sequence)> _coins = []; |
| | 16 | |
|
| | 17 | | private Transaction _transaction; |
| | 18 | | #endregion |
| | 19 | |
|
| | 20 | | #region Protected Properties |
| 2620 | 21 | | protected List<BaseOutput> Outputs { get; private set; } = []; |
| 664 | 22 | | protected LightningMoney CalculatedFee { get; } = LightningMoney.Zero; |
| 936 | 23 | | protected bool Finalized { get; private set; } |
| 128 | 24 | | protected Transaction FinalizedTransaction => Finalized |
| 128 | 25 | | ? _transaction |
| 128 | 26 | | : throw new Exception("Transaction not finalized."); |
| | 27 | | #endregion |
| | 28 | |
|
| | 29 | | #region Public Properties |
| 988 | 30 | | public uint256 TxId { get; private set; } = uint256.Zero; |
| 104 | 31 | | public bool IsValid => Finalized |
| 104 | 32 | | ? _builder.Verify(_transaction) |
| 104 | 33 | | : throw new Exception("Transaction not finalized."); |
| | 34 | | #endregion |
| | 35 | |
|
| | 36 | | #region Constructors |
| | 37 | |
|
| 36 | 38 | | protected BaseTransaction(bool hasAnchorOutput, Network network, uint version, SigHash sigHash, params Coin[] coins) |
| | 39 | | { |
| 36 | 40 | | _hasAnchorOutput = hasAnchorOutput; |
| | 41 | |
|
| 36 | 42 | | _builder = network.CreateTransactionBuilder(); |
| 36 | 43 | | _builder.SetSigningOptions(sigHash, false); |
| 36 | 44 | | _builder.DustPrevention = false; |
| 36 | 45 | | _builder.SetVersion(version); |
| | 46 | |
|
| 72 | 47 | | _coins = coins.Select(c => (c, Sequence.Final)).ToList(); |
| | 48 | |
|
| 36 | 49 | | _transaction = Transaction.Create(network); |
| 36 | 50 | | _transaction.Version = version; |
| 72 | 51 | | _transaction.Inputs.AddRange(_coins.Select(c => new TxIn(c.Item1.Outpoint))); |
| 36 | 52 | | } |
| | 53 | |
|
| 140 | 54 | | protected BaseTransaction(bool hasAnchorOutput, Network network, uint version, SigHash sigHash, |
| 140 | 55 | | params (Coin, Sequence)[] coins) |
| | 56 | | { |
| 140 | 57 | | _hasAnchorOutput = hasAnchorOutput; |
| | 58 | |
|
| 140 | 59 | | _builder = network.CreateTransactionBuilder(); |
| 140 | 60 | | _builder.SetSigningOptions(sigHash, false); |
| 140 | 61 | | _builder.DustPrevention = false; |
| 140 | 62 | | _builder.SetVersion(version); |
| | 63 | |
|
| 140 | 64 | | _coins.AddRange(coins); |
| | 65 | |
|
| 140 | 66 | | _transaction = Transaction.Create(network); |
| 140 | 67 | | _transaction.Version = version; |
| 560 | 68 | | foreach (var (coin, sequence) in _coins) |
| | 69 | | { |
| 140 | 70 | | _transaction.Inputs.Add(coin.Outpoint, null, null, sequence); |
| | 71 | | } |
| | 72 | |
|
| 140 | 73 | | } |
| | 74 | | #endregion |
| | 75 | |
|
| | 76 | | #region Abstract Methods |
| | 77 | | internal abstract void ConstructTransaction(LightningMoney currentFeePerKw); |
| | 78 | | #endregion |
| | 79 | |
|
| | 80 | | #region Protected Methods |
| | 81 | | protected void SetLockTime(LockTime lockTime) |
| | 82 | | { |
| 136 | 83 | | _transaction.LockTime = lockTime; |
| 136 | 84 | | } |
| | 85 | |
|
| | 86 | | protected void SignTransaction(params BitcoinSecret[] secrets) |
| | 87 | | { |
| 132 | 88 | | ArgumentNullException.ThrowIfNull(secrets); |
| | 89 | |
|
| | 90 | | // Check if the output amount is greater than the input amount |
| 132 | 91 | | if (!CheckTransactionAmounts()) |
| 0 | 92 | | throw new InvalidOperationException("Output amount cannot exceed input amount."); |
| | 93 | |
|
| | 94 | | // Sign all inputs |
| 132 | 95 | | ArgumentNullException.ThrowIfNull(secrets); |
| | 96 | |
|
| 132 | 97 | | if (Finalized) |
| | 98 | | { |
| | 99 | | // Remove signature from inputs |
| 0 | 100 | | _transaction.Inputs.Clear(); |
| 0 | 101 | | foreach (var (coin, sequence) in _coins) |
| | 102 | | { |
| 0 | 103 | | _transaction.Inputs.Add(coin.Outpoint, null, null, sequence); |
| | 104 | | } |
| | 105 | | } |
| | 106 | | else |
| | 107 | | { |
| | 108 | | // Add our keys |
| 264 | 109 | | _builder.AddKeys(secrets.Select(ISecret (s) => s).ToArray()); |
| 264 | 110 | | _builder.AddCoins(_coins.Select(c => c.Item1)); |
| | 111 | | } |
| | 112 | |
|
| 132 | 113 | | _transaction = _builder.SignTransactionInPlace(_transaction); |
| | 114 | |
|
| 132 | 115 | | TxId = _transaction.GetHash(); |
| 132 | 116 | | Finalized = true; |
| 132 | 117 | | } |
| | 118 | |
|
| | 119 | | protected void CalculateAndCheckFees(LightningMoney currentFeePerKw) |
| | 120 | | { |
| | 121 | | // Calculate transaction fee |
| 0 | 122 | | CalculateTransactionFee(currentFeePerKw); |
| | 123 | |
|
| | 124 | | // Check if the output amount plus fees is greater than the input amount |
| 0 | 125 | | if (!CheckTransactionAmounts(CalculatedFee)) |
| 0 | 126 | | throw new InvalidOperationException("Output amount cannot exceed input amount."); |
| 0 | 127 | | } |
| | 128 | |
|
| | 129 | | protected void AppendRemoteSignatureToTransaction(ITransactionSignature remoteSignature, PubKey remotePubKey) |
| | 130 | | { |
| 104 | 131 | | _builder.AddKnownSignature(remotePubKey, remoteSignature, _transaction.Inputs[0].PrevOut); |
| 104 | 132 | | } |
| | 133 | |
|
| | 134 | | protected void SignTransactionWithExistingKeys() |
| | 135 | | { |
| 104 | 136 | | _transaction = _builder.SignTransactionInPlace(_transaction); |
| | 137 | |
|
| 104 | 138 | | TxId = _transaction.GetHash(); |
| 104 | 139 | | Finalized = true; |
| 104 | 140 | | } |
| | 141 | |
|
| 296 | 142 | | protected LightningMoney TotalInputAmount => _coins.Sum(c => (LightningMoney)c.Item1.Amount); |
| | 143 | |
|
| 672 | 144 | | protected LightningMoney TotalOutputAmount => Outputs.Sum(o => o.Amount); |
| | 145 | |
|
| | 146 | | protected bool CheckTransactionAmounts(LightningMoney? fees = null) |
| | 147 | | { |
| | 148 | | // Check if the output amount is greater than the input amount |
| 132 | 149 | | return TotalOutputAmount + (fees ?? LightningMoney.Zero) <= TotalInputAmount; |
| | 150 | | } |
| | 151 | |
|
| | 152 | | protected int CalculateOutputWeight() |
| | 153 | | { |
| 132 | 154 | | var outputWeight = WeightConstants.TRANSACTION_BASE_WEIGHT; |
| 132 | 155 | | if (_hasAnchorOutput) |
| | 156 | | { |
| 40 | 157 | | outputWeight += 8; // Add 8 more bytes for (count_tx_out * 4) |
| | 158 | | } |
| | 159 | |
|
| 1352 | 160 | | foreach (var output in Outputs) |
| | 161 | | { |
| 544 | 162 | | switch (output) |
| | 163 | | { |
| | 164 | | case FundingOutput: |
| 16 | 165 | | outputWeight += WeightConstants.P2WSH_OUTPUT_WEIGHT; |
| 16 | 166 | | break; |
| 16 | 167 | | case ChangeOutput changeOutput when changeOutput.ScriptPubKey.IsScriptType(ScriptType.P2PKH): |
| 0 | 168 | | outputWeight += WeightConstants.P2PKH_OUTPUT_WEIGHT; |
| 0 | 169 | | break; |
| 16 | 170 | | case ChangeOutput changeOutput when changeOutput.ScriptPubKey.IsScriptType(ScriptType.P2SH): |
| 0 | 171 | | outputWeight += WeightConstants.P2SH_OUTPUT_WEIGHT; |
| 0 | 172 | | break; |
| 16 | 173 | | case ChangeOutput changeOutput when changeOutput.ScriptPubKey.IsScriptType(ScriptType.P2WPKH): |
| 4 | 174 | | outputWeight += WeightConstants.P2WPKH_OUTPUT_WEIGHT; |
| 4 | 175 | | break; |
| 12 | 176 | | case ChangeOutput changeOutput when changeOutput.ScriptPubKey.IsScriptType(ScriptType.P2WSH): |
| 12 | 177 | | outputWeight += WeightConstants.P2WSH_OUTPUT_WEIGHT; |
| 12 | 178 | | break; |
| | 179 | | case ChangeOutput changeOutput: |
| 0 | 180 | | outputWeight += changeOutput.ScriptPubKey.Length; |
| 0 | 181 | | break; |
| | 182 | | case ToLocalOutput: |
| 116 | 183 | | case ToRemoteOutput when _hasAnchorOutput: |
| 156 | 184 | | outputWeight += WeightConstants.P2WSH_OUTPUT_WEIGHT; |
| 156 | 185 | | break; |
| | 186 | | case ToRemoteOutput: |
| 76 | 187 | | outputWeight += WeightConstants.P2WPKH_OUTPUT_WEIGHT; |
| 76 | 188 | | break; |
| | 189 | | case ToAnchorOutput: |
| 80 | 190 | | outputWeight += WeightConstants.ANCHOR_OUTPUT_WEIGHT; |
| 80 | 191 | | break; |
| | 192 | | case OfferedHtlcOutput: |
| | 193 | | case ReceivedHtlcOutput: |
| 200 | 194 | | outputWeight += WeightConstants.HTLC_OUTPUT_WEIGHT; |
| | 195 | | break; |
| | 196 | | } |
| | 197 | | } |
| | 198 | |
|
| 132 | 199 | | return outputWeight; |
| | 200 | | } |
| | 201 | |
|
| | 202 | | protected int CalculateInputWeight() |
| | 203 | | { |
| 16 | 204 | | var inputWeight = 0; |
| 16 | 205 | | var mustAddWitnessHeader = false; |
| | 206 | |
|
| 64 | 207 | | foreach (var (coin, _) in _coins) |
| | 208 | | { |
| 32 | 209 | | var input = _transaction.Inputs.SingleOrDefault(i => i.PrevOut == coin.Outpoint) |
| 16 | 210 | | ?? throw new NullReferenceException("Input not found in transaction."); |
| | 211 | |
|
| 16 | 212 | | if (input.WitScript.PushCount > 0) |
| | 213 | | { |
| 0 | 214 | | mustAddWitnessHeader = true; |
| | 215 | | } |
| | 216 | |
|
| 16 | 217 | | if (coin.ScriptPubKey.IsScriptType(ScriptType.P2PKH)) |
| | 218 | | { |
| 4 | 219 | | inputWeight += 4 * Math.Max(WeightConstants.P2PKH_INTPUT_WEIGHT, input.ToBytes().Length); |
| | 220 | | } |
| 12 | 221 | | else if (coin.ScriptPubKey.IsScriptType(ScriptType.P2SH)) |
| | 222 | | { |
| 0 | 223 | | inputWeight += 4 * Math.Max(WeightConstants.P2SH_INTPUT_WEIGHT, input.ToBytes().Length); |
| 0 | 224 | | inputWeight += input.WitScript.ToBytes().Length; |
| | 225 | | } |
| 12 | 226 | | else if (coin.ScriptPubKey.IsScriptType(ScriptType.P2WPKH)) |
| | 227 | | { |
| 12 | 228 | | inputWeight += 4 * Math.Max(WeightConstants.P2WPKH_INTPUT_WEIGHT, input.ToBytes().Length); |
| 12 | 229 | | inputWeight += input.WitScript.ToBytes().Length; |
| | 230 | | } |
| 0 | 231 | | else if (coin.ScriptPubKey.IsScriptType(ScriptType.P2WSH)) |
| | 232 | | { |
| 0 | 233 | | inputWeight += 4 * Math.Max(WeightConstants.P2WSH_INTPUT_WEIGHT, input.ToBytes().Length); |
| 0 | 234 | | inputWeight += Math.Max(WeightConstants.MULTISIG_WITNESS_WEIGHT, input.WitScript.ToBytes().Length); |
| | 235 | | } |
| | 236 | | else |
| | 237 | | { |
| 0 | 238 | | inputWeight += 4 * Math.Max(WeightConstants.P2UNKOWN_S_INTPUT_WEIGHT, input.ToBytes().Length); |
| 0 | 239 | | inputWeight += input.WitScript.ToBytes().Length; |
| | 240 | | } |
| | 241 | | } |
| | 242 | |
|
| 16 | 243 | | if (mustAddWitnessHeader) |
| | 244 | | { |
| 0 | 245 | | inputWeight += WeightConstants.WITNESS_HEADER; |
| | 246 | | } |
| | 247 | |
|
| 16 | 248 | | return inputWeight; |
| | 249 | | } |
| | 250 | |
|
| | 251 | | protected void CalculateTransactionFee(LightningMoney currentFeePerKw) |
| | 252 | | { |
| 16 | 253 | | var outputWeight = CalculateOutputWeight(); |
| 16 | 254 | | var inputWeight = CalculateInputWeight(); |
| | 255 | |
|
| 16 | 256 | | CalculatedFee.Satoshi = (outputWeight + inputWeight) * currentFeePerKw.Satoshi / 1000L; |
| 16 | 257 | | } |
| | 258 | |
|
| | 259 | | #region Input Management |
| | 260 | | protected void AddCoin(Coin coin, Sequence sequence) |
| | 261 | | { |
| 0 | 262 | | ArgumentNullException.ThrowIfNull(coin); |
| | 263 | |
|
| 0 | 264 | | _transaction.Inputs.Add(coin.Outpoint, null, null, sequence); |
| 0 | 265 | | } |
| | 266 | | protected void AddCoin(Coin coin) |
| | 267 | | { |
| 0 | 268 | | ArgumentNullException.ThrowIfNull(coin); |
| | 269 | |
|
| 0 | 270 | | _coins.Add((coin, Sequence.Final)); |
| 0 | 271 | | _transaction.Inputs.Add(coin.Outpoint, null, null, Sequence.Final); |
| 0 | 272 | | } |
| | 273 | | #endregion |
| | 274 | |
|
| | 275 | | #region Output Management |
| | 276 | | protected void AddOutput(BaseOutput baseOutput) |
| | 277 | | { |
| 852 | 278 | | ArgumentNullException.ThrowIfNull(baseOutput); |
| | 279 | |
|
| 852 | 280 | | Outputs.Add(baseOutput); |
| 852 | 281 | | } |
| | 282 | |
|
| | 283 | | protected void AddOutputRange(IEnumerable<BaseOutput> outputs) |
| | 284 | | { |
| 0 | 285 | | ArgumentNullException.ThrowIfNull(outputs); |
| | 286 | |
|
| 0 | 287 | | var outputBases = outputs as BaseOutput[] ?? outputs.ToArray(); |
| 0 | 288 | | if (outputBases.Length == 0) |
| 0 | 289 | | return; |
| | 290 | |
|
| 0 | 291 | | foreach (var output in outputBases) |
| | 292 | | { |
| 0 | 293 | | ArgumentNullException.ThrowIfNull(output); |
| 0 | 294 | | Outputs.Add(output); |
| | 295 | | } |
| 0 | 296 | | } |
| | 297 | |
|
| | 298 | | protected void ClearOutputsFromTransaction() |
| | 299 | | { |
| 0 | 300 | | _transaction.Outputs.Clear(); |
| 0 | 301 | | } |
| | 302 | |
|
| | 303 | | protected void RemoveOutput(BaseOutput? baseOutput) |
| | 304 | | { |
| 256 | 305 | | ArgumentNullException.ThrowIfNull(baseOutput); |
| | 306 | |
|
| 256 | 307 | | Outputs.Remove(baseOutput); |
| 256 | 308 | | } |
| | 309 | |
|
| | 310 | | protected void AddOrderedOutputsToTransaction() |
| | 311 | | { |
| | 312 | | // Clear TxOuts |
| 132 | 313 | | _transaction.Outputs.Clear(); |
| | 314 | |
|
| 132 | 315 | | switch (Outputs.Count) |
| | 316 | | { |
| | 317 | | case 0: |
| 0 | 318 | | return; |
| | 319 | | case 1: |
| 20 | 320 | | _transaction.Outputs.Add(Outputs[0].ToTxOut()); |
| 20 | 321 | | break; |
| | 322 | | default: |
| | 323 | | // Add ordered outputs |
| 600 | 324 | | Outputs = Outputs.OrderBy(o => o, TransactionOutputComparer.Instance).ToList(); |
| 600 | 325 | | _transaction.Outputs.AddRange(Outputs.Select(o => o.ToTxOut())); |
| | 326 | | break; |
| | 327 | | } |
| 112 | 328 | | } |
| | 329 | | #endregion |
| | 330 | | #endregion |
| | 331 | | } |