Line data Source code
1 : // Copyright (c) 2014-2023 The Dash Core developers
2 : // Distributed under the MIT/X11 software license, see the accompanying
3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 :
5 : #include <key_io.h>
6 : #include <hash.h>
7 : #include <util/message.h> // For MESSAGE_MAGIC
8 : #include <messagesigner.h>
9 : #include <tinyformat.h>
10 : #include <util/strencodings.h>
11 :
12 291 : bool CMessageSigner::GetKeysFromSecret(const std::string& strSecret, CKey& keyRet, CPubKey& pubkeyRet)
13 : {
14 291 : keyRet = DecodeSecret(strSecret);
15 291 : if (!keyRet.IsValid()) {
16 0 : return false;
17 : }
18 291 : pubkeyRet = keyRet.GetPubKey();
19 :
20 291 : return true;
21 291 : }
22 :
23 701 : bool CMessageSigner::SignMessage(const std::string& strMessage, std::vector<unsigned char>& vchSigRet, const CKey& key)
24 : {
25 701 : CHashWriter ss(SER_GETHASH, 0);
26 701 : ss << MESSAGE_MAGIC;
27 701 : ss << strMessage;
28 :
29 701 : return CHashSigner::SignHash(ss.GetHash(), key, vchSigRet);
30 : }
31 :
32 0 : bool CMessageSigner::VerifyMessage(const CPubKey& pubkey, const std::vector<unsigned char>& vchSig, const std::string& strMessage, std::string& strErrorRet)
33 : {
34 0 : return VerifyMessage(pubkey.GetID(), vchSig, strMessage, strErrorRet);
35 : }
36 :
37 6035 : bool CMessageSigner::VerifyMessage(const CKeyID& keyID, const std::vector<unsigned char>& vchSig, const std::string& strMessage, std::string& strErrorRet)
38 : {
39 6035 : CHashWriter ss(SER_GETHASH, 0);
40 6035 : ss << MESSAGE_MAGIC;
41 6035 : ss << strMessage;
42 :
43 6035 : return CHashSigner::VerifyHash(ss.GetHash(), keyID, vchSig, strErrorRet);
44 : }
45 :
46 712 : bool CHashSigner::SignHash(const uint256& hash, const CKey& key, std::vector<unsigned char>& vchSigRet)
47 : {
48 712 : return key.SignCompact(hash, vchSigRet);
49 : }
50 :
51 0 : bool CHashSigner::VerifyHash(const uint256& hash, const CPubKey& pubkey, const std::vector<unsigned char>& vchSig, std::string& strErrorRet)
52 : {
53 0 : return VerifyHash(hash, pubkey.GetID(), vchSig, strErrorRet);
54 : }
55 :
56 6178 : bool CHashSigner::VerifyHash(const uint256& hash, const CKeyID& keyID, const std::vector<unsigned char>& vchSig, std::string& strErrorRet)
57 : {
58 6178 : CPubKey pubkeyFromSig;
59 6178 : if(!pubkeyFromSig.RecoverCompact(hash, vchSig)) {
60 0 : strErrorRet = "Error recovering public key.";
61 0 : return false;
62 : }
63 :
64 6178 : if(pubkeyFromSig.GetID() != keyID) {
65 5 : strErrorRet = strprintf("Keys don't match: pubkey=%s, pubkeyFromSig=%s, hash=%s, vchSig=%s",
66 5 : keyID.ToString(), pubkeyFromSig.GetID().ToString(), hash.ToString(),
67 5 : EncodeBase64(vchSig));
68 5 : return false;
69 : }
70 :
71 6173 : return true;
72 6178 : }
|