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.
11 "github.com/btcsuite/btcd/btcec"
12 "github.com/btcsuite/btcd/chaincfg"
13 "github.com/btcsuite/btcd/wire"
14 "github.com/btcsuite/btcutil"
17 // RawTxInWitnessSignature returns the serialized ECDA signature for the input
18 // idx of the given transaction, with the hashType appended to it. This
19 // function is identical to RawTxInSignature, however the signature generated
20 // signs a new sighash digest defined in BIP0143.
21 func RawTxInWitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int,
22 amt int64, subScript []byte, hashType SigHashType,
23 key *btcec.PrivateKey) ([]byte, error) {
25 parsedScript, err := parseScript(subScript)
27 return nil, fmt.Errorf("cannot parse output script: %v", err)
30 hash, err := calcWitnessSignatureHash(parsedScript, sigHashes, hashType, tx,
36 signature, err := key.Sign(hash)
38 return nil, fmt.Errorf("cannot sign tx input: %s", err)
41 return append(signature.Serialize(), byte(hashType)), nil
44 // WitnessSignature creates an input witness stack for tx to spend BTC sent
45 // from a previous output to the owner of privKey using the p2wkh script
46 // template. The passed transaction must contain all the inputs and outputs as
47 // dictated by the passed hashType. The signature generated observes the new
48 // transaction digest algorithm defined within BIP0143.
49 func WitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int, amt int64,
50 subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey,
51 compress bool) (wire.TxWitness, error) {
53 sig, err := RawTxInWitnessSignature(tx, sigHashes, idx, amt, subscript,
59 pk := (*btcec.PublicKey)(&privKey.PublicKey)
62 pkData = pk.SerializeCompressed()
64 pkData = pk.SerializeUncompressed()
67 // A witness script is actually a stack, so we return an array of byte
68 // slices here, rather than a single byte slice.
69 return wire.TxWitness{sig, pkData}, nil
72 // RawTxInSignature returns the serialized ECDSA signature for the input idx of
73 // the given transaction, with hashType appended to it.
74 func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte,
75 hashType SigHashType, key *btcec.PrivateKey) ([]byte, error) {
77 parsedScript, err := parseScript(subScript)
79 return nil, fmt.Errorf("cannot parse output script: %v", err)
81 hash := calcSignatureHash(parsedScript, hashType, tx, idx)
82 signature, err := key.Sign(hash)
84 return nil, fmt.Errorf("cannot sign tx input: %s", err)
87 return append(signature.Serialize(), byte(hashType)), nil
90 // SignatureScript creates an input signature script for tx to spend BTC sent
91 // from a previous output to the owner of privKey. tx must include all
92 // transaction inputs and outputs, however txin scripts are allowed to be filled
93 // or empty. The returned script is calculated to be used as the idx'th txin
94 // sigscript for tx. subscript is the PkScript of the previous output being used
95 // as the idx'th input. privKey is serialized in either a compressed or
96 // uncompressed format based on compress. This format must match the same format
97 // used to generate the payment address, or the script validation will fail.
98 func SignatureScript(tx *wire.MsgTx, idx int, subscript []byte, hashType SigHashType, privKey *btcec.PrivateKey, compress bool) ([]byte, error) {
99 sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey)
104 pk := (*btcec.PublicKey)(&privKey.PublicKey)
107 pkData = pk.SerializeCompressed()
109 pkData = pk.SerializeUncompressed()
112 return NewScriptBuilder().AddData(sig).AddData(pkData).Script()
115 func p2pkSignatureScript(tx *wire.MsgTx, idx int, subScript []byte, hashType SigHashType, privKey *btcec.PrivateKey) ([]byte, error) {
116 sig, err := RawTxInSignature(tx, idx, subScript, hashType, privKey)
121 return NewScriptBuilder().AddData(sig).Script()
124 // signMultiSig signs as many of the outputs in the provided multisig script as
125 // possible. It returns the generated script and a boolean if the script fulfils
126 // the contract (i.e. nrequired signatures are provided). Since it is arguably
127 // legal to not be able to sign any of the outputs, no error is returned.
128 func signMultiSig(tx *wire.MsgTx, idx int, subScript []byte, hashType SigHashType,
129 addresses []btcutil.Address, nRequired int, kdb KeyDB) ([]byte, bool) {
130 // We start with a single OP_FALSE to work around the (now standard)
131 // but in the reference implementation that causes a spurious pop at
132 // the end of OP_CHECKMULTISIG.
133 builder := NewScriptBuilder().AddOp(OP_FALSE)
135 for _, addr := range addresses {
136 key, _, err := kdb.GetKey(addr)
140 sig, err := RawTxInSignature(tx, idx, subScript, hashType, key)
147 if signed == nRequired {
153 script, _ := builder.Script()
154 return script, signed == nRequired
157 func sign(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
158 subScript []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB) ([]byte,
159 ScriptClass, []btcutil.Address, int, error) {
161 class, addresses, nrequired, err := ExtractPkScriptAddrs(subScript,
164 return nil, NonStandardTy, nil, 0, err
169 // look up key for address
170 key, _, err := kdb.GetKey(addresses[0])
172 return nil, class, nil, 0, err
175 script, err := p2pkSignatureScript(tx, idx, subScript, hashType,
178 return nil, class, nil, 0, err
181 return script, class, addresses, nrequired, nil
183 // look up key for address
184 key, compressed, err := kdb.GetKey(addresses[0])
186 return nil, class, nil, 0, err
189 script, err := SignatureScript(tx, idx, subScript, hashType,
192 return nil, class, nil, 0, err
195 return script, class, addresses, nrequired, nil
197 script, err := sdb.GetScript(addresses[0])
199 return nil, class, nil, 0, err
202 return script, class, addresses, nrequired, nil
204 script, _ := signMultiSig(tx, idx, subScript, hashType,
205 addresses, nrequired, kdb)
206 return script, class, addresses, nrequired, nil
208 return nil, class, nil, 0,
209 errors.New("can't sign NULLDATA transactions")
211 return nil, class, nil, 0,
212 errors.New("can't sign unknown transactions")
216 // mergeScripts merges sigScript and prevScript assuming they are both
217 // partial solutions for pkScript spending output idx of tx. class, addresses
218 // and nrequired are the result of extracting the addresses from pkscript.
219 // The return value is the best effort merging of the two scripts. Calling this
220 // function with addresses, class and nrequired that do not match pkScript is
221 // an error and results in undefined behaviour.
222 func mergeScripts(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
223 pkScript []byte, class ScriptClass, addresses []btcutil.Address,
224 nRequired int, sigScript, prevScript []byte) []byte {
226 // TODO: the scripthash and multisig paths here are overly
227 // inefficient in that they will recompute already known data.
228 // some internal refactoring could probably make this avoid needless
229 // extra calculations.
232 // Remove the last push in the script and then recurse.
233 // this could be a lot less inefficient.
234 sigPops, err := parseScript(sigScript)
235 if err != nil || len(sigPops) == 0 {
238 prevPops, err := parseScript(prevScript)
239 if err != nil || len(prevPops) == 0 {
243 // assume that script in sigPops is the correct one, we just
245 script := sigPops[len(sigPops)-1].data
247 // We already know this information somewhere up the stack.
248 class, addresses, nrequired, _ :=
249 ExtractPkScriptAddrs(script, chainParams)
251 // regenerate scripts.
252 sigScript, _ := unparseScript(sigPops)
253 prevScript, _ := unparseScript(prevPops)
256 mergedScript := mergeScripts(chainParams, tx, idx, script,
257 class, addresses, nrequired, sigScript, prevScript)
259 // Reappend the script and return the result.
260 builder := NewScriptBuilder()
261 builder.AddOps(mergedScript)
262 builder.AddData(script)
263 finalScript, _ := builder.Script()
266 return mergeMultiSig(tx, idx, addresses, nRequired, pkScript,
267 sigScript, prevScript)
269 // It doesn't actually make sense to merge anything other than multiig
270 // and scripthash (because it could contain multisig). Everything else
271 // has either zero signature, can't be spent, or has a single signature
272 // which is either present or not. The other two cases are handled
273 // above. In the conflict case here we just assume the longest is
274 // correct (this matches behaviour of the reference implementation).
276 if len(sigScript) > len(prevScript) {
283 // mergeMultiSig combines the two signature scripts sigScript and prevScript
284 // that both provide signatures for pkScript in output idx of tx. addresses
285 // and nRequired should be the results from extracting the addresses from
286 // pkScript. Since this function is internal only we assume that the arguments
287 // have come from other functions internally and thus are all consistent with
288 // each other, behaviour is undefined if this contract is broken.
289 func mergeMultiSig(tx *wire.MsgTx, idx int, addresses []btcutil.Address,
290 nRequired int, pkScript, sigScript, prevScript []byte) []byte {
292 // This is an internal only function and we already parsed this script
293 // as ok for multisig (this is how we got here), so if this fails then
294 // all assumptions are broken and who knows which way is up?
295 pkPops, _ := parseScript(pkScript)
297 sigPops, err := parseScript(sigScript)
298 if err != nil || len(sigPops) == 0 {
302 prevPops, err := parseScript(prevScript)
303 if err != nil || len(prevPops) == 0 {
307 // Convenience function to avoid duplication.
308 extractSigs := func(pops []parsedOpcode, sigs [][]byte) [][]byte {
309 for _, pop := range pops {
310 if len(pop.data) != 0 {
311 sigs = append(sigs, pop.data)
317 possibleSigs := make([][]byte, 0, len(sigPops)+len(prevPops))
318 possibleSigs = extractSigs(sigPops, possibleSigs)
319 possibleSigs = extractSigs(prevPops, possibleSigs)
321 // Now we need to match the signatures to pubkeys, the only real way to
322 // do that is to try to verify them all and match it to the pubkey
323 // that verifies it. we then can go through the addresses in order
324 // to build our script. Anything that doesn't parse or doesn't verify we
326 addrToSig := make(map[string][]byte)
328 for _, sig := range possibleSigs {
330 // can't have a valid signature that doesn't at least have a
331 // hashtype, in practise it is even longer than this. but
332 // that'll be checked next.
336 tSig := sig[:len(sig)-1]
337 hashType := SigHashType(sig[len(sig)-1])
339 pSig, err := btcec.ParseDERSignature(tSig, btcec.S256())
344 // We have to do this each round since hash types may vary
345 // between signatures and so the hash will vary. We can,
346 // however, assume no sigs etc are in the script since that
347 // would make the transaction nonstandard and thus not
348 // MultiSigTy, so we just need to hash the full thing.
349 hash := calcSignatureHash(pkPops, hashType, tx, idx)
351 for _, addr := range addresses {
352 // All multisig addresses should be pubkey addresses
353 // it is an error to call this internal function with
355 pkaddr := addr.(*btcutil.AddressPubKey)
357 pubKey := pkaddr.PubKey()
359 // If it matches we put it in the map. We only
360 // can take one signature per public key so if we
361 // already have one, we can throw this away.
362 if pSig.Verify(hash, pubKey) {
363 aStr := addr.EncodeAddress()
364 if _, ok := addrToSig[aStr]; !ok {
365 addrToSig[aStr] = sig
372 // Extra opcode to handle the extra arg consumed (due to previous bugs
373 // in the reference implementation).
374 builder := NewScriptBuilder().AddOp(OP_FALSE)
376 // This assumes that addresses are in the same order as in the script.
377 for _, addr := range addresses {
378 sig, ok := addrToSig[addr.EncodeAddress()]
384 if doneSigs == nRequired {
389 // padding for missing ones.
390 for i := doneSigs; i < nRequired; i++ {
394 script, _ := builder.Script()
398 // KeyDB is an interface type provided to SignTxOutput, it encapsulates
399 // any user state required to get the private keys for an address.
400 type KeyDB interface {
401 GetKey(btcutil.Address) (*btcec.PrivateKey, bool, error)
404 // KeyClosure implements KeyDB with a closure.
405 type KeyClosure func(btcutil.Address) (*btcec.PrivateKey, bool, error)
407 // GetKey implements KeyDB by returning the result of calling the closure.
408 func (kc KeyClosure) GetKey(address btcutil.Address) (*btcec.PrivateKey,
413 // ScriptDB is an interface type provided to SignTxOutput, it encapsulates any
414 // user state required to get the scripts for an pay-to-script-hash address.
415 type ScriptDB interface {
416 GetScript(btcutil.Address) ([]byte, error)
419 // ScriptClosure implements ScriptDB with a closure.
420 type ScriptClosure func(btcutil.Address) ([]byte, error)
422 // GetScript implements ScriptDB by returning the result of calling the closure.
423 func (sc ScriptClosure) GetScript(address btcutil.Address) ([]byte, error) {
427 // SignTxOutput signs output idx of the given tx to resolve the script given in
428 // pkScript with a signature type of hashType. Any keys required will be
429 // looked up by calling getKey() with the string of the given address.
430 // Any pay-to-script-hash signatures will be similarly looked up by calling
431 // getScript. If previousScript is provided then the results in previousScript
432 // will be merged in a type-dependent manner with the newly generated.
434 func SignTxOutput(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
435 pkScript []byte, hashType SigHashType, kdb KeyDB, sdb ScriptDB,
436 previousScript []byte) ([]byte, error) {
438 sigScript, class, addresses, nrequired, err := sign(chainParams, tx,
439 idx, pkScript, hashType, kdb, sdb)
444 if class == ScriptHashTy {
445 // TODO keep the sub addressed and pass down to merge.
446 realSigScript, _, _, _, err := sign(chainParams, tx, idx,
447 sigScript, hashType, kdb, sdb)
452 // Append the p2sh script as the last push in the script.
453 builder := NewScriptBuilder()
454 builder.AddOps(realSigScript)
455 builder.AddData(sigScript)
457 sigScript, _ = builder.Script()
458 // TODO keep a copy of the script for merging.
461 // Merge scripts. with any previous data, if any.
462 mergedScript := mergeScripts(chainParams, tx, idx, pkScript, class,
463 addresses, nrequired, sigScript, previousScript)
464 return mergedScript, nil