Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#ifndef BITCOIN_SCRIPT_SIGNINGPROVIDER_H7#define BITCOIN_SCRIPT_SIGNINGPROVIDER_H9#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#include <uint256.h>18#include <compare>19#include <cstdint>20#include <functional>21#include <map>22#include <memory>23#include <optional>24#include <set>25#include <span>26#include <tuple>27#include <utility>28#include <vector>30class MuSig2SecNonce;32struct ShortestVectorFirstComparator33{34bool operator()(const std::vector<unsigned char>& a, const std::vector<unsigned char>& b) const35{36if (a.size() < b.size()) return true;37if (a.size() > b.size()) return false;38return a < b;39}40};42struct TaprootSpendData43{44/** The BIP341 internal key. */45XOnlyPubKey internal_key;46/** The Merkle root of the script tree (0 if no scripts). */47uint256 merkle_root;48/** Map from (script, leaf_version) to (sets of) control blocks.49* More than one control block for a given script is only possible if it50* appears in multiple branches of the tree. We keep them all so that51* inference can reconstruct the full tree. Within each set, the control52* blocks are sorted by size, so that the signing logic can easily53* prefer the cheapest one. */54std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> scripts;55/** Merge other TaprootSpendData (for the same scriptPubKey) into this. */56void Merge(TaprootSpendData other);57};59/** Utility class to construct Taproot outputs from internal key and script tree. */60class TaprootBuilder61{62private:63/** Information about a tracked leaf in the Merkle tree. */64struct LeafInfo65{66std::vector<unsigned char> script; //!< The script.67int leaf_version; //!< The leaf version for that script.68std::vector<uint256> merkle_branch; //!< The hashing partners above this leaf.69};71/** Information associated with a node in the Merkle tree. */72struct NodeInfo73{74/** Merkle hash of this node. */75uint256 hash;76/** Tracked leaves underneath this node (either from the node itself, or its children).77* The merkle_branch field of each is the partners to get to *this* node. */78std::vector<LeafInfo> leaves;79};80/** Whether the builder is in a valid state so far. */81bool m_valid = true;83/** The current state of the builder.84*85* For each level in the tree, one NodeInfo object may be present. m_branch[0]86* is information about the root; further values are for deeper subtrees being87* explored.88*89* For every right branch taken to reach the position we're currently90* working in, there will be a (non-nullopt) entry in m_branch corresponding91* to the left branch at that level.92*93* For example, imagine this tree: - N0 -94* / \95* N1 N296* / \ / \97* A B C N398* / \99* D E100*101* Initially, m_branch is empty. After processing leaf A, it would become102* {nullopt, nullopt, A}. When processing leaf B, an entry at level 2 already103* exists, and it would thus be combined with it to produce a level 1 one,104* resulting in {nullopt, N1}. Adding C and D takes us to {nullopt, N1, C}105* and {nullopt, N1, C, D} respectively. When E is processed, it is combined106* with D, and then C, and then N1, to produce the root, resulting in {N0}.107*108* This structure allows processing with just O(log n) overhead if the leaves109* are computed on the fly.110*111* As an invariant, there can never be nullopt entries at the end. There can112* also not be more than 128 entries (as that would mean more than 128 levels113* in the tree). The depth of newly added entries will always be at least114* equal to the current size of m_branch (otherwise it does not correspond115* to a depth-first traversal of a tree). m_branch is only empty if no entries116* have ever be processed. m_branch having length 1 corresponds to being done.117*/118std::vector<std::optional<NodeInfo>> m_branch;120XOnlyPubKey m_internal_key; //!< The internal key, set when finalizing.121XOnlyPubKey m_output_key; //!< The output key, computed when finalizing.122bool m_parity; //!< The tweak parity, computed when finalizing.124/** Combine information about a parent Merkle tree node from its child nodes. */125static NodeInfo Combine(NodeInfo&& a, NodeInfo&& b);126/** Insert information about a node at a certain depth, and propagate information up. */127void Insert(NodeInfo&& node, int depth);129public:130/** Add a new script at a certain depth in the tree. Add() operations must be called131* in depth-first traversal order of binary tree. If track is true, it will be included in132* the GetSpendData() output. */133TaprootBuilder& Add(int depth, std::span<const unsigned char> script, int leaf_version, bool track = true);134/** Like Add(), but for a Merkle node with a given hash to the tree. */135TaprootBuilder& AddOmitted(int depth, const uint256& hash);136/** Finalize the construction. Can only be called when IsComplete() is true.137internal_key.IsFullyValid() must be true. */138TaprootBuilder& Finalize(const XOnlyPubKey& internal_key);140/** Return true if so far all input was valid. */141bool IsValid() const { return m_valid; }142/** Return whether there were either no leaves, or the leaves form a Huffman tree. */143bool IsComplete() const { return m_valid && (m_branch.size() == 0 || (m_branch.size() == 1 && m_branch[0].has_value())); }144/** Compute scriptPubKey (after Finalize()). */145WitnessV1Taproot GetOutput();146/** Check if a list of depths is legal (will lead to IsComplete()). */147static bool ValidDepths(const std::vector<int>& depths);148/** Compute spending data (after Finalize()). */149TaprootSpendData GetSpendData() const;150/** Returns a vector of tuples representing the depth, leaf version, and script */151std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> GetTreeTuples() const;152/** Returns true if there are any tapscripts */153bool HasScripts() const { return !m_branch.empty(); }155bool operator==(const TaprootBuilder& other) const { return GetTreeTuples() == other.GetTreeTuples(); }156};158/** Given a TaprootSpendData and the output key, reconstruct its script tree.159*160* If the output doesn't match the spenddata, or if the data in spenddata is incomplete,161* std::nullopt is returned. Otherwise, a vector of (depth, script, leaf_ver) tuples is162* returned, corresponding to a depth-first traversal of the script tree.163*/164std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output);166/** An interface to be implemented by keystores that support signing. */167class SigningProvider168{169public:170virtual ~SigningProvider() = default;171virtual bool GetCScript(const CScriptID &scriptid, CScript& script) const { return false; }172virtual bool HaveCScript(const CScriptID &scriptid) const { return false; }173virtual bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const { return false; }174virtual bool GetKey(const CKeyID &address, CKey& key) const { return false; }175virtual bool HaveKey(const CKeyID &address) const { return false; }176virtual bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const { return false; }177virtual bool GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const { return false; }178virtual bool GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const { return false; }179virtual std::vector<CPubKey> GetMuSig2ParticipantPubkeys(const CPubKey& pubkey) const { return {}; }180virtual std::map<CPubKey, std::vector<CPubKey>> GetAllMuSig2ParticipantPubkeys() const {return {}; }181virtual void SetMuSig2SecNonce(const uint256& id, MuSig2SecNonce&& nonce) const {}182virtual std::optional<std::reference_wrapper<MuSig2SecNonce>> GetMuSig2SecNonce(const uint256& session_id) const { return std::nullopt; }183virtual void DeleteMuSig2Session(const uint256& session_id) const {}185bool GetKeyByXOnly(const XOnlyPubKey& pubkey, CKey& key) const186{187for (const auto& id : pubkey.GetKeyIDs()) {188if (GetKey(id, key)) return true;189}190return false;191}193bool GetPubKeyByXOnly(const XOnlyPubKey& pubkey, CPubKey& out) const194{195for (const auto& id : pubkey.GetKeyIDs()) {196if (GetPubKey(id, out)) return true;197}198return false;199}201bool GetKeyOriginByXOnly(const XOnlyPubKey& pubkey, KeyOriginInfo& info) const202{203for (const auto& id : pubkey.GetKeyIDs()) {204if (GetKeyOrigin(id, info)) return true;205}206return false;207}208};210extern const SigningProvider& DUMMY_SIGNING_PROVIDER;212class HidingSigningProvider : public SigningProvider213{214private:215const bool m_hide_secret;216const bool m_hide_origin;217const SigningProvider* m_provider;219public:220HidingSigningProvider(const SigningProvider* provider, bool hide_secret, bool hide_origin) : m_hide_secret(hide_secret), m_hide_origin(hide_origin), m_provider(provider) {}221bool GetCScript(const CScriptID& scriptid, CScript& script) const override;222bool GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const override;223bool GetKey(const CKeyID& keyid, CKey& key) const override;224bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;225bool GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const override;226bool GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const override;227std::vector<CPubKey> GetMuSig2ParticipantPubkeys(const CPubKey& pubkey) const override;228std::map<CPubKey, std::vector<CPubKey>> GetAllMuSig2ParticipantPubkeys() const override;229void SetMuSig2SecNonce(const uint256& id, MuSig2SecNonce&& nonce) const override;230std::optional<std::reference_wrapper<MuSig2SecNonce>> GetMuSig2SecNonce(const uint256& session_id) const override;231void DeleteMuSig2Session(const uint256& session_id) const override;232};234struct FlatSigningProvider final : public SigningProvider235{236std::map<CScriptID, CScript> scripts;237std::map<CKeyID, CPubKey> pubkeys;238std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> origins;239std::map<CKeyID, CKey> keys;240std::map<XOnlyPubKey, TaprootBuilder> tr_trees; /** Map from output key to Taproot tree (which can then make the TaprootSpendData */241std::map<CPubKey, std::vector<CPubKey>> aggregate_pubkeys; /** MuSig2 aggregate pubkeys */242std::map<uint256, MuSig2SecNonce>* musig2_secnonces{nullptr};244bool GetCScript(const CScriptID& scriptid, CScript& script) const override;245bool GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const override;246bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;247bool HaveKey(const CKeyID &keyid) const override;248bool GetKey(const CKeyID& keyid, CKey& key) const override;249bool GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const override;250bool GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const override;
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.