一天有一项任务是在莱特币钱包中签名和验证消息。几天的搜索没有奏效,所以我不得不使用库比特币重写我的一些函数来签名和验证消息。特别感谢来自electrum的人的成就,他们帮助找到了解决方案。好的,更少的单词更多的代码......
import bitcoin
class SignVerify:
def sign(self, address, message, private_key):
if self.check_if_not_message(message):
set_data = self.sign_message_with_private_key(private_key, address, message)
return set_data
else:
raise AttributeError('Incorrect private key.')
def verify(self, message, signature, public_key):
if self.check_if_not_message(signature):
return self.ecdsa_verify(message, signature, public_key)
else:
raise AttributeError('Signature is empty.')
def sign_message_with_private_key(self, private_key, address, message):
message_in_byte = message.encode()
return self.ecdsa_sign(message_in_byte, private_key)
@staticmethod
def check_if_not_message(message):
if message is None or not message or message == ' ':
return
return True
@staticmethod
def litecoin_sig_hash(message):
padded = b"\x19Litecoin Signed Message:\n" + bitcoin.num_to_var_int(
len(message)) + bitcoin.from_string_to_bytes(message)
return bitcoin.bin_dbl_sha256(padded)
def ecdsa_sign(self, msg, priv):
v, r, s = bitcoin.ecdsa_raw_sign(self.litecoin_sig_hash(msg), priv)
sig = bitcoin.encode_sig(v, r, s)
assert self.ecdsa_verify(msg, sig,
bitcoin.privtopub(priv)), "Bad Sig!\t %s\nv = %d\n,r = %d\ns = %d" % (sig, v, r, s)
return sig
def ecdsa_verify(self, msg, sig, pub):
return bitcoin.ecdsa_raw_verify(self.litecoin_sig_hash(msg), bitcoin.decode_sig(sig), pub)
if __name__ == '__main__':
message = 'LNXKMg8NTd5XLAF2n3HNMYYbyZB6KR7E4x'
address = 'LNXKMg8NTd5XLAF2n3HNMYYbyZB6KR7E4x'
privkey = 'T8vwiYErLrsWVytCzaFtQkaYgMYRN2qi4XaWYveeEVBfiiepnNjE'
public_key = '034835d15daca879dd91689e4f2c0650d495bdde0fdb4edb8ceb909830cdf7f26f'
a = SignVerify()
signature = a.sign(address=address, message=message, private_key=privkey)
print('sign => ', signature)
print('verify => ', a.verify(message=message, signature=signature, public_key=public_key))
我希望有人会帮助)))