1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Copyright (c) 2017 The Zcash developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #ifndef BITCOIN_PUBKEY_H
8 #define BITCOIN_PUBKEY_H
9 
10 #include <hash.h>
11 #include <serialize.h>
12 #include <span.h>
13 #include <uint256.h>
14 
15 #include <cstring>
16 #include <optional>
17 #include <vector>
18 
19 const unsigned int BIP32_EXTKEY_SIZE = 74;
20 
21 /** A reference to a CKey: the Hash160 of its serialized public key */
22 class CKeyID : public uint160
23 {
24 public:
CKeyID()25     CKeyID() : uint160() {}
CKeyID(const uint160 & in)26     explicit CKeyID(const uint160& in) : uint160(in) {}
27 };
28 
29 typedef uint256 ChainCode;
30 
31 /** An encapsulated public key. */
32 class CPubKey
33 {
34 public:
35     /**
36      * secp256k1:
37      */
38     static constexpr unsigned int SIZE                   = 65;
39     static constexpr unsigned int COMPRESSED_SIZE        = 33;
40     static constexpr unsigned int SIGNATURE_SIZE         = 72;
41     static constexpr unsigned int COMPACT_SIGNATURE_SIZE = 65;
42     /**
43      * see www.keylength.com
44      * script supports up to 75 for single byte push
45      */
46     static_assert(
47         SIZE >= COMPRESSED_SIZE,
48         "COMPRESSED_SIZE is larger than SIZE");
49 
50 private:
51 
52     /**
53      * Just store the serialized data.
54      * Its length can very cheaply be computed from the first byte.
55      */
56     unsigned char vch[SIZE];
57 
58     //! Compute the length of a pubkey with a given first byte.
GetLen(unsigned char chHeader)59     unsigned int static GetLen(unsigned char chHeader)
60     {
61         if (chHeader == 2 || chHeader == 3)
62             return COMPRESSED_SIZE;
63         if (chHeader == 4 || chHeader == 6 || chHeader == 7)
64             return SIZE;
65         return 0;
66     }
67 
68     //! Set this key data to be invalid
Invalidate()69     void Invalidate()
70     {
71         vch[0] = 0xFF;
72     }
73 
74 public:
75 
ValidSize(const std::vector<unsigned char> & vch)76     bool static ValidSize(const std::vector<unsigned char> &vch) {
77       return vch.size() > 0 && GetLen(vch[0]) == vch.size();
78     }
79 
80     //! Construct an invalid public key.
CPubKey()81     CPubKey()
82     {
83         Invalidate();
84     }
85 
86     //! Initialize a public key using begin/end iterators to byte data.
87     template <typename T>
Set(const T pbegin,const T pend)88     void Set(const T pbegin, const T pend)
89     {
90         int len = pend == pbegin ? 0 : GetLen(pbegin[0]);
91         if (len && len == (pend - pbegin))
92             memcpy(vch, (unsigned char*)&pbegin[0], len);
93         else
94             Invalidate();
95     }
96 
97     //! Construct a public key using begin/end iterators to byte data.
98     template <typename T>
CPubKey(const T pbegin,const T pend)99     CPubKey(const T pbegin, const T pend)
100     {
101         Set(pbegin, pend);
102     }
103 
104     //! Construct a public key from a byte vector.
CPubKey(Span<const uint8_t> _vch)105     explicit CPubKey(Span<const uint8_t> _vch)
106     {
107         Set(_vch.begin(), _vch.end());
108     }
109 
110     //! Simple read-only vector-like interface to the pubkey data.
size()111     unsigned int size() const { return GetLen(vch[0]); }
data()112     const unsigned char* data() const { return vch; }
begin()113     const unsigned char* begin() const { return vch; }
end()114     const unsigned char* end() const { return vch + size(); }
115     const unsigned char& operator[](unsigned int pos) const { return vch[pos]; }
116 
117     //! Comparator implementation.
118     friend bool operator==(const CPubKey& a, const CPubKey& b)
119     {
120         return a.vch[0] == b.vch[0] &&
121                memcmp(a.vch, b.vch, a.size()) == 0;
122     }
123     friend bool operator!=(const CPubKey& a, const CPubKey& b)
124     {
125         return !(a == b);
126     }
127     friend bool operator<(const CPubKey& a, const CPubKey& b)
128     {
129         return a.vch[0] < b.vch[0] ||
130                (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0);
131     }
132 
133     //! Implement serialization, as if this was a byte vector.
134     template <typename Stream>
Serialize(Stream & s)135     void Serialize(Stream& s) const
136     {
137         unsigned int len = size();
138         ::WriteCompactSize(s, len);
139         s.write((char*)vch, len);
140     }
141     template <typename Stream>
Unserialize(Stream & s)142     void Unserialize(Stream& s)
143     {
144         unsigned int len = ::ReadCompactSize(s);
145         if (len <= SIZE) {
146             s.read((char*)vch, len);
147             if (len != size()) {
148                 Invalidate();
149             }
150         } else {
151             // invalid pubkey, skip available data
152             char dummy;
153             while (len--)
154                 s.read(&dummy, 1);
155             Invalidate();
156         }
157     }
158 
159     //! Get the KeyID of this public key (hash of its serialization)
GetID()160     CKeyID GetID() const
161     {
162         return CKeyID(Hash160(MakeSpan(vch).first(size())));
163     }
164 
165     //! Get the 256-bit hash of this public key.
GetHash()166     uint256 GetHash() const
167     {
168         return Hash(MakeSpan(vch).first(size()));
169     }
170 
171     /*
172      * Check syntactic correctness.
173      *
174      * When setting a pubkey (Set()) or deserializing fails (its header bytes
175      * don't match the length of the data), the size is set to 0. Thus,
176      * by checking size, one can observe whether Set() or deserialization has
177      * failed.
178      *
179      * This does not check for more than that. In particular, it does not verify
180      * that the coordinates correspond to a point on the curve (see IsFullyValid()
181      * for that instead).
182      *
183      * Note that this is consensus critical as CheckECDSASignature() calls it!
184      */
IsValid()185     bool IsValid() const
186     {
187         return size() > 0;
188     }
189 
190     //! fully validate whether this is a valid public key (more expensive than IsValid())
191     bool IsFullyValid() const;
192 
193     //! Check whether this is a compressed public key.
IsCompressed()194     bool IsCompressed() const
195     {
196         return size() == COMPRESSED_SIZE;
197     }
198 
199     /**
200      * Verify a DER signature (~72 bytes).
201      * If this public key is not fully valid, the return value will be false.
202      */
203     bool Verify(const uint256& hash, const std::vector<unsigned char>& vchSig) const;
204 
205     /**
206      * Check whether a signature is normalized (lower-S).
207      */
208     static bool CheckLowS(const std::vector<unsigned char>& vchSig);
209 
210     //! Recover a public key from a compact signature.
211     bool RecoverCompact(const uint256& hash, const std::vector<unsigned char>& vchSig);
212 
213     //! Turn this public key into an uncompressed public key.
214     bool Decompress();
215 
216     //! Derive BIP32 child pubkey.
217     bool Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
218 };
219 
220 class XOnlyPubKey
221 {
222 private:
223     uint256 m_keydata;
224 
225 public:
226     /** Construct an empty x-only pubkey. */
227     XOnlyPubKey() = default;
228 
229     XOnlyPubKey(const XOnlyPubKey&) = default;
230     XOnlyPubKey& operator=(const XOnlyPubKey&) = default;
231 
232     /** Determine if this pubkey is fully valid. This is true for approximately 50% of all
233      *  possible 32-byte arrays. If false, VerifySchnorr and CreatePayToContract will always
234      *  fail. */
235     bool IsFullyValid() const;
236 
237     /** Test whether this is the 0 key (the result of default construction). This implies
238      *  !IsFullyValid(). */
IsNull()239     bool IsNull() const { return m_keydata.IsNull(); }
240 
241     /** Construct an x-only pubkey from exactly 32 bytes. */
242     explicit XOnlyPubKey(Span<const unsigned char> bytes);
243 
244     /** Construct an x-only pubkey from a normal pubkey. */
XOnlyPubKey(const CPubKey & pubkey)245     explicit XOnlyPubKey(const CPubKey& pubkey) : XOnlyPubKey(Span<const unsigned char>(pubkey.begin() + 1, pubkey.begin() + 33)) {}
246 
247     /** Verify a Schnorr signature against this public key.
248      *
249      * sigbytes must be exactly 64 bytes.
250      */
251     bool VerifySchnorr(const uint256& msg, Span<const unsigned char> sigbytes) const;
252 
253     /** Compute the Taproot tweak as specified in BIP341, with *this as internal
254      * key:
255      *  - if merkle_root == nullptr: H_TapTweak(xonly_pubkey)
256      *  - otherwise:                 H_TapTweak(xonly_pubkey || *merkle_root)
257      *
258      * Note that the behavior of this function with merkle_root != nullptr is
259      * consensus critical.
260      */
261     uint256 ComputeTapTweakHash(const uint256* merkle_root) const;
262 
263     /** Verify that this is a Taproot tweaked output point, against a specified internal key,
264      *  Merkle root, and parity. */
265     bool CheckTapTweak(const XOnlyPubKey& internal, const uint256& merkle_root, bool parity) const;
266 
267     /** Construct a Taproot tweaked output point with this point as internal key. */
268     std::optional<std::pair<XOnlyPubKey, bool>> CreateTapTweak(const uint256* merkle_root) const;
269 
270     const unsigned char& operator[](int pos) const { return *(m_keydata.begin() + pos); }
data()271     const unsigned char* data() const { return m_keydata.begin(); }
size()272     static constexpr size_t size() { return decltype(m_keydata)::size(); }
begin()273     const unsigned char* begin() const { return m_keydata.begin(); }
end()274     const unsigned char* end() const { return m_keydata.end(); }
begin()275     unsigned char* begin() { return m_keydata.begin(); }
end()276     unsigned char* end() { return m_keydata.end(); }
277     bool operator==(const XOnlyPubKey& other) const { return m_keydata == other.m_keydata; }
278     bool operator!=(const XOnlyPubKey& other) const { return m_keydata != other.m_keydata; }
279     bool operator<(const XOnlyPubKey& other) const { return m_keydata < other.m_keydata; }
280 };
281 
282 struct CExtPubKey {
283     unsigned char nDepth;
284     unsigned char vchFingerprint[4];
285     unsigned int nChild;
286     ChainCode chaincode;
287     CPubKey pubkey;
288 
289     friend bool operator==(const CExtPubKey &a, const CExtPubKey &b)
290     {
291         return a.nDepth == b.nDepth &&
292             memcmp(a.vchFingerprint, b.vchFingerprint, sizeof(vchFingerprint)) == 0 &&
293             a.nChild == b.nChild &&
294             a.chaincode == b.chaincode &&
295             a.pubkey == b.pubkey;
296     }
297 
298     friend bool operator!=(const CExtPubKey &a, const CExtPubKey &b)
299     {
300         return !(a == b);
301     }
302 
303     void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
304     void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
305     bool Derive(CExtPubKey& out, unsigned int nChild) const;
306 };
307 
308 /** Users of this module must hold an ECCVerifyHandle. The constructor and
309  *  destructor of these are not allowed to run in parallel, though. */
310 class ECCVerifyHandle
311 {
312     static int refcount;
313 
314 public:
315     ECCVerifyHandle();
316     ~ECCVerifyHandle();
317 };
318 
319 typedef struct secp256k1_context_struct secp256k1_context;
320 
321 /** Access to the internal secp256k1 context used for verification. Only intended to be used
322  *  by key.cpp. */
323 const secp256k1_context* GetVerifyContext();
324 
325 #endif // BITCOIN_PUBKEY_H
326