signingprovider.h raw

   1  // Copyright (c) 2009-2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-2022 The Limenka developers
   3  // Distributed under the MIT software license, see the accompanying
   4  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  
   6  #ifndef LIMENKA_SCRIPT_SIGNINGPROVIDER_H
   7  #define LIMENKA_SCRIPT_SIGNINGPROVIDER_H
   8  
   9  #include <addresstype.h>
  10  #include <attributes.h>
  11  #include <key.h>
  12  #include <pubkey.h>
  13  #include <script/keyorigin.h>
  14  #include <script/script.h>
  15  #include <sync.h>
  16  
  17  static const bool DEFAULT_WALLET_IMPLICIT_SEGWIT = false;
  18  
  19  extern bool g_implicit_segwit;
  20  
  21  struct ShortestVectorFirstComparator
  22  {
  23      bool operator()(const std::vector<unsigned char>& a, const std::vector<unsigned char>& b) const
  24      {
  25          if (a.size() < b.size()) return true;
  26          if (a.size() > b.size()) return false;
  27          return a < b;
  28      }
  29  };
  30  
  31  struct TaprootSpendData
  32  {
  33      /** The BIP341 internal key. */
  34      XOnlyPubKey internal_key;
  35      /** The Merkle root of the script tree (0 if no scripts). */
  36      uint256 merkle_root;
  37      /** Map from (script, leaf_version) to (sets of) control blocks.
  38       *  More than one control block for a given script is only possible if it
  39       *  appears in multiple branches of the tree. We keep them all so that
  40       *  inference can reconstruct the full tree. Within each set, the control
  41       *  blocks are sorted by size, so that the signing logic can easily
  42       *  prefer the cheapest one. */
  43      std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> scripts;
  44      /** Merge other TaprootSpendData (for the same scriptPubKey) into this. */
  45      void Merge(TaprootSpendData other);
  46  };
  47  
  48  /** Utility class to construct Taproot outputs from internal key and script tree. */
  49  class TaprootBuilder
  50  {
  51  private:
  52      /** Information about a tracked leaf in the Merkle tree. */
  53      struct LeafInfo
  54      {
  55          std::vector<unsigned char> script;   //!< The script.
  56          int leaf_version;                    //!< The leaf version for that script.
  57          std::vector<uint256> merkle_branch;  //!< The hashing partners above this leaf.
  58      };
  59  
  60      /** Information associated with a node in the Merkle tree. */
  61      struct NodeInfo
  62      {
  63          /** Merkle hash of this node. */
  64          uint256 hash;
  65          /** Tracked leaves underneath this node (either from the node itself, or its children).
  66           *  The merkle_branch field of each is the partners to get to *this* node. */
  67          std::vector<LeafInfo> leaves;
  68      };
  69      /** Whether the builder is in a valid state so far. */
  70      bool m_valid = true;
  71  
  72      /** The current state of the builder.
  73       *
  74       * For each level in the tree, one NodeInfo object may be present. m_branch[0]
  75       * is information about the root; further values are for deeper subtrees being
  76       * explored.
  77       *
  78       * For every right branch taken to reach the position we're currently
  79       * working in, there will be a (non-nullopt) entry in m_branch corresponding
  80       * to the left branch at that level.
  81       *
  82       * For example, imagine this tree:     - N0 -
  83       *                                    /      \
  84       *                                   N1      N2
  85       *                                  /  \    /  \
  86       *                                 A    B  C   N3
  87       *                                            /  \
  88       *                                           D    E
  89       *
  90       * Initially, m_branch is empty. After processing leaf A, it would become
  91       * {nullopt, nullopt, A}. When processing leaf B, an entry at level 2 already
  92       * exists, and it would thus be combined with it to produce a level 1 one,
  93       * resulting in {nullopt, N1}. Adding C and D takes us to {nullopt, N1, C}
  94       * and {nullopt, N1, C, D} respectively. When E is processed, it is combined
  95       * with D, and then C, and then N1, to produce the root, resulting in {N0}.
  96       *
  97       * This structure allows processing with just O(log n) overhead if the leaves
  98       * are computed on the fly.
  99       *
 100       * As an invariant, there can never be nullopt entries at the end. There can
 101       * also not be more than 128 entries (as that would mean more than 128 levels
 102       * in the tree). The depth of newly added entries will always be at least
 103       * equal to the current size of m_branch (otherwise it does not correspond
 104       * to a depth-first traversal of a tree). m_branch is only empty if no entries
 105       * have ever be processed. m_branch having length 1 corresponds to being done.
 106       */
 107      std::vector<std::optional<NodeInfo>> m_branch;
 108  
 109      XOnlyPubKey m_internal_key;  //!< The internal key, set when finalizing.
 110      XOnlyPubKey m_output_key;    //!< The output key, computed when finalizing.
 111      bool m_parity;               //!< The tweak parity, computed when finalizing.
 112  
 113      /** Combine information about a parent Merkle tree node from its child nodes. */
 114      static NodeInfo Combine(NodeInfo&& a, NodeInfo&& b);
 115      /** Insert information about a node at a certain depth, and propagate information up. */
 116      void Insert(NodeInfo&& node, int depth);
 117  
 118  public:
 119      /** Add a new script at a certain depth in the tree. Add() operations must be called
 120       *  in depth-first traversal order of binary tree. If track is true, it will be included in
 121       *  the GetSpendData() output. */
 122      TaprootBuilder& Add(int depth, Span<const unsigned char> script, int leaf_version, bool track = true);
 123      /** Like Add(), but for a Merkle node with a given hash to the tree. */
 124      TaprootBuilder& AddOmitted(int depth, const uint256& hash);
 125      /** Finalize the construction. Can only be called when IsComplete() is true.
 126          internal_key.IsFullyValid() must be true. */
 127      TaprootBuilder& Finalize(const XOnlyPubKey& internal_key);
 128  
 129      /** Return true if so far all input was valid. */
 130      bool IsValid() const { return m_valid; }
 131      /** Return whether there were either no leaves, or the leaves form a Huffman tree. */
 132      bool IsComplete() const { return m_valid && (m_branch.size() == 0 || (m_branch.size() == 1 && m_branch[0].has_value())); }
 133      /** Compute scriptPubKey (after Finalize()). */
 134      WitnessV1Taproot GetOutput();
 135      /** Check if a list of depths is legal (will lead to IsComplete()). */
 136      static bool ValidDepths(const std::vector<int>& depths);
 137      /** Compute spending data (after Finalize()). */
 138      TaprootSpendData GetSpendData() const;
 139      /** Returns a vector of tuples representing the depth, leaf version, and script */
 140      std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> GetTreeTuples() const;
 141      /** Returns true if there are any tapscripts */
 142      bool HasScripts() const { return !m_branch.empty(); }
 143  
 144      bool operator==(const TaprootBuilder& other) const { return GetTreeTuples() == other.GetTreeTuples(); }
 145  };
 146  
 147  /** Given a TaprootSpendData and the output key, reconstruct its script tree.
 148   *
 149   * If the output doesn't match the spenddata, or if the data in spenddata is incomplete,
 150   * std::nullopt is returned. Otherwise, a vector of (depth, script, leaf_ver) tuples is
 151   * returned, corresponding to a depth-first traversal of the script tree.
 152   */
 153  std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output);
 154  
 155  /** An interface to be implemented by keystores that support signing. */
 156  class SigningProvider
 157  {
 158  public:
 159      virtual ~SigningProvider() = default;
 160      virtual bool GetCScript(const CScriptID &scriptid, CScript& script) const { return false; }
 161      virtual bool HaveCScript(const CScriptID &scriptid) const { return false; }
 162      virtual bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const { return false; }
 163      virtual bool GetKey(const CKeyID &address, CKey& key) const { return false; }
 164      virtual bool HaveKey(const CKeyID &address) const { return false; }
 165      virtual bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const { return false; }
 166      virtual bool GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const { return false; }
 167      virtual bool GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const { return false; }
 168      virtual bool GetSpkPubKey(const uint256& key_hash, XOnlyPubKey& pubkey) const { return false; }
 169  
 170      bool GetKeyByXOnly(const XOnlyPubKey& pubkey, CKey& key) const
 171      {
 172          for (const auto& id : pubkey.GetKeyIDs()) {
 173              if (GetKey(id, key)) return true;
 174          }
 175          return false;
 176      }
 177  
 178      bool GetPubKeyByXOnly(const XOnlyPubKey& pubkey, CPubKey& out) const
 179      {
 180          for (const auto& id : pubkey.GetKeyIDs()) {
 181              if (GetPubKey(id, out)) return true;
 182          }
 183          return false;
 184      }
 185  
 186      bool GetKeyOriginByXOnly(const XOnlyPubKey& pubkey, KeyOriginInfo& info) const
 187      {
 188          for (const auto& id : pubkey.GetKeyIDs()) {
 189              if (GetKeyOrigin(id, info)) return true;
 190          }
 191          return false;
 192      }
 193  };
 194  
 195  extern const SigningProvider& DUMMY_SIGNING_PROVIDER;
 196  
 197  class HidingSigningProvider : public SigningProvider
 198  {
 199  private:
 200      const bool m_hide_secret;
 201      const bool m_hide_origin;
 202      const SigningProvider* m_provider;
 203  
 204  public:
 205      HidingSigningProvider(const SigningProvider* provider, bool hide_secret, bool hide_origin) : m_hide_secret(hide_secret), m_hide_origin(hide_origin), m_provider(provider) {}
 206      bool GetCScript(const CScriptID& scriptid, CScript& script) const override;
 207      bool GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const override;
 208      bool GetKey(const CKeyID& keyid, CKey& key) const override;
 209      bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
 210      bool GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const override;
 211      bool GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const override;
 212      bool GetSpkPubKey(const uint256& key_hash, XOnlyPubKey& pubkey) const override;
 213  };
 214  
 215  struct FlatSigningProvider final : public SigningProvider
 216  {
 217      std::map<CScriptID, CScript> scripts;
 218      std::map<CKeyID, CPubKey> pubkeys;
 219      std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> origins;
 220      std::map<CKeyID, CKey> keys;
 221      std::map<XOnlyPubKey, TaprootBuilder> tr_trees; /** Map from output key to Taproot tree (which can then make the TaprootSpendData */
 222      std::map<uint256, XOnlyPubKey> spk_keys; /** Map from HASH256(xpk) to XOnlyPubKey for P2SPKH */
 223  
 224      bool GetCScript(const CScriptID& scriptid, CScript& script) const override;
 225      bool GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const override;
 226      bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
 227      bool HaveKey(const CKeyID &keyid) const override;
 228      bool GetKey(const CKeyID& keyid, CKey& key) const override;
 229      bool GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const override;
 230      bool GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const override;
 231      bool GetSpkPubKey(const uint256& key_hash, XOnlyPubKey& pubkey) const override;
 232  
 233      void AddMasterKey(const CExtKey& key);
 234      FlatSigningProvider& Merge(FlatSigningProvider&& b) LIFETIMEBOUND;
 235  };
 236  
 237  /** Fillable signing provider that keeps keys in an address->secret map */
 238  class FillableSigningProvider : public SigningProvider
 239  {
 240  protected:
 241      using KeyMap = std::map<CKeyID, CKey>;
 242      using ScriptMap = std::map<CScriptID, CScript>;
 243  
 244      /**
 245       * Map of key id to unencrypted private keys known by the signing provider.
 246       * Map may be empty if the provider has another source of keys, like an
 247       * encrypted store.
 248       */
 249      KeyMap mapKeys GUARDED_BY(cs_KeyStore);
 250  
 251      /**
 252       * Map of script id to scripts known by the signing provider.
 253       *
 254       * This map originally just held P2SH redeemScripts, and was used by wallet
 255       * code to look up script ids referenced in "OP_HASH160 <script id>
 256       * OP_EQUAL" P2SH outputs. Later in 605e8473a7d it was extended to hold
 257       * P2WSH witnessScripts as well, and used to look up nested scripts
 258       * referenced in "OP_0 <script hash>" P2WSH outputs. Later in commits
 259       * f4691ab3a9d and 248f3a76a82, it was extended once again to hold segwit
 260       * "OP_0 <key or script hash>" scriptPubKeys, in order to give the wallet a
 261       * way to distinguish between segwit outputs that it generated addresses for
 262       * and wanted to receive payments from, and segwit outputs that it never
 263       * generated addresses for, but it could spend just because of having keys.
 264       * (Before segwit activation it was also important to not treat segwit
 265       * outputs to arbitrary wallet keys as payments, because these could be
 266       * spent by anyone without even needing to sign with the keys.)
 267       *
 268       * Some of the scripts stored in mapScripts are memory-only and
 269       * intentionally not saved to disk. Specifically, scripts added by
 270       * ImplicitlyLearnRelatedKeyScripts(pubkey) calls are not written to disk so
 271       * future wallet code can have flexibility to be more selective about what
 272       * transaction outputs it recognizes as payments, instead of having to treat
 273       * all outputs spending to keys it knows as payments. By contrast,
 274       * mapScripts entries added by AddCScript(script),
 275       * LearnRelatedScripts(pubkey, type), and LearnAllRelatedScripts(pubkey)
 276       * calls are saved because they are all intentionally used to receive
 277       * payments.
 278       *
 279       * The FillableSigningProvider::mapScripts script map should not be confused
 280       * with LegacyScriptPubKeyMan::setWatchOnly script set. The two collections
 281       * can hold the same scripts, but they serve different purposes. The
 282       * setWatchOnly script set is intended to expand the set of outputs the
 283       * wallet considers payments. Every output with a script it contains is
 284       * considered to belong to the wallet, regardless of whether the script is
 285       * solvable or signable. By contrast, the scripts in mapScripts are only
 286       * used for solving, and to restrict which outputs are considered payments
 287       * by the wallet. An output with a script in mapScripts, unlike
 288       * setWatchOnly, is not automatically considered to belong to the wallet if
 289       * it can't be solved and signed for.
 290       */
 291      ScriptMap mapScripts GUARDED_BY(cs_KeyStore);
 292  
 293      void ImplicitlyLearnRelatedKeyScripts(const CPubKey& pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
 294  
 295  public:
 296      mutable RecursiveMutex cs_KeyStore;
 297  
 298      virtual bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
 299      virtual bool AddKey(const CKey &key) { return AddKeyPubKey(key, key.GetPubKey()); }
 300      virtual bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override;
 301      virtual bool HaveKey(const CKeyID &address) const override;
 302      virtual std::set<CKeyID> GetKeys() const;
 303      virtual bool GetKey(const CKeyID &address, CKey &keyOut) const override;
 304      virtual bool AddCScript(const CScript& redeemScript);
 305      virtual bool HaveCScript(const CScriptID &hash) const override;
 306      virtual std::set<CScriptID> GetCScripts() const;
 307      virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const override;
 308  };
 309  
 310  /** Return the CKeyID of the key involved in a script (if there is a unique one). */
 311  CKeyID GetKeyForDestination(const SigningProvider& store, const CTxDestination& dest);
 312  
 313  /** A signing provider to be used to interface with multiple signing providers at once. */
 314  class MultiSigningProvider: public SigningProvider {
 315      std::vector<std::unique_ptr<SigningProvider>> m_providers;
 316  
 317  public:
 318      void AddProvider(std::unique_ptr<SigningProvider> provider);
 319  
 320      bool GetCScript(const CScriptID& scriptid, CScript& script) const override;
 321      bool GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const override;
 322      bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
 323      bool GetKey(const CKeyID& keyid, CKey& key) const override;
 324      bool GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const override;
 325      bool GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const override;
 326      bool GetSpkPubKey(const uint256& key_hash, XOnlyPubKey& pubkey) const override;
 327  };
 328  
 329  #endif // LIMENKA_SCRIPT_SIGNINGPROVIDER_H
 330