protocol: add: hexHash
authorJulien Moutinho <julm+hjugement@autogeree.net>
Mon, 1 Jul 2019 21:34:27 +0000 (21:34 +0000)
committerJulien Moutinho <julm+hjugement@autogeree.net>
Mon, 1 Jul 2019 21:34:27 +0000 (21:34 +0000)
hjugement-protocol/src/Voting/Protocol/FFC.hs

index 462c152d103c9986a7c46a5a2175707ac02cad47..d37f4e51b0ea92e053687a9a205a2a7187b4ff71 100644 (file)
@@ -49,6 +49,9 @@ import qualified Data.ByteString as BS
 import qualified Data.Char as Char
 import qualified Data.List as List
 import qualified Data.Text as Text
+import qualified Data.Text.Lazy as TL
+import qualified Data.Text.Lazy.Builder as TLB
+import qualified Data.Text.Lazy.Builder.Int as TLB
 import qualified Prelude as Num
 import qualified System.Random as Random
 
@@ -314,7 +317,7 @@ groupGenPowers = go one
        where go g = g : go (g * groupGen @c)
 
 -- | @('hash' bs gs)@ returns as a number in 'E'
--- the SHA256 of the given 'BS.ByteString' 'bs'
+-- the 'Crypto.SHA256' hash of the given 'BS.ByteString' 'bs'
 -- prefixing the decimal representation of given subgroup elements 'gs',
 -- with a comma (",") intercalated between them.
 --
@@ -331,6 +334,23 @@ hash bs gs = do
        fromNatural $
                decodeBigEndian $ ByteArray.convert h
 
+-- | @('hexHash' bs)@ returns the 'Crypto.SHA256' hash
+-- of the given 'BS.ByteString' 'bs', escaped in hexadecimal
+-- into a 'Text' of 32 lowercase characters.
+--
+-- Used (in retro-dependencies of this library) to hash
+-- the 'PublicKey' of a voter or a trustee.
+hexHash :: BS.ByteString -> Text
+hexHash bs =
+       let h = Crypto.hashWith Crypto.SHA256 bs in
+       let n = decodeBigEndian $ ByteArray.convert h in
+       -- NOTE: always set the 256 bit then remove it
+       -- to always have leading zeros,
+       -- and thus always 64 characters wide hashes.
+       TL.toStrict $
+       TL.tail $ TLB.toLazyText $ TLB.hexadecimal $
+       setBit n 256
+
 -- | @('decodeBigEndian' bs)@ interpret @bs@ as big-endian number.
 decodeBigEndian :: BS.ByteString -> Natural
 decodeBigEndian =