Skip to content

Instantly share code, notes, and snippets.

@robot-dreams
Last active December 23, 2021 21:19
Show Gist options
  • Save robot-dreams/02d27311448bd4cb79bec3ce155bf21a to your computer and use it in GitHub Desktop.
Save robot-dreams/02d27311448bd4cb79bec3ce155bf21a to your computer and use it in GitHub Desktop.
secp256k1 #1049
from ec import *
from util import *
import hashlib
def accumulate(m, h):
if h.infinity:
m.update(b'\0')
else:
m.update(h.encode_uncompressed())
# Copied from PR
expected32_6bit20 = [
0x68, 0xb6, 0xed, 0x6f, 0x28, 0xca, 0xc9, 0x7f,
0x8e, 0x8b, 0xd6, 0xc0, 0x61, 0x79, 0x34, 0x6e,
0x5a, 0x8f, 0x2b, 0xbc, 0x3e, 0x1f, 0xc5, 0x2e,
0x2a, 0xd0, 0x45, 0x67, 0x7f, 0x95, 0x95, 0x8e
]
expected32_8bit8 = [
0x8b, 0x65, 0x8e, 0xea, 0x86, 0xae, 0x3c, 0x95,
0x90, 0xb6, 0x77, 0xa4, 0x8c, 0x76, 0xd9, 0xec,
0xf5, 0xab, 0x8a, 0x2f, 0xfd, 0xdb, 0x19, 0x12,
0x1a, 0xee, 0xe6, 0xb7, 0x6e, 0x05, 0x3f, 0xc6
]
def test_constants_sha(prefix, iters, expected):
m = hashlib.sha256()
h = INFINITY
accumulate(m, h)
accumulate(m, G)
accumulate(m, -G)
inp = [
(prefix ) & 0xFF,
(prefix >> 8 ) & 0xFF,
(prefix >> 16) & 0xFF,
(prefix >> 24) & 0xFF,
0,
0,
]
for i in range(iters):
inp[4] = (i ) & 0xFF
inp[5] = (i >> 8) & 0xFF
tmp = hashlib.sha256()
tmp.update(bytes(inp))
x = b32_to_int(tmp.digest())
accumulate(m, x * G)
assert(list(m.digest()) == expected)
test_constants_sha(4808378, 1024, expected32_6bit20)
test_constants_sha(1607366309, 2048, expected32_8bit8)
from util import *
import hashlib
# Checks that for every combination of n consecutive bit positions
# (of which there are 256 - n), all 2^n patterns occur among the
# iters possible choices of input scalars
def test_all_consecutive_n_bit_patterns(prefix, iters, n):
m = hashlib.sha256()
inp = [
(prefix ) & 0xFF,
(prefix >> 8 ) & 0xFF,
(prefix >> 16) & 0xFF,
(prefix >> 24) & 0xFF,
0,
0,
]
seen = []
for i in range(256 - n):
seen.append(set())
for i in range(iters):
inp[4] = (i ) & 0xFF
inp[5] = (i >> 8) & 0xFF
tmp = hashlib.sha256()
tmp.update(bytes(inp))
x = b32_to_int(tmp.digest())
for j in range(256 - n):
seen[j].add(x & ((1 << n) - 1))
x >>= 1
for i in range(256 - n):
assert len(seen[i]) == 1 << n
test_all_consecutive_n_bit_patterns(4808378, 1024, 6)
test_all_consecutive_n_bit_patterns(1607366309, 2048, 8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment