github.com/decred/dcrlnd@v0.7.6/lnwallet/chanfunding/psbt_assembler.go (about) 1 package chanfunding 2 3 import ( 4 "crypto/sha256" 5 "errors" 6 "fmt" 7 "github.com/decred/dcrd/txscript/v4/stdaddr" 8 "sync" 9 10 "github.com/decred/dcrd/chaincfg/v3" 11 "github.com/decred/dcrd/dcrec/secp256k1/v4" 12 "github.com/decred/dcrd/dcrutil/v4" 13 "github.com/decred/dcrd/wire" 14 "github.com/decred/dcrlnd/input" 15 "github.com/decred/dcrlnd/internal/psbt" 16 "github.com/decred/dcrlnd/keychain" 17 ) 18 19 // PsbtState is a type for the state of the PSBT intent state machine. 20 type PsbtState uint8 21 22 const ( 23 // PsbtShimRegistered denotes a channel funding process has started with 24 // a PSBT shim attached. This is the default state for a PsbtIntent. We 25 // don't use iota here because the values have to be in sync with the 26 // RPC constants. 27 PsbtShimRegistered PsbtState = 1 28 29 // PsbtOutputKnown denotes that the local and remote peer have 30 // negotiated the multisig keys to be used as the channel funding output 31 // and therefore the PSBT funding process can now start. 32 PsbtOutputKnown PsbtState = 2 33 34 // PsbtVerified denotes that a potential PSBT has been presented to the 35 // intent and passed all checks. The verified PSBT can be given to a/the 36 // signer(s). 37 PsbtVerified PsbtState = 3 38 39 // PsbtFinalized denotes that a fully signed PSBT has been given to the 40 // intent that looks identical to the previously verified transaction 41 // but has all witness data added and is therefore completely signed. 42 PsbtFinalized PsbtState = 4 43 44 // PsbtFundingTxCompiled denotes that the PSBT processed by this intent 45 // has been successfully converted into a protocol transaction. It is 46 // not yet completely certain that the resulting transaction will be 47 // published because the commitment transactions between the channel 48 // peers first need to be counter signed. But the job of the intent is 49 // hereby completed. 50 PsbtFundingTxCompiled PsbtState = 5 51 52 // PsbtInitiatorCanceled denotes that the user has canceled the intent. 53 PsbtInitiatorCanceled PsbtState = 6 54 55 // PsbtResponderCanceled denotes that the remote peer has canceled the 56 // funding, likely due to a timeout. 57 PsbtResponderCanceled PsbtState = 7 58 ) 59 60 // String returns a string representation of the PsbtState. 61 func (s PsbtState) String() string { 62 switch s { 63 case PsbtShimRegistered: 64 return "shim_registered" 65 66 case PsbtOutputKnown: 67 return "output_known" 68 69 case PsbtVerified: 70 return "verified" 71 72 case PsbtFinalized: 73 return "finalized" 74 75 case PsbtFundingTxCompiled: 76 return "funding_tx_compiled" 77 78 case PsbtInitiatorCanceled: 79 return "user_canceled" 80 81 case PsbtResponderCanceled: 82 return "remote_canceled" 83 84 default: 85 return fmt.Sprintf("<unknown(%d)>", s) 86 } 87 } 88 89 var ( 90 // ErrRemoteCanceled is the error that is returned to the user if the 91 // funding flow was canceled by the remote peer. 92 ErrRemoteCanceled = errors.New("remote canceled funding, possibly " + 93 "timed out") 94 95 // ErrUserCanceled is the error that is returned through the PsbtReady 96 // channel if the user canceled the funding flow. 97 ErrUserCanceled = errors.New("user canceled funding") 98 ) 99 100 // PsbtIntent is an intent created by the PsbtAssembler which represents a 101 // funding output to be created by a PSBT. This might be used when a hardware 102 // wallet, or a channel factory is the entity crafting the funding transaction, 103 // and not lnd. 104 type PsbtIntent struct { 105 // ShimIntent is the wrapped basic intent that contains common fields 106 // we also use in the PSBT funding case. 107 ShimIntent 108 109 // State is the current state the intent state machine is in. 110 State PsbtState 111 112 // BasePsbt is the user-supplied base PSBT the channel output should be 113 // added to. If this is nil we will create a new, empty PSBT as the base 114 // for the funding transaction. 115 BasePsbt *psbt.Packet 116 117 // PendingPsbt is the parsed version of the current PSBT. This can be 118 // in two stages: If the user has not yet provided any PSBT, this is 119 // nil. Once the user sends us an unsigned funded PSBT, we verify that 120 // we have a valid transaction that sends to the channel output PK 121 // script and has an input large enough to pay for it. We keep this 122 // verified but not yet signed version around until the fully signed 123 // transaction is submitted by the user. At that point we make sure the 124 // inputs and outputs haven't changed to what was previously verified. 125 // Only witness data should be added after the verification process. 126 PendingPsbt *psbt.Packet 127 128 // FinalTX is the final, signed and ready to be published wire format 129 // transaction. This is only set after the PsbtFinalize step was 130 // completed successfully. 131 FinalTX *wire.MsgTx 132 133 // PsbtReady is an error channel the funding manager will listen for 134 // a signal about the PSBT being ready to continue the funding flow. In 135 // the normal, happy flow, this channel is only ever closed. If a 136 // non-nil error is sent through the channel, the funding flow will be 137 // canceled. 138 // 139 // NOTE: This channel must always be buffered. 140 PsbtReady chan error 141 142 // shouldPublish specifies if the intent assumes its assembler should 143 // publish the transaction once the channel funding has completed. If 144 // this is set to false then the finalize step can be skipped. 145 shouldPublish bool 146 147 // signalPsbtReady is a Once guard to make sure the PsbtReady channel is 148 // only closed exactly once. 149 signalPsbtReady sync.Once 150 151 // netParams are the network parameters used to encode the P2WSH funding 152 // address. 153 netParams *chaincfg.Params 154 } 155 156 // BindKeys sets both the remote and local node's keys that will be used for the 157 // channel funding multisig output. 158 func (i *PsbtIntent) BindKeys(localKey *keychain.KeyDescriptor, 159 remoteKey *secp256k1.PublicKey) { 160 161 i.localKey = localKey 162 i.remoteKey = remoteKey 163 i.State = PsbtOutputKnown 164 } 165 166 // FundingParams returns the parameters that are necessary to start funding the 167 // channel output this intent was created for. It returns the P2WSH funding 168 // address, the exact funding amount and a PSBT packet that contains exactly one 169 // output that encodes the previous two parameters. 170 func (i *PsbtIntent) FundingParams() (stdaddr.Address, int64, *psbt.Packet, 171 error) { 172 173 if i.State != PsbtOutputKnown { 174 return nil, 0, nil, fmt.Errorf("invalid state, got %v "+ 175 "expected %v", i.State, PsbtOutputKnown) 176 } 177 178 // The funding output needs to be known already at this point, which 179 // means we need to have the local and remote multisig keys bound 180 // already. 181 witnessScript, out, err := i.FundingOutput() 182 if err != nil { 183 return nil, 0, nil, fmt.Errorf("unable to create funding "+ 184 "output: %v", err) 185 } 186 witnessScriptHash := sha256.Sum256(witnessScript) 187 188 // Encode the address in the human readable bech32 format. 189 addr, err := stdaddr.NewAddressScriptHashV0( 190 witnessScriptHash[:], i.netParams, 191 ) 192 if err != nil { 193 return nil, 0, nil, fmt.Errorf("unable to encode address: %v", 194 err) 195 } 196 197 // We'll also encode the address/amount in a machine readable raw PSBT 198 // format. If the user supplied a base PSBT, we'll add the output to 199 // that one, otherwise we'll create a new one. 200 packet := i.BasePsbt 201 if packet == nil { 202 packet, err = psbt.New(nil, nil, 2, 0, nil) 203 if err != nil { 204 return nil, 0, nil, fmt.Errorf("unable to create "+ 205 "PSBT: %v", err) 206 } 207 } 208 packet.UnsignedTx.TxOut = append(packet.UnsignedTx.TxOut, out) 209 packet.Outputs = append(packet.Outputs, psbt.POutput{}) 210 return addr, out.Value, packet, nil 211 } 212 213 // Verify makes sure the PSBT that is given to the intent has an output that 214 // sends to the channel funding multisig address with the correct amount. A 215 // simple check that at least a single input has been specified is performed. 216 func (i *PsbtIntent) Verify(packet *psbt.Packet, skipFinalize bool) error { 217 if packet == nil { 218 return fmt.Errorf("PSBT is nil") 219 } 220 if i.State != PsbtOutputKnown { 221 return fmt.Errorf("invalid state. got %v expected %v", i.State, 222 PsbtOutputKnown) 223 } 224 225 // Try to locate the channel funding multisig output. 226 _, expectedOutput, err := i.FundingOutput() 227 if err != nil { 228 return fmt.Errorf("funding output cannot be created: %v", err) 229 } 230 outputFound := false 231 outputSum := int64(0) 232 for _, out := range packet.UnsignedTx.TxOut { 233 outputSum += out.Value 234 if psbt.TxOutsEqual(out, expectedOutput) { 235 outputFound = true 236 } 237 } 238 if !outputFound { 239 return fmt.Errorf("funding output not found in PSBT") 240 } 241 242 // At least one input needs to be specified and it must be large enough 243 // to pay for all outputs. We don't want to dive into fee estimation 244 // here so we just assume that if the input amount exceeds the output 245 // amount, the chosen fee is sufficient. 246 if len(packet.UnsignedTx.TxIn) == 0 { 247 return fmt.Errorf("PSBT has no inputs") 248 } 249 sum, err := psbt.SumUtxoInputValues(packet) 250 if err != nil { 251 return fmt.Errorf("error determining input sum: %v", err) 252 } 253 if sum <= outputSum { 254 return fmt.Errorf("input amount sum must be larger than " + 255 "output amount sum") 256 } 257 258 // SumUtxoInputValues checks that packet.Inputs is non-empty. Here we 259 // check that each Input has a WitnessUtxo field, to avoid possible 260 // malleability. 261 for _, in := range packet.Inputs { 262 if in.WitnessUtxo == nil { 263 return fmt.Errorf("not all inputs are segwit spends") 264 } 265 } 266 267 // In case we aren't going to publish any transaction, we now have 268 // everything we need and can skip the Finalize step. 269 i.PendingPsbt = packet 270 if !i.shouldPublish && skipFinalize { 271 i.FinalTX = packet.UnsignedTx 272 i.State = PsbtFinalized 273 274 // Signal the funding manager that it can now continue with its 275 // funding flow as the PSBT is now complete . 276 i.signalPsbtReady.Do(func() { 277 close(i.PsbtReady) 278 }) 279 280 return nil 281 } 282 283 i.State = PsbtVerified 284 return nil 285 } 286 287 // Finalize makes sure the final PSBT that is given to the intent is fully valid 288 // and signed but still contains the same UTXOs and outputs as the pending 289 // transaction we previously verified. If everything checks out, the funding 290 // manager is informed that the channel can now be opened and the funding 291 // transaction be broadcast. 292 func (i *PsbtIntent) Finalize(packet *psbt.Packet) error { 293 if packet == nil { 294 return fmt.Errorf("PSBT is nil") 295 } 296 if i.State != PsbtVerified { 297 return fmt.Errorf("invalid state. got %v expected %v", i.State, 298 PsbtVerified) 299 } 300 301 // Make sure the PSBT itself thinks it's finalized and ready to be 302 // broadcast. 303 err := psbt.MaybeFinalizeAll(packet) 304 if err != nil { 305 return fmt.Errorf("error finalizing PSBT: %v", err) 306 } 307 rawTx, err := psbt.Extract(packet) 308 if err != nil { 309 return fmt.Errorf("unable to extract funding TX: %v", err) 310 } 311 312 return i.FinalizeRawTX(rawTx) 313 } 314 315 // FinalizeRawTX makes sure the final raw transaction that is given to the 316 // intent is fully valid and signed but still contains the same UTXOs and 317 // outputs as the pending transaction we previously verified. If everything 318 // checks out, the funding manager is informed that the channel can now be 319 // opened and the funding transaction be broadcast. 320 func (i *PsbtIntent) FinalizeRawTX(rawTx *wire.MsgTx) error { 321 if rawTx == nil { 322 return fmt.Errorf("raw transaction is nil") 323 } 324 if i.State != PsbtVerified { 325 return fmt.Errorf("invalid state. got %v expected %v", i.State, 326 PsbtVerified) 327 } 328 329 // Do a basic check that this is still the same TX that we verified in 330 // the previous step. This is to protect the user from unwanted 331 // modifications. We only check the outputs and previous outpoints of 332 // the inputs of the wire transaction because the fields in the PSBT 333 // part are allowed to change. 334 if i.PendingPsbt == nil { 335 return fmt.Errorf("PSBT was not verified first") 336 } 337 err := psbt.VerifyOutputsEqual( 338 rawTx.TxOut, i.PendingPsbt.UnsignedTx.TxOut, 339 ) 340 if err != nil { 341 return fmt.Errorf("outputs differ from verified PSBT: %v", err) 342 } 343 err = psbt.VerifyInputPrevOutpointsEqual( 344 rawTx.TxIn, i.PendingPsbt.UnsignedTx.TxIn, 345 ) 346 if err != nil { 347 return fmt.Errorf("inputs differ from verified PSBT: %v", err) 348 } 349 350 // We also check that we have a signed TX. This is only necessary if the 351 // FinalizeRawTX is called directly with a wire format TX instead of 352 // extracting the TX from a PSBT. 353 err = verifyInputsSigned(rawTx.TxIn) 354 if err != nil { 355 return fmt.Errorf("inputs not signed: %v", err) 356 } 357 358 // As far as we can tell, this TX is ok to be used as a funding 359 // transaction. 360 i.State = PsbtFinalized 361 i.FinalTX = rawTx 362 363 // Signal the funding manager that it can now finally continue with its 364 // funding flow as the PSBT is now ready to be converted into a real 365 // transaction and be published. 366 i.signalPsbtReady.Do(func() { 367 close(i.PsbtReady) 368 }) 369 return nil 370 } 371 372 // CompileFundingTx finalizes the previously verified PSBT and returns the 373 // extracted binary serialized transaction from it. It also prepares the channel 374 // point for which this funding intent was initiated for. 375 func (i *PsbtIntent) CompileFundingTx() (*wire.MsgTx, error) { 376 if i.State != PsbtFinalized { 377 return nil, fmt.Errorf("invalid state. got %v expected %v", 378 i.State, PsbtFinalized) 379 } 380 381 // Identify our funding outpoint now that we know everything's ready. 382 _, txOut, err := i.FundingOutput() 383 if err != nil { 384 return nil, fmt.Errorf("cannot get funding output: %v", err) 385 } 386 ok, idx := input.FindScriptOutputIndex(i.FinalTX, txOut.PkScript) 387 if !ok { 388 return nil, fmt.Errorf("funding output not found in PSBT") 389 } 390 i.chanPoint = &wire.OutPoint{ 391 Hash: i.FinalTX.TxHash(), 392 Index: idx, 393 } 394 i.State = PsbtFundingTxCompiled 395 396 return i.FinalTX, nil 397 } 398 399 // RemoteCanceled informs the listener of the PSBT ready channel that the 400 // funding has been canceled by the remote peer and that we can no longer 401 // continue with it. 402 func (i *PsbtIntent) RemoteCanceled() { 403 log.Debugf("PSBT funding intent canceled by remote, state=%v", i.State) 404 i.signalPsbtReady.Do(func() { 405 i.PsbtReady <- ErrRemoteCanceled 406 i.State = PsbtResponderCanceled 407 }) 408 i.ShimIntent.Cancel() 409 } 410 411 // Cancel allows the caller to cancel a funding Intent at any time. This will 412 // return make sure the channel funding flow with the remote peer is failed and 413 // any reservations are canceled. 414 // 415 // NOTE: Part of the chanfunding.Intent interface. 416 func (i *PsbtIntent) Cancel() { 417 log.Debugf("PSBT funding intent canceled, state=%v", i.State) 418 i.signalPsbtReady.Do(func() { 419 i.PsbtReady <- ErrUserCanceled 420 i.State = PsbtInitiatorCanceled 421 }) 422 i.ShimIntent.Cancel() 423 } 424 425 // Inputs returns all inputs to the final funding transaction that we know 426 // about. These are only known after the PSBT has been verified. 427 func (i *PsbtIntent) Inputs() []wire.OutPoint { 428 var inputs []wire.OutPoint 429 430 switch i.State { 431 432 // We return the inputs to the pending psbt. 433 case PsbtVerified: 434 for _, in := range i.PendingPsbt.UnsignedTx.TxIn { 435 inputs = append(inputs, in.PreviousOutPoint) 436 } 437 438 // We return the inputs to the final funding tx. 439 case PsbtFinalized, PsbtFundingTxCompiled: 440 for _, in := range i.FinalTX.TxIn { 441 inputs = append(inputs, in.PreviousOutPoint) 442 } 443 444 // In all other states we cannot know the inputs to the funding tx, and 445 // return an empty list. 446 default: 447 } 448 449 return inputs 450 } 451 452 // Outputs returns all outputs of the final funding transaction that we 453 // know about. These are only known after the PSBT has been verified. 454 func (i *PsbtIntent) Outputs() []*wire.TxOut { 455 switch i.State { 456 457 // We return the outputs of the pending psbt. 458 case PsbtVerified: 459 return i.PendingPsbt.UnsignedTx.TxOut 460 461 // We return the outputs of the final funding tx. 462 case PsbtFinalized, PsbtFundingTxCompiled: 463 return i.FinalTX.TxOut 464 465 // In all other states we cannot know the final outputs, and return an 466 // empty list. 467 default: 468 return nil 469 } 470 } 471 472 // ShouldPublishFundingTX returns true if the intent assumes that its assembler 473 // should publish the funding TX once the funding negotiation is complete. 474 func (i *PsbtIntent) ShouldPublishFundingTX() bool { 475 return i.shouldPublish 476 } 477 478 // PsbtAssembler is a type of chanfunding.Assembler wherein the funding 479 // transaction is constructed outside of lnd by using partially signed bitcoin 480 // transactions (PSBT). 481 type PsbtAssembler struct { 482 // fundingAmt is the total amount of coins in the funding output. 483 fundingAmt dcrutil.Amount 484 485 // basePsbt is the user-supplied base PSBT the channel output should be 486 // added to. 487 basePsbt *psbt.Packet 488 489 // netParams are the network parameters used to encode the P2WSH funding 490 // address. 491 netParams *chaincfg.Params 492 493 // shouldPublish specifies if the assembler should publish the 494 // transaction once the channel funding has completed. 495 shouldPublish bool 496 } 497 498 // NewPsbtAssembler creates a new CannedAssembler from the material required 499 // to construct a funding output and channel point. An optional base PSBT can 500 // be supplied which will be used to add the channel output to instead of 501 // creating a new one. 502 func NewPsbtAssembler(fundingAmt dcrutil.Amount, basePsbt *psbt.Packet, 503 netParams *chaincfg.Params, shouldPublish bool) *PsbtAssembler { 504 505 return &PsbtAssembler{ 506 fundingAmt: fundingAmt, 507 basePsbt: basePsbt, 508 netParams: netParams, 509 shouldPublish: shouldPublish, 510 } 511 } 512 513 // ProvisionChannel creates a new ShimIntent given the passed funding Request. 514 // The returned intent is immediately able to provide the channel point and 515 // funding output as they've already been created outside lnd. 516 // 517 // NOTE: This method satisfies the chanfunding.Assembler interface. 518 func (p *PsbtAssembler) ProvisionChannel(req *Request) (Intent, error) { 519 // We'll exit out if this field is set as the funding transaction will 520 // be assembled externally, so we don't influence coin selection. 521 if req.SubtractFees { 522 return nil, fmt.Errorf("SubtractFees not supported for PSBT") 523 } 524 525 intent := &PsbtIntent{ 526 ShimIntent: ShimIntent{ 527 localFundingAmt: p.fundingAmt, 528 }, 529 State: PsbtShimRegistered, 530 BasePsbt: p.basePsbt, 531 PsbtReady: make(chan error, 1), 532 shouldPublish: p.shouldPublish, 533 netParams: p.netParams, 534 } 535 536 // A simple sanity check to ensure the provisioned request matches the 537 // re-made shim intent. 538 if req.LocalAmt+req.RemoteAmt != p.fundingAmt { 539 return nil, fmt.Errorf("intent doesn't match PSBT "+ 540 "assembler: local_amt=%v, remote_amt=%v, funding_amt=%v", 541 req.LocalAmt, req.RemoteAmt, p.fundingAmt) 542 } 543 544 return intent, nil 545 } 546 547 // ShouldPublishFundingTx is a method of the assembler that signals if the 548 // funding transaction should be published after the channel negotiations are 549 // completed with the remote peer. 550 // 551 // NOTE: This method is a part of the ConditionalPublishAssembler interface. 552 func (p *PsbtAssembler) ShouldPublishFundingTx() bool { 553 return p.shouldPublish 554 } 555 556 // A compile-time assertion to ensure PsbtAssembler meets the 557 // ConditionalPublishAssembler interface. 558 var _ ConditionalPublishAssembler = (*PsbtAssembler)(nil) 559 560 // verifyInputsSigned verifies that the given list of inputs is non-empty and 561 // that all the inputs either contain a script signature or a witness stack. 562 func verifyInputsSigned(ins []*wire.TxIn) error { 563 if len(ins) == 0 { 564 return fmt.Errorf("no inputs in transaction") 565 } 566 for idx, in := range ins { 567 if len(in.SignatureScript) == 0 { 568 return fmt.Errorf("input %d has no signature data "+ 569 "attached", idx) 570 } 571 } 572 return nil 573 }