Skip to content

Commit 2a6e00b

Browse files
committed
bip340: Add bip340_tagged_hash tests
1 parent 3821e5e commit 2a6e00b

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

src/test/test_hash.py

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,22 @@
7070
[ 'a' * 1000000, '52783243c1697bdbe16d37f97f68f08325dc1528' ],
7171
]
7272

73+
# Test cases generated using the core test TaggedHash python impl:
74+
#import binascii, sys, hashlib
75+
#if __name__ == '__main__':
76+
# ss = hashlib.sha256(sys.argv[2].encode('utf-8')).digest()
77+
# ss += ss
78+
# ss += binascii.unhexlify(sys.argv[1])
79+
# print(binascii.hexlify(hashlib.sha256(ss).digest()))
80+
#
81+
bip340_tagged_cases = [
82+
[ '00000000000000', 'Foo',
83+
'89691133c1656f396254afbdee8049d77bec37e0c7427094b00bc2baf8fefef2' ],
84+
[ '0102030405060708090a0b0c0d0e0f', 'Bar',
85+
'15586de28c491c70948008f57bf0befe13c8c4a6938dd773f5173ed921f33f93' ],
86+
]
87+
88+
7389
class HashTests(unittest.TestCase):
7490

7591
SHA256_LEN, SHA512_LEN, HASH160_LEN, RIPEMD160_LEN = 32, 64, 20, 20
@@ -87,10 +103,13 @@ def make_outbuf(self, fn, aligned=True):
87103
return byref(buf, offset), buf_len
88104

89105

90-
def do_hash(self, fn, hex_in, aligned=True):
106+
def do_hash(self, fn, hex_in, aligned, tag=None):
91107
buf, buf_len = self.make_outbuf(fn, aligned)
92108
in_bytes, in_bytes_len = make_cbuffer(hex_in)
93-
ret = fn(in_bytes, in_bytes_len, buf, buf_len)
109+
args = [in_bytes, in_bytes_len, buf, buf_len]
110+
if tag is not None:
111+
args.insert(2, tag)
112+
ret = fn(*args)
94113
self.assertEqual(ret, WALLY_OK)
95114
ret, result = wally_hex_from_bytes(buf, buf_len)
96115
self.assertEqual(ret, WALLY_OK)
@@ -138,6 +157,21 @@ def test_invalid_args(self):
138157
(in_bytes, in_bytes_len, buf, buf_len + 1)]:
139158
self.assertEqual(fn(args[0], args[1], args[2], args[3]),
140159
WALLY_EINVAL)
160+
if fn == wally_sha256:
161+
# First time around: check tagged hash args too
162+
ret = wally_bip340_tagged_hash(args[0], args[1], 'Tag', args[2], args[3])
163+
self.assertEqual(ret, WALLY_EINVAL)
164+
# Invalid tags
165+
for tag in [ '', None ]:
166+
ret = wally_bip340_tagged_hash(in_bytes, in_bytes_len, tag, buf, buf_len)
167+
self.assertEqual(ret, WALLY_EINVAL)
168+
169+
170+
def test_bip340_tagged_vectors(self):
171+
for msg, tag, expected in bip340_tagged_cases:
172+
for aligned in [True, False]:
173+
result = self.do_hash(wally_bip340_tagged_hash, msg, aligned, tag)
174+
self.assertEqual(result, utf8(expected.lower()))
141175

142176

143177
if __name__ == '__main__':

0 commit comments

Comments
 (0)