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 0 : bool CMessageSigner::GetKeysFromSecret(const std::string& strSecret, CKey& keyRet, CPubKey& pubkeyRet)
13 : {
14 0 : keyRet = DecodeSecret(strSecret);
15 0 : if (!keyRet.IsValid()) {
16 0 : return false;
17 : }
18 0 : pubkeyRet = keyRet.GetPubKey();
19 :
20 0 : return true;
21 0 : }
22 :
23 5 : bool CMessageSigner::SignMessage(const std::string& strMessage, std::vector<unsigned char>& vchSigRet, const CKey& key)
24 : {
25 5 : CHashWriter ss(SER_GETHASH, 0);
26 5 : ss << MESSAGE_MAGIC;
27 5 : ss << strMessage;
28 :
29 5 : 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 2 : bool CMessageSigner::VerifyMessage(const CKeyID& keyID, const std::vector<unsigned char>& vchSig, const std::string& strMessage, std::string& strErrorRet)
38 : {
39 2 : CHashWriter ss(SER_GETHASH, 0);
40 2 : ss << MESSAGE_MAGIC;
41 2 : ss << strMessage;
42 :
43 2 : return CHashSigner::VerifyHash(ss.GetHash(), keyID, vchSig, strErrorRet);
44 : }
45 :
46 8 : bool CHashSigner::SignHash(const uint256& hash, const CKey& key, std::vector<unsigned char>& vchSigRet)
47 : {
48 8 : 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 9 : bool CHashSigner::VerifyHash(const uint256& hash, const CKeyID& keyID, const std::vector<unsigned char>& vchSig, std::string& strErrorRet)
57 : {
58 9 : CPubKey pubkeyFromSig;
59 9 : if(!pubkeyFromSig.RecoverCompact(hash, vchSig)) {
60 0 : strErrorRet = "Error recovering public key.";
61 0 : return false;
62 : }
63 :
64 9 : if(pubkeyFromSig.GetID() != keyID) {
65 2 : strErrorRet = strprintf("Keys don't match: pubkey=%s, pubkeyFromSig=%s, hash=%s, vchSig=%s",
66 2 : keyID.ToString(), pubkeyFromSig.GetID().ToString(), hash.ToString(),
67 2 : EncodeBase64(vchSig));
68 2 : return false;
69 : }
70 :
71 7 : return true;
72 9 : }
|