sr_commit_calc_ref.py (1966B)
1 # This is a reference implementation of the COMMIT/REVEAL calculation for 2 # prop250. We use it to generate a test vector for the test_encoding() 3 # unittest. 4 # 5 # Here is the computation formula: 6 # 7 # H = SHA3-256 8 # TIMESTAMP = 8 bytes network-endian value 9 # RAND = H(32 bytes of random) 10 # 11 # REVEAL = base64-encode( TIMESTAMP || RAND ) 12 # COMMIT = base64-encode( TIMESTAMP || H(REVEAL) ) 13 # 14 15 # Future imports for Python 2.7, mandatory in 3.0 16 from __future__ import division 17 from __future__ import print_function 18 from __future__ import unicode_literals 19 20 import sys 21 import hashlib 22 import struct 23 import base64 24 25 # Python 3.6+, the SHA3 is available in hashlib natively. Else this requires 26 # the pysha3 package (pip install pysha3). 27 if sys.version_info < (3, 6): 28 import sha3 29 30 # Test vector to make sure the right sha3 version will be used. pysha3 < 1.0 31 # used the old Keccak implementation. During the finalization of SHA3, NIST 32 # changed the delimiter suffix from 0x01 to 0x06. The Keccak sponge function 33 # stayed the same. pysha3 1.0 provides the previous Keccak hash, too. 34 TEST_VALUE = "e167f68d6563d75bb25f3aa49c29ef612d41352dc00606de7cbd630bb2665f51" 35 if TEST_VALUE != sha3.sha3_256(b"Hello World").hexdigest(): 36 print("pysha3 version is < 1.0. Please install from:") 37 print("https://github.com/tiran/pysha3https://github.com/tiran/pysha3") 38 sys.exit(1) 39 40 # TIMESTAMP 41 ts = 1454333590 42 # RAND 43 data = 'A' * 32 # Yes very very random, NIST grade :). 44 rand = hashlib.sha3_256(data) 45 46 reveal = struct.pack('!Q', ts) + rand.digest() 47 b64_reveal = base64.b64encode(reveal) 48 print("REVEAL: %s" % (b64_reveal)) 49 50 # Yes we do hash the _encoded_ reveal here that is H(REVEAL) 51 hashed_reveal = hashlib.sha3_256(b64_reveal) 52 commit = struct.pack('!Q', ts) + hashed_reveal.digest() 53 print("COMMIT: %s" % (base64.b64encode(commit))) 54 55 # REVEAL: AAAAAFavXpZJxbwTupvaJCTeIUCQmOPxAMblc7ChL5H2nZKuGchdaA== 56 # COMMIT: AAAAAFavXpbkBMzMQG7aNoaGLFNpm2Wkk1ozXhuWWqL//GynltxVAg==