updater.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Copyright (c) 2018 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 psbt
  5. // The Updater requires provision of a single PSBT and is able to add data to
  6. // both input and output sections. It can be called repeatedly to add more
  7. // data. It also allows addition of signatures via the addPartialSignature
  8. // function; this is called internally to the package in the Sign() function of
  9. // Updater, located in signer.go
  10. import (
  11. "bytes"
  12. sha256 "github.com/minio/sha256-simd"
  13. "github.com/pkt-cash/pktd/btcutil"
  14. "github.com/pkt-cash/pktd/btcutil/er"
  15. "github.com/pkt-cash/pktd/txscript/opcode"
  16. "github.com/pkt-cash/pktd/txscript/params"
  17. "github.com/pkt-cash/pktd/txscript/scriptbuilder"
  18. "github.com/pkt-cash/pktd/wire"
  19. )
  20. // Updater encapsulates the role 'Updater' as specified in BIP174; it accepts
  21. // Psbt structs and has methods to add fields to the inputs and outputs.
  22. type Updater struct {
  23. Upsbt *Packet
  24. }
  25. // NewUpdater returns a new instance of Updater, if the passed Psbt struct is
  26. // in a valid form, else an error.
  27. func NewUpdater(p *Packet) (*Updater, er.R) {
  28. if err := p.SanityCheck(); err != nil {
  29. return nil, err
  30. }
  31. return &Updater{Upsbt: p}, nil
  32. }
  33. // AddInNonWitnessUtxo adds the utxo information for an input which is
  34. // non-witness. This requires provision of a full transaction (which is the
  35. // source of the corresponding prevOut), and the input index. If addition of
  36. // this key-value pair to the Psbt fails, an error is returned.
  37. func (p *Updater) AddInNonWitnessUtxo(tx *wire.MsgTx, inIndex int) er.R {
  38. if inIndex > len(p.Upsbt.Inputs)-1 {
  39. return ErrInvalidPrevOutNonWitnessTransaction.Default()
  40. }
  41. p.Upsbt.Inputs[inIndex].NonWitnessUtxo = tx
  42. if err := p.Upsbt.SanityCheck(); err != nil {
  43. return ErrInvalidPsbtFormat.Default()
  44. }
  45. return nil
  46. }
  47. // AddInWitnessUtxo adds the utxo information for an input which is witness.
  48. // This requires provision of a full transaction *output* (which is the source
  49. // of the corresponding prevOut); not the full transaction because BIP143 means
  50. // the output information is sufficient, and the input index. If addition of
  51. // this key-value pair to the Psbt fails, an error is returned.
  52. func (p *Updater) AddInWitnessUtxo(txout *wire.TxOut, inIndex int) er.R {
  53. if inIndex > len(p.Upsbt.Inputs)-1 {
  54. return ErrInvalidPsbtFormat.Default()
  55. }
  56. p.Upsbt.Inputs[inIndex].WitnessUtxo = txout
  57. if err := p.Upsbt.SanityCheck(); err != nil {
  58. return ErrInvalidPsbtFormat.Default()
  59. }
  60. return nil
  61. }
  62. // addPartialSignature allows the Updater role to insert fields of type partial
  63. // signature into a Psbt, consisting of both the pubkey (as keydata) and the
  64. // ECDSA signature (as value). Note that the Signer role is encapsulated in
  65. // this function; signatures are only allowed to be added that follow the
  66. // sanity-check on signing rules explained in the BIP under `Signer`; if the
  67. // rules are not satisfied, an ErrInvalidSignatureForInput is returned.
  68. //
  69. // NOTE: This function does *not* validate the ECDSA signature itself.
  70. func (p *Updater) addPartialSignature(inIndex int, sig []byte,
  71. pubkey []byte) er.R {
  72. partialSig := PartialSig{
  73. PubKey: pubkey, Signature: sig,
  74. }
  75. // First validate the passed (sig, pub).
  76. if !partialSig.checkValid() {
  77. return ErrInvalidPsbtFormat.Default()
  78. }
  79. pInput := p.Upsbt.Inputs[inIndex]
  80. // First check; don't add duplicates.
  81. for _, x := range pInput.PartialSigs {
  82. if bytes.Equal(x.PubKey, partialSig.PubKey) {
  83. return ErrDuplicateKey.Default()
  84. }
  85. }
  86. // Attaching signature without utxo field is not allowed.
  87. if pInput.WitnessUtxo == nil && pInput.NonWitnessUtxo == nil {
  88. return ErrInvalidPsbtFormat.Default()
  89. }
  90. // Next, we perform a series of additional sanity checks.
  91. if pInput.NonWitnessUtxo != nil {
  92. if len(p.Upsbt.UnsignedTx.TxIn) < inIndex+1 {
  93. return ErrInvalidPrevOutNonWitnessTransaction.Default()
  94. }
  95. if pInput.NonWitnessUtxo.TxHash() !=
  96. p.Upsbt.UnsignedTx.TxIn[inIndex].PreviousOutPoint.Hash {
  97. return ErrInvalidSignatureForInput.Default()
  98. }
  99. // To validate that the redeem script matches, we must pull out
  100. // the scriptPubKey of the corresponding output and compare
  101. // that with the P2SH scriptPubKey that is generated by
  102. // redeemScript.
  103. if pInput.RedeemScript != nil {
  104. outIndex := p.Upsbt.UnsignedTx.TxIn[inIndex].PreviousOutPoint.Index
  105. scriptPubKey := pInput.NonWitnessUtxo.TxOut[outIndex].PkScript
  106. scriptHash := btcutil.Hash160(pInput.RedeemScript)
  107. scriptHashScript, err := scriptbuilder.NewScriptBuilder().
  108. AddOp(opcode.OP_HASH160).
  109. AddData(scriptHash).
  110. AddOp(opcode.OP_EQUAL).
  111. Script()
  112. if err != nil {
  113. return err
  114. }
  115. if !bytes.Equal(scriptHashScript, scriptPubKey) {
  116. return ErrInvalidSignatureForInput.Default()
  117. }
  118. }
  119. }
  120. // It could be that we set both the non-witness and witness UTXO fields
  121. // in case it's from a wallet that patched the CVE-2020-14199
  122. // vulnerability. We detect whether the input being spent is actually a
  123. // witness input and then copy it over to the witness UTXO field in the
  124. // signer. Run the witness checks as well, even if we might already have
  125. // checked the script hash. But that should be a negligible performance
  126. // penalty.
  127. if pInput.WitnessUtxo != nil {
  128. scriptPubKey := pInput.WitnessUtxo.PkScript
  129. var script []byte
  130. if pInput.RedeemScript != nil {
  131. scriptHash := btcutil.Hash160(pInput.RedeemScript)
  132. scriptHashScript, err := scriptbuilder.NewScriptBuilder().
  133. AddOp(opcode.OP_HASH160).
  134. AddData(scriptHash).
  135. AddOp(opcode.OP_EQUAL).
  136. Script()
  137. if err != nil {
  138. return err
  139. }
  140. if !bytes.Equal(scriptHashScript, scriptPubKey) {
  141. return ErrInvalidSignatureForInput.Default()
  142. }
  143. script = pInput.RedeemScript
  144. } else {
  145. script = scriptPubKey
  146. }
  147. // If a witnessScript field is present, this is a P2WSH,
  148. // whether nested or not (that is handled by the assignment to
  149. // `script` above); in that case, sanity check that `script` is
  150. // the p2wsh of witnessScript. Contrariwise, if no
  151. // witnessScript field is present, this will be signed as
  152. // p2wkh.
  153. if pInput.WitnessScript != nil {
  154. witnessScriptHash := sha256.Sum256(pInput.WitnessScript)
  155. witnessScriptHashScript, err := scriptbuilder.NewScriptBuilder().
  156. AddOp(opcode.OP_0).
  157. AddData(witnessScriptHash[:]).
  158. Script()
  159. if err != nil {
  160. return err
  161. }
  162. if !bytes.Equal(script, witnessScriptHashScript) {
  163. return ErrInvalidSignatureForInput.Default()
  164. }
  165. } else {
  166. // Otherwise, this is a p2wkh input.
  167. pubkeyHash := btcutil.Hash160(pubkey)
  168. pubkeyHashScript, err := scriptbuilder.NewScriptBuilder().
  169. AddOp(opcode.OP_0).
  170. AddData(pubkeyHash).
  171. Script()
  172. if err != nil {
  173. return err
  174. }
  175. // Validate that we're able to properly reconstruct the
  176. // witness program.
  177. if !bytes.Equal(pubkeyHashScript, script) {
  178. return ErrInvalidSignatureForInput.Default()
  179. }
  180. }
  181. }
  182. p.Upsbt.Inputs[inIndex].PartialSigs = append(
  183. p.Upsbt.Inputs[inIndex].PartialSigs, &partialSig,
  184. )
  185. if err := p.Upsbt.SanityCheck(); err != nil {
  186. return err
  187. }
  188. // Addition of a non-duplicate-key partial signature cannot violate
  189. // sanity-check rules.
  190. return nil
  191. }
  192. // AddInSighashType adds the sighash type information for an input. The
  193. // sighash type is passed as a 32 bit unsigned integer, along with the index
  194. // for the input. An error is returned if addition of this key-value pair to
  195. // the Psbt fails.
  196. func (p *Updater) AddInSighashType(sighashType params.SigHashType,
  197. inIndex int) er.R {
  198. p.Upsbt.Inputs[inIndex].SighashType = sighashType
  199. if err := p.Upsbt.SanityCheck(); err != nil {
  200. return err
  201. }
  202. return nil
  203. }
  204. // AddInRedeemScript adds the redeem script information for an input. The
  205. // redeem script is passed serialized, as a byte slice, along with the index of
  206. // the input. An error is returned if addition of this key-value pair to the
  207. // Psbt fails.
  208. func (p *Updater) AddInRedeemScript(redeemScript []byte,
  209. inIndex int) er.R {
  210. p.Upsbt.Inputs[inIndex].RedeemScript = redeemScript
  211. if err := p.Upsbt.SanityCheck(); err != nil {
  212. return ErrInvalidPsbtFormat.Default()
  213. }
  214. return nil
  215. }
  216. // AddInWitnessScript adds the witness script information for an input. The
  217. // witness script is passed serialized, as a byte slice, along with the index
  218. // of the input. An error is returned if addition of this key-value pair to the
  219. // Psbt fails.
  220. func (p *Updater) AddInWitnessScript(witnessScript []byte,
  221. inIndex int) er.R {
  222. p.Upsbt.Inputs[inIndex].WitnessScript = witnessScript
  223. if err := p.Upsbt.SanityCheck(); err != nil {
  224. return err
  225. }
  226. return nil
  227. }
  228. // AddInBip32Derivation takes a master key fingerprint as defined in BIP32, a
  229. // BIP32 path as a slice of uint32 values, and a serialized pubkey as a byte
  230. // slice, along with the integer index of the input, and inserts this data into
  231. // that input.
  232. //
  233. // NOTE: This can be called multiple times for the same input. An error is
  234. // returned if addition of this key-value pair to the Psbt fails.
  235. func (p *Updater) AddInBip32Derivation(masterKeyFingerprint uint32,
  236. bip32Path []uint32, pubKeyData []byte, inIndex int) er.R {
  237. bip32Derivation := Bip32Derivation{
  238. PubKey: pubKeyData,
  239. MasterKeyFingerprint: masterKeyFingerprint,
  240. Bip32Path: bip32Path,
  241. }
  242. if !bip32Derivation.checkValid() {
  243. return ErrInvalidPsbtFormat.Default()
  244. }
  245. // Don't allow duplicate keys
  246. for _, x := range p.Upsbt.Inputs[inIndex].Bip32Derivation {
  247. if bytes.Equal(x.PubKey, bip32Derivation.PubKey) {
  248. return ErrDuplicateKey.Default()
  249. }
  250. }
  251. p.Upsbt.Inputs[inIndex].Bip32Derivation = append(
  252. p.Upsbt.Inputs[inIndex].Bip32Derivation, &bip32Derivation,
  253. )
  254. if err := p.Upsbt.SanityCheck(); err != nil {
  255. return err
  256. }
  257. return nil
  258. }
  259. // AddOutBip32Derivation takes a master key fingerprint as defined in BIP32, a
  260. // BIP32 path as a slice of uint32 values, and a serialized pubkey as a byte
  261. // slice, along with the integer index of the output, and inserts this data
  262. // into that output.
  263. //
  264. // NOTE: That this can be called multiple times for the same output. An error
  265. // is returned if addition of this key-value pair to the Psbt fails.
  266. func (p *Updater) AddOutBip32Derivation(masterKeyFingerprint uint32,
  267. bip32Path []uint32, pubKeyData []byte, outIndex int) er.R {
  268. bip32Derivation := Bip32Derivation{
  269. PubKey: pubKeyData,
  270. MasterKeyFingerprint: masterKeyFingerprint,
  271. Bip32Path: bip32Path,
  272. }
  273. if !bip32Derivation.checkValid() {
  274. return ErrInvalidPsbtFormat.Default()
  275. }
  276. // Don't allow duplicate keys
  277. for _, x := range p.Upsbt.Outputs[outIndex].Bip32Derivation {
  278. if bytes.Equal(x.PubKey, bip32Derivation.PubKey) {
  279. return ErrDuplicateKey.Default()
  280. }
  281. }
  282. p.Upsbt.Outputs[outIndex].Bip32Derivation = append(
  283. p.Upsbt.Outputs[outIndex].Bip32Derivation, &bip32Derivation,
  284. )
  285. if err := p.Upsbt.SanityCheck(); err != nil {
  286. return err
  287. }
  288. return nil
  289. }
  290. // AddOutRedeemScript takes a redeem script as a byte slice and appends it to
  291. // the output at index outIndex.
  292. func (p *Updater) AddOutRedeemScript(redeemScript []byte,
  293. outIndex int) er.R {
  294. p.Upsbt.Outputs[outIndex].RedeemScript = redeemScript
  295. if err := p.Upsbt.SanityCheck(); err != nil {
  296. return ErrInvalidPsbtFormat.Default()
  297. }
  298. return nil
  299. }
  300. // AddOutWitnessScript takes a witness script as a byte slice and appends it to
  301. // the output at index outIndex.
  302. func (p *Updater) AddOutWitnessScript(witnessScript []byte,
  303. outIndex int) er.R {
  304. p.Upsbt.Outputs[outIndex].WitnessScript = witnessScript
  305. if err := p.Upsbt.SanityCheck(); err != nil {
  306. return err
  307. }
  308. return nil
  309. }