github.com/btcsuite/btcd@v0.24.0/txscript/sign.go (about) 1 // Copyright (c) 2013-2015 The btcsuite developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package txscript 6 7 import ( 8 "errors" 9 10 "github.com/btcsuite/btcd/btcec/v2" 11 "github.com/btcsuite/btcd/btcec/v2/schnorr" 12 "github.com/btcsuite/btcd/btcutil" 13 14 "github.com/btcsuite/btcd/btcec/v2/ecdsa" 15 "github.com/btcsuite/btcd/chaincfg" 16 "github.com/btcsuite/btcd/wire" 17 ) 18 19 // RawTxInWitnessSignature returns the serialized ECDA signature for the input 20 // idx of the given transaction, with the hashType appended to it. This 21 // function is identical to RawTxInSignature, however the signature generated 22 // signs a new sighash digest defined in BIP0143. 23 func RawTxInWitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, 24 amt int64, subScript []byte, hashType SigHashType, 25 key *btcec.PrivateKey) ([]byte, error) { 26 27 hash, err := calcWitnessSignatureHashRaw(subScript, sigHashes, hashType, tx, 28 idx, amt) 29 if err != nil { 30 return nil, err 31 } 32 33 signature := ecdsa.Sign(key, hash) 34 35 return append(signature.Serialize(), byte(hashType)), nil 36 } 37 38 // WitnessSignature creates an input witness stack for tx to spend BTC sent 39 // from a previous output to the owner of privKey using the p2wkh script 40 // template. The passed transaction must contain all the inputs and outputs as 41 // dictated by the passed hashType. The signature generated observes the new 42 // transaction digest algorithm defined within BIP0143. 43 func WitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, amt int64, 44 subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey, 45 compress bool) (wire.TxWitness, error) { 46 47 sig, err := RawTxInWitnessSignature(tx, sigHashes, idx, amt, subscript, 48 hashType, privKey) 49 if err != nil { 50 return nil, err 51 } 52 53 pk := privKey.PubKey() 54 var pkData []byte 55 if compress { 56 pkData = pk.SerializeCompressed() 57 } else { 58 pkData = pk.SerializeUncompressed() 59 } 60 61 // A witness script is actually a stack, so we return an array of byte 62 // slices here, rather than a single byte slice. 63 return wire.TxWitness{sig, pkData}, nil 64 } 65 66 // RawTxInTaprootSignature returns a valid schnorr signature required to 67 // perform a taproot key-spend of the specified input. If SigHashDefault was 68 // specified, then the returned signature is 64-byte in length, as it omits the 69 // additional byte to denote the sighash type. 70 func RawTxInTaprootSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, 71 amt int64, pkScript []byte, tapScriptRootHash []byte, hashType SigHashType, 72 key *btcec.PrivateKey) ([]byte, error) { 73 74 // First, we'll start by compute the top-level taproot sighash. 75 sigHash, err := calcTaprootSignatureHashRaw( 76 sigHashes, hashType, tx, idx, 77 NewCannedPrevOutputFetcher(pkScript, amt), 78 ) 79 if err != nil { 80 return nil, err 81 } 82 83 // Before we sign the sighash, we'll need to apply the taptweak to the 84 // private key based on the tapScriptRootHash. 85 privKeyTweak := TweakTaprootPrivKey(*key, tapScriptRootHash) 86 87 // With the sighash constructed, we can sign it with the specified 88 // private key. 89 signature, err := schnorr.Sign(privKeyTweak, sigHash) 90 if err != nil { 91 return nil, err 92 } 93 94 sig := signature.Serialize() 95 96 // If this is sighash default, then we can just return the signature 97 // directly. 98 if hashType == SigHashDefault { 99 return sig, nil 100 } 101 102 // Otherwise, append the sighash type to the final sig. 103 return append(sig, byte(hashType)), nil 104 } 105 106 // TaprootWitnessSignature returns a valid witness stack that can be used to 107 // spend the key-spend path of a taproot input as specified in BIP 342 and BIP 108 // 86. This method assumes that the public key included in pkScript was 109 // generated using ComputeTaprootKeyNoScript that commits to a fake root 110 // tapscript hash. If not, then RawTxInTaprootSignature should be used with the 111 // actual committed contents. 112 // 113 // TODO(roasbeef): add support for annex even tho it's non-standard? 114 func TaprootWitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, 115 amt int64, pkScript []byte, hashType SigHashType, 116 key *btcec.PrivateKey) (wire.TxWitness, error) { 117 118 // As we're assuming this was a BIP 86 key, we use an empty root hash 119 // which means output key commits to just the public key. 120 fakeTapscriptRootHash := []byte{} 121 122 sig, err := RawTxInTaprootSignature( 123 tx, sigHashes, idx, amt, pkScript, fakeTapscriptRootHash, 124 hashType, key, 125 ) 126 if err != nil { 127 return nil, err 128 } 129 130 // The witness script to spend a taproot input using the key-spend path 131 // is just the signature itself, given the public key is 132 // embedded in the previous output script. 133 return wire.TxWitness{sig}, nil 134 } 135 136 // RawTxInTapscriptSignature computes a raw schnorr signature for a signature 137 // generated from a tapscript leaf. This differs from the 138 // RawTxInTaprootSignature which is used to generate signatures for top-level 139 // taproot key spends. 140 // 141 // TODO(roasbeef): actually add code-sep to interface? not really used 142 // anywhere.... 143 func RawTxInTapscriptSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, 144 amt int64, pkScript []byte, tapLeaf TapLeaf, hashType SigHashType, 145 privKey *btcec.PrivateKey) ([]byte, error) { 146 147 // First, we'll start by compute the top-level taproot sighash. 148 tapLeafHash := tapLeaf.TapHash() 149 sigHash, err := calcTaprootSignatureHashRaw( 150 sigHashes, hashType, tx, idx, 151 NewCannedPrevOutputFetcher(pkScript, amt), 152 WithBaseTapscriptVersion(blankCodeSepValue, tapLeafHash[:]), 153 ) 154 if err != nil { 155 return nil, err 156 } 157 158 // With the sighash constructed, we can sign it with the specified 159 // private key. 160 signature, err := schnorr.Sign(privKey, sigHash) 161 if err != nil { 162 return nil, err 163 } 164 165 // Finally, append the sighash type to the final sig if it's not the 166 // default sighash value (in which case appending it is disallowed). 167 if hashType != SigHashDefault { 168 return append(signature.Serialize(), byte(hashType)), nil 169 } 170 171 // The default sighash case where we'll return _just_ the signature. 172 return signature.Serialize(), nil 173 } 174 175 // RawTxInSignature returns the serialized ECDSA signature for the input idx of 176 // the given transaction, with hashType appended to it. 177 func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte, 178 hashType SigHashType, key *btcec.PrivateKey) ([]byte, error) { 179 180 hash, err := CalcSignatureHash(subScript, hashType, tx, idx) 181 if err != nil { 182 return nil, err 183 } 184 signature := ecdsa.Sign(key, hash) 185 186 return append(signature.Serialize(), byte(hashType)), nil 187 } 188 189 // SignatureScript creates an input signature script for tx to spend BTC sent 190 // from a previous output to the owner of privKey. tx must include all 191 // transaction inputs and outputs, however txin scripts are allowed to be filled 192 // or empty. The returned script is calculated to be used as the idx'th txin 193 // sigscript for tx. subscript is the PkScript of the previous output being used 194 // as the idx'th input. privKey is serialized in either a compressed or 195 // uncompressed format based on compress. This format must match the same format 196 // used to generate the payment address, or the script validation will fail. 197 func SignatureScript(tx *wire.MsgTx, idx int, subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey, compress bool) ([]byte, error) { 198 sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey) 199 if err != nil { 200 return nil, err 201 } 202 203 pk := privKey.PubKey() 204 var pkData []byte 205 if compress { 206 pkData = pk.SerializeCompressed() 207 } else { 208 pkData = pk.SerializeUncompressed() 209 } 210 211 return NewScriptBuilder().AddData(sig).AddData(pkData).Script() 212 } 213 214 func p2pkSignatureScript(tx *wire.MsgTx, idx int, subScript []byte, hashType SigHashType, privKey *btcec.PrivateKey) ([]byte, error) { 215 sig, err := RawTxInSignature(tx, idx, subScript, hashType, privKey) 216 if err != nil { 217 return nil, err 218 } 219 220 return NewScriptBuilder().AddData(sig).Script() 221 } 222 223 // signMultiSig signs as many of the outputs in the provided multisig script as 224 // possible. It returns the generated script and a boolean if the script fulfils 225 // the contract (i.e. nrequired signatures are provided). Since it is arguably 226 // legal to not be able to sign any of the outputs, no error is returned. 227 func signMultiSig(tx *wire.MsgTx, idx int, subScript []byte, hashType SigHashType, 228 addresses []btcutil.Address, nRequired int, kdb KeyDB) ([]byte, bool) { 229 // We start with a single OP_FALSE to work around the (now standard) 230 // but in the reference implementation that causes a spurious pop at 231 // the end of OP_CHECKMULTISIG. 232 builder := NewScriptBuilder().AddOp(OP_FALSE) 233 signed := 0 234 for _, addr := range addresses { 235 key, _, err := kdb.GetKey(addr) 236 if err != nil { 237 continue 238 } 239 sig, err := RawTxInSignature(tx, idx, subScript, hashType, key) 240 if err != nil { 241 continue 242 } 243 244 builder.AddData(sig) 245 signed++ 246 if signed == nRequired { 247 break 248 } 249 250 } 251 252 script, _ := builder.Script() 253 return script, signed == nRequired 254 } 255 256 func sign(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int, 257 subScript []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB) ([]byte, 258 ScriptClass, []btcutil.Address, int, error) { 259 260 class, addresses, nrequired, err := ExtractPkScriptAddrs(subScript, 261 chainParams) 262 if err != nil { 263 return nil, NonStandardTy, nil, 0, err 264 } 265 266 switch class { 267 case PubKeyTy: 268 // look up key for address 269 key, _, err := kdb.GetKey(addresses[0]) 270 if err != nil { 271 return nil, class, nil, 0, err 272 } 273 274 script, err := p2pkSignatureScript(tx, idx, subScript, hashType, 275 key) 276 if err != nil { 277 return nil, class, nil, 0, err 278 } 279 280 return script, class, addresses, nrequired, nil 281 case PubKeyHashTy: 282 // look up key for address 283 key, compressed, err := kdb.GetKey(addresses[0]) 284 if err != nil { 285 return nil, class, nil, 0, err 286 } 287 288 script, err := SignatureScript(tx, idx, subScript, hashType, 289 key, compressed) 290 if err != nil { 291 return nil, class, nil, 0, err 292 } 293 294 return script, class, addresses, nrequired, nil 295 case ScriptHashTy: 296 script, err := sdb.GetScript(addresses[0]) 297 if err != nil { 298 return nil, class, nil, 0, err 299 } 300 301 return script, class, addresses, nrequired, nil 302 case MultiSigTy: 303 script, _ := signMultiSig(tx, idx, subScript, hashType, 304 addresses, nrequired, kdb) 305 return script, class, addresses, nrequired, nil 306 case NullDataTy: 307 return nil, class, nil, 0, 308 errors.New("can't sign NULLDATA transactions") 309 default: 310 return nil, class, nil, 0, 311 errors.New("can't sign unknown transactions") 312 } 313 } 314 315 // mergeMultiSig combines the two signature scripts sigScript and prevScript 316 // that both provide signatures for pkScript in output idx of tx. addresses 317 // and nRequired should be the results from extracting the addresses from 318 // pkScript. Since this function is internal only we assume that the arguments 319 // have come from other functions internally and thus are all consistent with 320 // each other, behaviour is undefined if this contract is broken. 321 // 322 // NOTE: This function is only valid for version 0 scripts. Since the function 323 // does not accept a script version, the results are undefined for other script 324 // versions. 325 func mergeMultiSig(tx *wire.MsgTx, idx int, addresses []btcutil.Address, 326 nRequired int, pkScript, sigScript, prevScript []byte) []byte { 327 328 // Nothing to merge if either the new or previous signature scripts are 329 // empty. 330 if len(sigScript) == 0 { 331 return prevScript 332 } 333 if len(prevScript) == 0 { 334 return sigScript 335 } 336 337 // Convenience function to avoid duplication. 338 var possibleSigs [][]byte 339 extractSigs := func(script []byte) error { 340 const scriptVersion = 0 341 tokenizer := MakeScriptTokenizer(scriptVersion, script) 342 for tokenizer.Next() { 343 if data := tokenizer.Data(); len(data) != 0 { 344 possibleSigs = append(possibleSigs, data) 345 } 346 } 347 return tokenizer.Err() 348 } 349 350 // Attempt to extract signatures from the two scripts. Return the other 351 // script that is intended to be merged in the case signature extraction 352 // fails for some reason. 353 if err := extractSigs(sigScript); err != nil { 354 return prevScript 355 } 356 if err := extractSigs(prevScript); err != nil { 357 return sigScript 358 } 359 360 // Now we need to match the signatures to pubkeys, the only real way to 361 // do that is to try to verify them all and match it to the pubkey 362 // that verifies it. we then can go through the addresses in order 363 // to build our script. Anything that doesn't parse or doesn't verify we 364 // throw away. 365 addrToSig := make(map[string][]byte) 366 sigLoop: 367 for _, sig := range possibleSigs { 368 369 // can't have a valid signature that doesn't at least have a 370 // hashtype, in practise it is even longer than this. but 371 // that'll be checked next. 372 if len(sig) < 1 { 373 continue 374 } 375 tSig := sig[:len(sig)-1] 376 hashType := SigHashType(sig[len(sig)-1]) 377 378 pSig, err := ecdsa.ParseDERSignature(tSig) 379 if err != nil { 380 continue 381 } 382 383 // We have to do this each round since hash types may vary 384 // between signatures and so the hash will vary. We can, 385 // however, assume no sigs etc are in the script since that 386 // would make the transaction nonstandard and thus not 387 // MultiSigTy, so we just need to hash the full thing. 388 hash := calcSignatureHash(pkScript, hashType, tx, idx) 389 390 for _, addr := range addresses { 391 // All multisig addresses should be pubkey addresses 392 // it is an error to call this internal function with 393 // bad input. 394 pkaddr := addr.(*btcutil.AddressPubKey) 395 396 pubKey := pkaddr.PubKey() 397 398 // If it matches we put it in the map. We only 399 // can take one signature per public key so if we 400 // already have one, we can throw this away. 401 if pSig.Verify(hash, pubKey) { 402 aStr := addr.EncodeAddress() 403 if _, ok := addrToSig[aStr]; !ok { 404 addrToSig[aStr] = sig 405 } 406 continue sigLoop 407 } 408 } 409 } 410 411 // Extra opcode to handle the extra arg consumed (due to previous bugs 412 // in the reference implementation). 413 builder := NewScriptBuilder().AddOp(OP_FALSE) 414 doneSigs := 0 415 // This assumes that addresses are in the same order as in the script. 416 for _, addr := range addresses { 417 sig, ok := addrToSig[addr.EncodeAddress()] 418 if !ok { 419 continue 420 } 421 builder.AddData(sig) 422 doneSigs++ 423 if doneSigs == nRequired { 424 break 425 } 426 } 427 428 // padding for missing ones. 429 for i := doneSigs; i < nRequired; i++ { 430 builder.AddOp(OP_0) 431 } 432 433 script, _ := builder.Script() 434 return script 435 } 436 437 // mergeScripts merges sigScript and prevScript assuming they are both 438 // partial solutions for pkScript spending output idx of tx. class, addresses 439 // and nrequired are the result of extracting the addresses from pkscript. 440 // The return value is the best effort merging of the two scripts. Calling this 441 // function with addresses, class and nrequired that do not match pkScript is 442 // an error and results in undefined behaviour. 443 // 444 // NOTE: This function is only valid for version 0 scripts. Since the function 445 // does not accept a script version, the results are undefined for other script 446 // versions. 447 func mergeScripts(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int, 448 pkScript []byte, class ScriptClass, addresses []btcutil.Address, 449 nRequired int, sigScript, prevScript []byte) []byte { 450 451 // TODO(oga) the scripthash and multisig paths here are overly 452 // inefficient in that they will recompute already known data. 453 // some internal refactoring could probably make this avoid needless 454 // extra calculations. 455 const scriptVersion = 0 456 switch class { 457 case ScriptHashTy: 458 // Nothing to merge if either the new or previous signature 459 // scripts are empty or fail to parse. 460 if len(sigScript) == 0 || 461 checkScriptParses(scriptVersion, sigScript) != nil { 462 463 return prevScript 464 } 465 if len(prevScript) == 0 || 466 checkScriptParses(scriptVersion, prevScript) != nil { 467 468 return sigScript 469 } 470 471 // Remove the last push in the script and then recurse. 472 // this could be a lot less inefficient. 473 // 474 // Assume that final script is the correct one since it was just 475 // made and it is a pay-to-script-hash. 476 script := finalOpcodeData(scriptVersion, sigScript) 477 478 // We already know this information somewhere up the stack, 479 // therefore the error is ignored. 480 class, addresses, nrequired, _ := 481 ExtractPkScriptAddrs(script, chainParams) 482 483 // Merge 484 mergedScript := mergeScripts(chainParams, tx, idx, script, 485 class, addresses, nrequired, sigScript, prevScript) 486 487 // Reappend the script and return the result. 488 builder := NewScriptBuilder() 489 builder.AddOps(mergedScript) 490 builder.AddData(script) 491 finalScript, _ := builder.Script() 492 return finalScript 493 494 case MultiSigTy: 495 return mergeMultiSig(tx, idx, addresses, nRequired, pkScript, 496 sigScript, prevScript) 497 498 // It doesn't actually make sense to merge anything other than multiig 499 // and scripthash (because it could contain multisig). Everything else 500 // has either zero signature, can't be spent, or has a single signature 501 // which is either present or not. The other two cases are handled 502 // above. In the conflict case here we just assume the longest is 503 // correct (this matches behaviour of the reference implementation). 504 default: 505 if len(sigScript) > len(prevScript) { 506 return sigScript 507 } 508 return prevScript 509 } 510 } 511 512 // KeyDB is an interface type provided to SignTxOutput, it encapsulates 513 // any user state required to get the private keys for an address. 514 type KeyDB interface { 515 GetKey(btcutil.Address) (*btcec.PrivateKey, bool, error) 516 } 517 518 // KeyClosure implements KeyDB with a closure. 519 type KeyClosure func(btcutil.Address) (*btcec.PrivateKey, bool, error) 520 521 // GetKey implements KeyDB by returning the result of calling the closure. 522 func (kc KeyClosure) GetKey(address btcutil.Address) (*btcec.PrivateKey, bool, error) { 523 return kc(address) 524 } 525 526 // ScriptDB is an interface type provided to SignTxOutput, it encapsulates any 527 // user state required to get the scripts for an pay-to-script-hash address. 528 type ScriptDB interface { 529 GetScript(btcutil.Address) ([]byte, error) 530 } 531 532 // ScriptClosure implements ScriptDB with a closure. 533 type ScriptClosure func(btcutil.Address) ([]byte, error) 534 535 // GetScript implements ScriptDB by returning the result of calling the closure. 536 func (sc ScriptClosure) GetScript(address btcutil.Address) ([]byte, error) { 537 return sc(address) 538 } 539 540 // SignTxOutput signs output idx of the given tx to resolve the script given in 541 // pkScript with a signature type of hashType. Any keys required will be 542 // looked up by calling getKey() with the string of the given address. 543 // Any pay-to-script-hash signatures will be similarly looked up by calling 544 // getScript. If previousScript is provided then the results in previousScript 545 // will be merged in a type-dependent manner with the newly generated. 546 // signature script. 547 // 548 // NOTE: This function is only valid for version 0 scripts. Since the function 549 // does not accept a script version, the results are undefined for other script 550 // versions. 551 func SignTxOutput(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int, 552 pkScript []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB, 553 previousScript []byte) ([]byte, error) { 554 555 sigScript, class, addresses, nrequired, err := sign(chainParams, tx, 556 idx, pkScript, hashType, kdb, sdb) 557 if err != nil { 558 return nil, err 559 } 560 561 if class == ScriptHashTy { 562 // TODO keep the sub addressed and pass down to merge. 563 realSigScript, _, _, _, err := sign(chainParams, tx, idx, 564 sigScript, hashType, kdb, sdb) 565 if err != nil { 566 return nil, err 567 } 568 569 // Append the p2sh script as the last push in the script. 570 builder := NewScriptBuilder() 571 builder.AddOps(realSigScript) 572 builder.AddData(sigScript) 573 574 sigScript, _ = builder.Script() 575 // TODO keep a copy of the script for merging. 576 } 577 578 // Merge scripts. with any previous data, if any. 579 mergedScript := mergeScripts(chainParams, tx, idx, pkScript, class, 580 addresses, nrequired, sigScript, previousScript) 581 return mergedScript, nil 582 }