Refactor message hashing into a utility function

And add unit test for it.

The purpose of using a preamble or "magic" text as part of signing and
verifying a message was not given when the code was repeated in a few
locations. Make a test showing how it is used to prevent inadvertently
signing a transaction.
This commit is contained in:
Jeffrey Czyz
2019-12-07 20:52:38 +01:00
committed by Vasil Dimov
parent f8f0d9893d
commit e193a84fb2
3 changed files with 43 additions and 13 deletions

View File

@@ -15,7 +15,11 @@
#include <string>
#include <vector>
const std::string strMessageMagic = "Bitcoin Signed Message:\n";
/**
* Text used to signify that a signed message follows and to prevent
* inadvertently signing a transaction.
*/
const std::string MESSAGE_MAGIC = "Bitcoin Signed Message:\n";
MessageVerificationResult MessageVerify(
const std::string& address,
@@ -37,12 +41,8 @@ MessageVerificationResult MessageVerify(
return MessageVerificationResult::ERR_MALFORMED_SIGNATURE;
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << message;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), signature_bytes)) {
if (!pubkey.RecoverCompact(MessageHash(message), signature_bytes)) {
return MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED;
}
@@ -58,13 +58,9 @@ bool MessageSign(
const std::string& message,
std::string& signature)
{
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << message;
std::vector<unsigned char> signature_bytes;
if (!privkey.SignCompact(ss.GetHash(), signature_bytes)) {
if (!privkey.SignCompact(MessageHash(message), signature_bytes)) {
return false;
}
@@ -72,3 +68,11 @@ bool MessageSign(
return true;
}
uint256 MessageHash(const std::string& message)
{
CHashWriter hasher(SER_GETHASH, 0);
hasher << MESSAGE_MAGIC << message;
return hasher.GetHash();
}