sr_commit_calc_ref.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import sys
  15. import hashlib
  16. import struct
  17. import base64
  18. # Python 3.6+, the SHA3 is available in hashlib natively. Else this requires
  19. # the pysha3 package (pip install pysha3).
  20. if sys.version_info < (3, 6):
  21. import sha3
  22. # Test vector to make sure the right sha3 version will be used. pysha3 < 1.0
  23. # used the old Keccak implementation. During the finalization of SHA3, NIST
  24. # changed the delimiter suffix from 0x01 to 0x06. The Keccak sponge function
  25. # stayed the same. pysha3 1.0 provides the previous Keccak hash, too.
  26. TEST_VALUE = "e167f68d6563d75bb25f3aa49c29ef612d41352dc00606de7cbd630bb2665f51"
  27. if TEST_VALUE != sha3.sha3_256(b"Hello World").hexdigest():
  28. print("pysha3 version is < 1.0. Please install from:")
  29. print("https://github.com/tiran/pysha3https://github.com/tiran/pysha3")
  30. sys.exit(1)
  31. # TIMESTAMP
  32. ts = 1454333590
  33. # RAND
  34. data = 'A' * 32 # Yes very very random, NIST grade :).
  35. rand = hashlib.sha3_256(data)
  36. reveal = struct.pack('!Q', ts) + rand.digest()
  37. b64_reveal = base64.b64encode(reveal)
  38. print("REVEAL: %s" % (b64_reveal))
  39. # Yes we do hash the _encoded_ reveal here that is H(REVEAL)
  40. hashed_reveal = hashlib.sha3_256(b64_reveal)
  41. commit = struct.pack('!Q', ts) + hashed_reveal.digest()
  42. print("COMMIT: %s" % (base64.b64encode(commit)))
  43. # REVEAL: AAAAAFavXpZJxbwTupvaJCTeIUCQmOPxAMblc7ChL5H2nZKuGchdaA==
  44. # COMMIT: AAAAAFavXpbkBMzMQG7aNoaGLFNpm2Wkk1ozXhuWWqL//GynltxVAg==