sign.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. package txscript
  5. import (
  6. "github.com/pkt-cash/pktd/btcutil/er"
  7. "github.com/pkt-cash/pktd/txscript/opcode"
  8. "github.com/pkt-cash/pktd/txscript/params"
  9. "github.com/pkt-cash/pktd/txscript/parsescript"
  10. "github.com/pkt-cash/pktd/txscript/scriptbuilder"
  11. "github.com/pkt-cash/pktd/btcec"
  12. "github.com/pkt-cash/pktd/btcutil"
  13. "github.com/pkt-cash/pktd/chaincfg"
  14. "github.com/pkt-cash/pktd/wire"
  15. )
  16. // RawTxInWitnessSignature returns the serialized ECDA signature for the input
  17. // idx of the given transaction, with the hashType appended to it. This
  18. // function is identical to RawTxInSignature, however the signature generated
  19. // signs a new sighash digest defined in BIP0143.
  20. func RawTxInWitnessSignature(tx *wire.MsgTx, sigHashes *TxSigHashes, idx int,
  21. amt int64, subScript []byte, hashType params.SigHashType,
  22. key *btcec.PrivateKey) ([]byte, er.R) {
  23. parsedScript, err := parsescript.ParseScript(subScript)
  24. if err != nil {
  25. return nil, er.Errorf("cannot parse output script: %v", err)
  26. }
  27. hash, err := calcWitnessSignatureHash(parsedScript, sigHashes, hashType, tx,
  28. idx, amt)
  29. if err != nil {
  30. return nil, err
  31. }
  32. signature, err := key.Sign(hash)
  33. if err != nil {
  34. return nil, er.Errorf("cannot sign tx input: %s", err)
  35. }
  36. return append(signature.Serialize(), byte(hashType)), nil
  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 params.SigHashType, privKey *btcec.PrivateKey,
  45. compress bool) (wire.TxWitness, er.R) {
  46. sig, err := RawTxInWitnessSignature(tx, sigHashes, idx, amt, subscript,
  47. hashType, privKey)
  48. if err != nil {
  49. return nil, err
  50. }
  51. pk := (*btcec.PublicKey)(&privKey.PublicKey)
  52. var pkData []byte
  53. if compress {
  54. pkData = pk.SerializeCompressed()
  55. } else {
  56. pkData = pk.SerializeUncompressed()
  57. }
  58. // A witness script is actually a stack, so we return an array of byte
  59. // slices here, rather than a single byte slice.
  60. return wire.TxWitness{sig, pkData}, nil
  61. }
  62. // RawTxInSignature returns the serialized ECDSA signature for the input idx of
  63. // the given transaction, with hashType appended to it.
  64. func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte,
  65. hashType params.SigHashType, key *btcec.PrivateKey) ([]byte, er.R) {
  66. hash, err := CalcSignatureHash(subScript, hashType, tx, idx)
  67. if err != nil {
  68. return nil, err
  69. }
  70. signature, err := key.Sign(hash)
  71. if err != nil {
  72. return nil, er.Errorf("cannot sign tx input: %s", err)
  73. }
  74. return append(signature.Serialize(), byte(hashType)), nil
  75. }
  76. // SignatureScript creates an input signature script for tx to spend BTC sent
  77. // from a previous output to the owner of privKey. tx must include all
  78. // transaction inputs and outputs, however txin scripts are allowed to be filled
  79. // or empty. The returned script is calculated to be used as the idx'th txin
  80. // sigscript for tx. subscript is the PkScript of the previous output being used
  81. // as the idx'th input. privKey is serialized in either a compressed or
  82. // uncompressed format based on compress. This format must match the same format
  83. // used to generate the payment address, or the script validation will fail.
  84. func SignatureScript(tx *wire.MsgTx, idx int, subscript []byte, hashType params.SigHashType, privKey *btcec.PrivateKey, compress bool) ([]byte, er.R) {
  85. sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey)
  86. if err != nil {
  87. return nil, err
  88. }
  89. pk := (*btcec.PublicKey)(&privKey.PublicKey)
  90. var pkData []byte
  91. if compress {
  92. pkData = pk.SerializeCompressed()
  93. } else {
  94. pkData = pk.SerializeUncompressed()
  95. }
  96. return scriptbuilder.NewScriptBuilder().AddData(sig).AddData(pkData).Script()
  97. }
  98. func p2pkSignatureScript(tx *wire.MsgTx, idx int, subScript []byte, hashType params.SigHashType, privKey *btcec.PrivateKey) ([]byte, er.R) {
  99. sig, err := RawTxInSignature(tx, idx, subScript, hashType, privKey)
  100. if err != nil {
  101. return nil, err
  102. }
  103. return scriptbuilder.NewScriptBuilder().AddData(sig).Script()
  104. }
  105. // signMultiSig signs as many of the outputs in the provided multisig script as
  106. // possible. It returns the generated script and a boolean if the script fulfills
  107. // the contract (i.e. nrequired signatures are provided). Since it is arguably
  108. // legal to not be able to sign any of the outputs, no error is returned.
  109. func signMultiSig(tx *wire.MsgTx, idx int, subScript []byte, hashType params.SigHashType,
  110. addresses []btcutil.Address, nRequired int, kdb KeyDB) ([]byte, bool) {
  111. // We start with a single OP_FALSE to work around the (now standard)
  112. // but in the reference implementation that causes a spurious pop at
  113. // the end of OP_CHECKMULTISIG.
  114. builder := scriptbuilder.NewScriptBuilder().AddOp(opcode.OP_FALSE)
  115. signed := 0
  116. for _, addr := range addresses {
  117. key, _, err := kdb.GetKey(addr)
  118. if err != nil {
  119. continue
  120. }
  121. sig, err := RawTxInSignature(tx, idx, subScript, hashType, key)
  122. if err != nil {
  123. continue
  124. }
  125. builder.AddData(sig)
  126. signed++
  127. if signed == nRequired {
  128. break
  129. }
  130. }
  131. script, _ := builder.Script()
  132. return script, signed == nRequired
  133. }
  134. func sign(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
  135. subScript []byte, hashType params.SigHashType, kdb KeyDB, sdb ScriptDB) ([]byte,
  136. ScriptClass, []btcutil.Address, int, er.R) {
  137. class, addresses, nrequired, err := ExtractPkScriptAddrs(subScript,
  138. chainParams)
  139. if err != nil {
  140. return nil, NonStandardTy, nil, 0, err
  141. }
  142. switch class {
  143. case PubKeyTy:
  144. // look up key for address
  145. key, _, err := kdb.GetKey(addresses[0])
  146. if err != nil {
  147. return nil, class, nil, 0, err
  148. }
  149. script, err := p2pkSignatureScript(tx, idx, subScript, hashType,
  150. key)
  151. if err != nil {
  152. return nil, class, nil, 0, err
  153. }
  154. return script, class, addresses, nrequired, nil
  155. case PubKeyHashTy:
  156. // look up key for address
  157. key, compressed, err := kdb.GetKey(addresses[0])
  158. if err != nil {
  159. return nil, class, nil, 0, err
  160. }
  161. script, err := SignatureScript(tx, idx, subScript, hashType,
  162. key, compressed)
  163. if err != nil {
  164. return nil, class, nil, 0, err
  165. }
  166. return script, class, addresses, nrequired, nil
  167. case ScriptHashTy:
  168. script, err := sdb.GetScript(addresses[0])
  169. if err != nil {
  170. return nil, class, nil, 0, err
  171. }
  172. return script, class, addresses, nrequired, nil
  173. case MultiSigTy:
  174. script, _ := signMultiSig(tx, idx, subScript, hashType,
  175. addresses, nrequired, kdb)
  176. return script, class, addresses, nrequired, nil
  177. case NullDataTy:
  178. return nil, class, nil, 0,
  179. er.New("can't sign NULLDATA transactions")
  180. default:
  181. return nil, class, nil, 0,
  182. er.Errorf("can't sign unknown transactions: class = [%v]", class)
  183. }
  184. }
  185. // mergeScripts merges sigScript and prevScript assuming they are both
  186. // partial solutions for pkScript spending output idx of tx. class, addresses
  187. // and nrequired are the result of extracting the addresses from pkscript.
  188. // The return value is the best effort merging of the two scripts. Calling this
  189. // function with addresses, class and nrequired that do not match pkScript is
  190. // an error and results in undefined behavior.
  191. func mergeScripts(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
  192. pkScript []byte, class ScriptClass, addresses []btcutil.Address,
  193. nRequired int, sigScript, prevScript []byte) []byte {
  194. // TODO: the scripthash and multisig paths here are overly
  195. // inefficient in that they will recompute already known data.
  196. // some internal refactoring could probably make this avoid needless
  197. // extra calculations.
  198. switch class {
  199. case ScriptHashTy:
  200. // Remove the last push in the script and then recurse.
  201. // this could be a lot less inefficient.
  202. sigPops, err := parsescript.ParseScript(sigScript)
  203. if err != nil || len(sigPops) == 0 {
  204. return prevScript
  205. }
  206. prevPops, err := parsescript.ParseScript(prevScript)
  207. if err != nil || len(prevPops) == 0 {
  208. return sigScript
  209. }
  210. // assume that script in sigPops is the correct one, we just
  211. // made it.
  212. script := sigPops[len(sigPops)-1].Data
  213. // We already know this information somewhere up the stack.
  214. class, addresses, nrequired, _ :=
  215. ExtractPkScriptAddrs(script, chainParams)
  216. // regenerate scripts.
  217. sigScript, _ := unparseScript(sigPops)
  218. prevScript, _ := unparseScript(prevPops)
  219. // Merge
  220. mergedScript := mergeScripts(chainParams, tx, idx, script,
  221. class, addresses, nrequired, sigScript, prevScript)
  222. // Reappend the script and return the result.
  223. builder := scriptbuilder.NewScriptBuilder()
  224. builder.AddOps(mergedScript)
  225. builder.AddData(script)
  226. finalScript, _ := builder.Script()
  227. return finalScript
  228. case MultiSigTy:
  229. return mergeMultiSig(tx, idx, addresses, nRequired, pkScript,
  230. sigScript, prevScript)
  231. // It doesn't actually make sense to merge anything other than multiig
  232. // and scripthash (because it could contain multisig). Everything else
  233. // has either zero signature, can't be spent, or has a single signature
  234. // which is either present or not. The other two cases are handled
  235. // above. In the conflict case here we just assume the longest is
  236. // correct (this matches behavior of the reference implementation).
  237. default:
  238. if len(sigScript) > len(prevScript) {
  239. return sigScript
  240. }
  241. return prevScript
  242. }
  243. }
  244. // mergeMultiSig combines the two signature scripts sigScript and prevScript
  245. // that both provide signatures for pkScript in output idx of tx. addresses
  246. // and nRequired should be the results from extracting the addresses from
  247. // pkScript. Since this function is internal only we assume that the arguments
  248. // have come from other functions internally and thus are all consistent with
  249. // each other, behavior is undefined if this contract is broken.
  250. func mergeMultiSig(tx *wire.MsgTx, idx int, addresses []btcutil.Address,
  251. nRequired int, pkScript, sigScript, prevScript []byte) []byte {
  252. // This is an internal only function and we already parsed this script
  253. // as ok for multisig (this is how we got here), so if this fails then
  254. // all assumptions are broken and who knows which way is up?
  255. pkPops, _ := parsescript.ParseScript(pkScript)
  256. sigPops, err := parsescript.ParseScript(sigScript)
  257. if err != nil || len(sigPops) == 0 {
  258. return prevScript
  259. }
  260. prevPops, err := parsescript.ParseScript(prevScript)
  261. if err != nil || len(prevPops) == 0 {
  262. return sigScript
  263. }
  264. // Convenience function to avoid duplication.
  265. extractSigs := func(pops []parsescript.ParsedOpcode, sigs [][]byte) [][]byte {
  266. for _, pop := range pops {
  267. if len(pop.Data) != 0 {
  268. sigs = append(sigs, pop.Data)
  269. }
  270. }
  271. return sigs
  272. }
  273. possibleSigs := make([][]byte, 0, len(sigPops)+len(prevPops))
  274. possibleSigs = extractSigs(sigPops, possibleSigs)
  275. possibleSigs = extractSigs(prevPops, possibleSigs)
  276. // Now we need to match the signatures to pubkeys, the only real way to
  277. // do that is to try to verify them all and match it to the pubkey
  278. // that verifies it. we then can go through the addresses in order
  279. // to build our script. Anything that doesn't parse or doesn't verify we
  280. // throw away.
  281. addrToSig := make(map[string][]byte)
  282. sigLoop:
  283. for _, sig := range possibleSigs {
  284. // can't have a valid signature that doesn't at least have a
  285. // hashtype, in practice it is even longer than this. but
  286. // that'll be checked next.
  287. if len(sig) < 1 {
  288. continue
  289. }
  290. tSig := sig[:len(sig)-1]
  291. hashType := params.SigHashType(sig[len(sig)-1])
  292. pSig, err := btcec.ParseDERSignature(tSig, btcec.S256())
  293. if err != nil {
  294. continue
  295. }
  296. // We have to do this each round since hash types may vary
  297. // between signatures and so the hash will vary. We can,
  298. // however, assume no sigs etc are in the script since that
  299. // would make the transaction nonstandard and thus not
  300. // MultiSigTy, so we just need to hash the full thing.
  301. hash := calcSignatureHash(pkPops, hashType, tx, idx)
  302. for _, addr := range addresses {
  303. // All multisig addresses should be pubkey addresses
  304. // it is an error to call this internal function with
  305. // bad input.
  306. pkaddr := addr.(*btcutil.AddressPubKey)
  307. if pkaddr == nil {
  308. panic("mergeMultiSig: pkaddr == nil")
  309. }
  310. pubKey := pkaddr.PubKey()
  311. if pubKey == nil {
  312. panic("mergeMultiSig: pubKey == nil")
  313. }
  314. // If it matches we put it in the map. We only
  315. // can take one signature per public key so if we
  316. // already have one, we can throw this away.
  317. if pSig.Verify(hash, pubKey) {
  318. aStr := addr.EncodeAddress()
  319. if _, ok := addrToSig[aStr]; !ok {
  320. addrToSig[aStr] = sig
  321. }
  322. continue sigLoop
  323. }
  324. }
  325. }
  326. // Extra opcode to handle the extra arg consumed (due to previous bugs
  327. // in the reference implementation).
  328. builder := scriptbuilder.NewScriptBuilder().AddOp(opcode.OP_FALSE)
  329. doneSigs := 0
  330. // This assumes that addresses are in the same order as in the script.
  331. for _, addr := range addresses {
  332. sig, ok := addrToSig[addr.EncodeAddress()]
  333. if !ok {
  334. continue
  335. }
  336. builder.AddData(sig)
  337. doneSigs++
  338. if doneSigs == nRequired {
  339. break
  340. }
  341. }
  342. // padding for missing ones.
  343. for i := doneSigs; i < nRequired; i++ {
  344. builder.AddOp(opcode.OP_0)
  345. }
  346. script, _ := builder.Script()
  347. return script
  348. }
  349. // KeyDB is an interface type provided to SignTxOutput, it encapsulates
  350. // any user state required to get the private keys for an address.
  351. type KeyDB interface {
  352. GetKey(btcutil.Address) (*btcec.PrivateKey, bool, er.R)
  353. }
  354. // KeyClosure implements KeyDB with a closure.
  355. type KeyClosure func(btcutil.Address) (*btcec.PrivateKey, bool, er.R)
  356. // GetKey implements KeyDB by returning the result of calling the closure.
  357. func (kc KeyClosure) GetKey(address btcutil.Address) (*btcec.PrivateKey,
  358. bool, er.R) {
  359. return kc(address)
  360. }
  361. // ScriptDB is an interface type provided to SignTxOutput, it encapsulates any
  362. // user state required to get the scripts for an pay-to-script-hash address.
  363. type ScriptDB interface {
  364. GetScript(btcutil.Address) ([]byte, er.R)
  365. }
  366. // ScriptClosure implements ScriptDB with a closure.
  367. type ScriptClosure func(btcutil.Address) ([]byte, er.R)
  368. // GetScript implements ScriptDB by returning the result of calling the closure.
  369. func (sc ScriptClosure) GetScript(address btcutil.Address) ([]byte, er.R) {
  370. return sc(address)
  371. }
  372. // SignTxOutput signs output idx of the given tx to resolve the script given in
  373. // pkScript with a signature type of hashType. Any keys required will be
  374. // looked up by calling getKey() with the string of the given address.
  375. // Any pay-to-script-hash signatures will be similarly looked up by calling
  376. // getScript. If previousScript is provided then the results in previousScript
  377. // will be merged in a type-dependent manner with the newly generated.
  378. // signature script.
  379. func SignTxOutput(chainParams *chaincfg.Params, tx *wire.MsgTx, idx int,
  380. pkScript []byte, hashType params.SigHashType, kdb KeyDB, sdb ScriptDB,
  381. previousScript []byte) ([]byte, er.R) {
  382. sigScript, class, addresses, nrequired, err := sign(chainParams, tx,
  383. idx, pkScript, hashType, kdb, sdb)
  384. if err != nil {
  385. return nil, err
  386. }
  387. if class == ScriptHashTy {
  388. // TODO keep the sub addressed and pass down to merge.
  389. realSigScript, _, _, _, err := sign(chainParams, tx, idx,
  390. sigScript, hashType, kdb, sdb)
  391. if err != nil {
  392. return nil, err
  393. }
  394. // Append the p2sh script as the last push in the script.
  395. builder := scriptbuilder.NewScriptBuilder()
  396. builder.AddOps(realSigScript)
  397. builder.AddData(sigScript)
  398. sigScript, _ = builder.Script()
  399. // TODO keep a copy of the script for merging.
  400. }
  401. // Merge scripts. with any previous data, if any.
  402. mergedScript := mergeScripts(chainParams, tx, idx, pkScript, class,
  403. addresses, nrequired, sigScript, previousScript)
  404. return mergedScript, nil
  405. }