lol-cpp 0.0.0.3 → 0.2.0.0
raw patch · 25 files changed
+2247/−1394 lines, 25 filesdep +lol-appsdep +test-frameworkdep −lol-benchesdep −lol-testsdep ~DRBGdep ~MonadRandomdep ~basenew-uploader
Dependencies added: lol-apps, test-framework
Dependencies removed: lol-benches, lol-tests
Dependency ranges changed: DRBG, MonadRandom, base, constraints, deepseq, lol, mtl, numeric-prelude, reflection, vector
Files
- CHANGES.md +4/−0
- Crypto/Lol/Cyclotomic/Tensor/CPP.hs +410/−179
- Crypto/Lol/Cyclotomic/Tensor/CPP/Backend.hs +167/−244
- Crypto/Lol/Cyclotomic/Tensor/CPP/Extension.hs +51/−50
- Crypto/Lol/Cyclotomic/Tensor/CPP/Instances.hs +1/−1
- Crypto/Lol/Cyclotomic/Tensor/CPP/common.cpp +13/−1
- Crypto/Lol/Cyclotomic/Tensor/CPP/common.h +5/−1
- Crypto/Lol/Cyclotomic/Tensor/CPP/crt.cpp +175/−179
- Crypto/Lol/Cyclotomic/Tensor/CPP/g.cpp +147/−140
- Crypto/Lol/Cyclotomic/Tensor/CPP/l.cpp +110/−46
- Crypto/Lol/Cyclotomic/Tensor/CPP/mul.cpp +14/−13
- Crypto/Lol/Cyclotomic/Tensor/CPP/norm.cpp +22/−26
- Crypto/Lol/Cyclotomic/Tensor/CPP/random.cpp +11/−11
- Crypto/Lol/Cyclotomic/Tensor/CPP/rrq.cpp +23/−0
- Crypto/Lol/Cyclotomic/Tensor/CPP/tensor.h +41/−19
- Crypto/Lol/Cyclotomic/Tensor/CPP/types.h +145/−12
- Crypto/Lol/Cyclotomic/Tensor/CPP/zq.cpp +30/−16
- LICENSE +585/−250
- benchmarks/BenchAppsCPPMain.hs +31/−0
- benchmarks/BenchCPPMain.hs +0/−83
- benchmarks/BenchLolCPPMain.hs +70/−0
- lol-cpp.cabal +136/−102
- tests/TestAppsCPPMain.hs +26/−0
- tests/TestCPPMain.hs +0/−21
- tests/TestLolCPPMain.hs +30/−0
CHANGES.md view
@@ -1,6 +1,10 @@ Changelog for lol-cpp project ================================ +0.0.0.4+----+ * Added lol-apps tests, benchmarks, and examples.+ 0.0.0.3 ---- * Removed unnecessary dependencies.
Crypto/Lol/Cyclotomic/Tensor/CPP.hs view
@@ -1,16 +1,17 @@ {-| Module : Crypto.Lol.Cyclotomic.Tensor.CPP-Description : Wrapper for a C++ implementation of the 'Tensor' interface.+Description : Wrapper for a C++ implementation of 'Tensor' interfaces. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX -Wrapper for a C++ implementation of the 'Tensor' interface.+Wrapper for a C++ implementation of 'Tensor' interfaces. -} +{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-}@@ -18,6 +19,7 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-}@@ -25,7 +27,7 @@ {-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-}-{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-}@@ -34,10 +36,10 @@ import Algebra.Additive as Additive (C) import Algebra.Module as Module (C)+import Algebra.Ring as Ring (C) import Algebra.ZeroTestable as ZeroTestable (C) import Control.Applicative hiding ((*>))-import Control.Arrow ((***)) import Control.DeepSeq import Control.Monad.Except import Control.Monad.Identity (Identity (..), runIdentity)@@ -45,16 +47,14 @@ import Control.Monad.Trans as T (lift) import Data.Coerce-import Data.Constraint hiding ((***)) import Data.Int import Data.Maybe import Data.Traversable as T-import Data.Vector.Generic as V (fromList, toList, unzip)-import Data.Vector.Storable as SV (Vector, convert, foldl',- fromList, generate,- length, map, replicate,- replicateM, thaw, thaw, toList,- unsafeFreeze,+import Data.Vector.Generic as V (fromList, toList)+import Data.Vector.Storable as SV (Vector, and, convert, foldl',+ fromList, generate, length, map,+ replicate, replicateM, thaw,+ thaw, toList, unsafeFreeze, unsafeWith, zipWith, (!)) import Data.Vector.Storable.Mutable as SM hiding (replicate) @@ -67,20 +67,23 @@ import Crypto.Lol.Cyclotomic.Tensor.CPP.Extension import Crypto.Lol.Cyclotomic.Tensor.CPP.Instances () import Crypto.Lol.GaussRandom-import Crypto.Lol.Prelude as LP hiding- (replicate,- unzip, zip)+import Crypto.Lol.Prelude as LP hiding (replicate,+ unzip, zip)+import Crypto.Lol.Reflects+import Crypto.Lol.Tests import Crypto.Lol.Types.FiniteField+import Crypto.Lol.Types.IFunctor import Crypto.Lol.Types.IZipVector import Crypto.Lol.Types.Proto-import Crypto.Lol.Utils.ShowType+import Crypto.Lol.Types.Unsafe.RRq+import Crypto.Lol.Types.Unsafe.ZqBasic import Data.Foldable as F import System.IO.Unsafe (unsafePerformIO) -- | Newtype wrapper around a Vector.-newtype CT' (m :: Factored) r = CT' { unCT :: Vector r }+newtype CT' (m :: Factored) r = CT' { unCT' :: Vector r } deriving (Show, Eq, NFData) -- the first argument, though phantom, affects representation@@ -89,7 +92,7 @@ -- GADT wrapper that distinguishes between Unbox and unrestricted -- element types --- | An implementation of 'Tensor' backed by C++ code.+-- | An implementation of 'Tensor' backend by C++ code. data CT (m :: Factored) r where CT :: Storable r => CT' m r -> CT m r ZV :: IZipVector m r -> CT m r@@ -100,41 +103,46 @@ show _ = "CT" instance Eq r => Eq (CT m r) where+ {-# SPECIALIZE instance Eq (CT m Int64) #-}+ {-# SPECIALIZE instance Eq (CT m Double) #-}+ {-# SPECIALIZE instance Eq (CT m (Complex Double)) #-}+ {-# SPECIALIZE instance Eq (CT m (ZqBasic q Int64)) #-}+ {-# SPECIALIZE instance Eq (CT m (RRq q Double)) #-}+ (ZV x) == (ZV y) = x == y (CT x) == (CT y) = x == y x@(CT _) == y = x == toCT y y == x@(CT _) = x == toCT y -instance (Protoable (IZipVector m r), Fact m, Storable r) => Protoable (CT m r) where- type ProtoType (CT m r) = ProtoType (IZipVector m r)-- toProto x@(CT _) = toProto $ toZV x- toProto (ZV x) = toProto x-- fromProto x = toCT <$> ZV <$> fromProto x-+{-# INLINE toCT #-} toCT :: (Storable r) => CT m r -> CT m r-toCT v@(CT _) = v-toCT (ZV v) = CT $ zvToCT' v+toCT = \case+ v@(CT _) -> v+ (ZV v) -> CT $ zvToCT' v +{-# INLINE toZV #-} toZV :: (Fact m) => CT m r -> CT m r-toZV (CT (CT' v)) = ZV $ fromMaybe (error "toZV: internal error") $- iZipVector $ convert v-toZV v@(ZV _) = v+toZV = \case+ (CT (CT' v)) -> ZV $ fromMaybe (error "toZV: internal error") $+ iZipVector $ convert v+ v@(ZV _) -> v +{-# INLINE zvToCT' #-} zvToCT' :: forall m r . (Storable r) => IZipVector m r -> CT' m r-zvToCT' v = coerce (convert $ unIZipVector v :: Vector r)+zvToCT' = CT' . convert . unIZipVector +{-# INLINE wrap #-} wrap :: (Storable s, Storable r) => (CT' l s -> CT' m r) -> (CT l s -> CT m r)-{-# INLINABLE wrap #-}-wrap f (CT v) = CT $ f v-wrap f (ZV v) = CT $ f $ zvToCT' v+wrap f = \case+ (CT v) -> CT $ f v+ (ZV v) -> CT $ f $ zvToCT' v +{-# INLINE wrapM #-} wrapM :: (Storable s, Storable r, Monad mon) => (CT' l s -> mon (CT' m r)) -> (CT l s -> mon (CT m r))-{-# INLINABLE wrapM #-}-wrapM f (CT v) = CT <$> f v-wrapM f (ZV v) = CT <$> f (zvToCT' v)+wrapM f = \case+ (CT v) -> CT <$> f v+ (ZV v) -> CT <$> f (zvToCT' v) -- convert an CT' *twace* signature to Tagged one type family Tw (r :: *) :: * where@@ -153,26 +161,22 @@ -- which used a (very fast) C function for (*) and (+) instance (Additive r, Storable r, Fact m) => Additive.C (CT m r) where+ {-# SPECIALIZE instance Fact m => Additive.C (CT m Int64) #-}+ {-# SPECIALIZE instance Fact m => Additive.C (CT m Double) #-}+ {-# SPECIALIZE instance Fact m => Additive.C (CT m (Complex Double)) #-}+ {-# SPECIALIZE instance (Fact m, Reflects q Int64) => Additive.C (CT m (ZqBasic q Int64)) #-}+ {-# SPECIALIZE instance Fact m => Additive.C (CT m (RRq q Double)) #-}+ (CT (CT' a)) + (CT (CT' b)) = CT $ CT' $ SV.zipWith (+) a b a + b = toCT a + toCT b negate (CT (CT' a)) = CT $ CT' $ SV.map negate a -- EAC: This probably should be converted to C code- negate a = negate $ toCT a+ negate a = negate $ toCT a zero = CT $ repl zero -{--instance (Fact m, Ring r, Storable r, Dispatch r)- => Ring.C (CT m r) where- (CT a@(CT' _)) * (CT b@(CT' _)) = CT $ (untag $ cZipDispatch dmul) a b-- fromInteger = CT . repl . fromInteger--}--instance (ZeroTestable r, Storable r)- => ZeroTestable.C (CT m r) where- --{-# INLINABLE isZero #-}+instance (ZeroTestable r, Storable r) => ZeroTestable.C (CT m r) where isZero (CT (CT' a)) = SV.foldl' (\ b x -> b && isZero x) True a- isZero (ZV v) = isZero v+ isZero (ZV v) = isZero v instance (GFCtx fp d, Fact m, Additive (CT m fp)) => Module.C (GF fp d) (CT m fp) where@@ -181,6 +185,27 @@ CT (CT' arr) -> CT $ CT' $ SV.fromList $ unCoeffs $ r *> Coeffs $ SV.toList arr ZV zv -> ZV $ fromJust $ iZipVector $ V.fromList $ unCoeffs $ r *> Coeffs $ V.toList $ unIZipVector zv +instance (Fact m, Ring r, Storable r) => Ring.C (CT m r) where+ {-# SPECIALIZE instance Fact m => Ring.C (CT m Int64) #-}+ {-# SPECIALIZE instance Fact m => Ring.C (CT m Double) #-}+ {-# SPECIALIZE instance Fact m => Ring.C (CT m (Complex Double)) #-}+ {-# SPECIALIZE instance (Fact m, Reflects q Int64) => Ring.C (CT m (ZqBasic q Int64)) #-}++ (*) = zipWithI (*)+ fromInteger i = CT $ repl $ fromInteger i++instance (Fact m, Ring r, Storable r) => Module.C r (CT m r) where+ {-# SPECIALIZE instance Fact m => Module.C Int64 (CT m Int64) #-}+ {-# SPECIALIZE instance Fact m => Module.C Double (CT m Double) #-}+ {-# SPECIALIZE instance Fact m => Module.C (Complex Double) (CT m (Complex Double)) #-}+ {-# SPECIALIZE instance (Fact m, Reflects q Int64) => Module.C (ZqBasic q Int64) (CT m (ZqBasic q Int64)) #-}+ (*>) r = wrap $ coerce $ SV.map (r*)++-- x is approximately equal to y iff all their components are approximately equal+instance (ApproxEqual r, Storable r) => ApproxEqual (CT m r) where+ (CT (CT' x)) =~= (CT (CT' y)) = SV.and $ SV.zipWith (=~=) x y+ x =~= y = toCT x =~= toCT y+ ---------- Category-theoretic instances ---------- instance Fact m => Functor (CT m) where@@ -192,6 +217,7 @@ (ZV f) <*> (ZV a) = ZV (f <*> a) f@(ZV _) <*> v@(CT _) = f <*> toZV v+ (CT _) <*> _ = error "CPP: internal error: function held by CT" instance Fact m => Foldable (CT m) where -- Foldable instance is implied by Traversable@@ -199,121 +225,278 @@ instance Fact m => Traversable (CT m) where traverse f r@(CT _) = T.traverse f $ toZV r- traverse f (ZV v) = ZV <$> T.traverse f v+ traverse f (ZV v) = ZV <$> T.traverse f v -instance Tensor CT where+instance TensorGaussian CT Double where+ tweakedGaussianDec v = CT <$> cDispatchGaussianDouble v - type TElt CT r = (Storable r, Dispatch r)+instance (Reflects q Int64, Prime q, IrreduciblePoly (ZqBasic q Int64))+ => TensorCRTSet CT (ZqBasic q Int64) where+ crtSetDec = (CT <$>) <$> coerceBasis crtSetDec' - entailIndexT = tag $ Sub Dict- entailEqT = tag $ Sub Dict- entailZTT = tag $ Sub Dict- -- entailRingT = tag $ Sub Dict- entailNFDataT = tag $ Sub Dict- entailRandomT = tag $ Sub Dict- entailShowT = tag $ Sub Dict- entailModuleT = tag $ Sub Dict+instance IFunctor CT where+ type IFElt CT a = Storable a - scalarPow = CT . scalarPow' -- Vector code+ fmapI f (CT (CT' sv)) = CT $ CT' $ SV.map f sv+ fmapI f a = fmapI f $ toCT a - l = wrap $ basicDispatch dl- lInv = wrap $ basicDispatch dlinv+ zipWithI f (CT (CT' sv1)) (CT (CT' sv2)) = CT $ CT' $ SV.zipWith f sv1 sv2+ zipWithI f a b = zipWithI f (toCT a) (toCT b) - mulGPow = wrap $ basicDispatch dmulgpow- mulGDec = wrap $ basicDispatch dmulgdec+---------- Tensor instances ---------- - divGPow = wrapM $ dispatchGInv dginvpow- divGDec = wrapM $ dispatchGInv dginvdec+instance Reflects q Int64 => TensorPowDec CT (ZqBasic q Int64) where+ scalarPow = CT . scalarPow' + decToPow = wrap $ basicDispatch dlZq+ powToDec = wrap $ basicDispatch dlinvZq++ twacePowDec = wrap $ runIdentity $ coerceTw twacePowDec'+ embedPow = wrap $ runIdentity $ coerceEm embedPow'+ embedDec = wrap $ runIdentity $ coerceEm embedDec'++ coeffs = wrapM $ coerceCoeffs coeffs'++ powBasisPow = (CT <$>) <$> coerceBasis powBasisPow'++ {-# INLINABLE scalarPow #-}+ {-# INLINABLE decToPow #-}+ {-# INLINABLE powToDec #-}+ {-# INLINABLE twacePowDec #-}+ {-# INLINABLE embedPow #-}+ {-# INLINABLE embedDec #-}+ {-# INLINABLE coeffs #-}+ {-# INLINABLE powBasisPow #-}++instance Reflects q Int64 => TensorG CT (ZqBasic q Int64) where+ mulGPow = wrap $ basicDispatch dmulgpowZq+ mulGDec = wrap $ basicDispatch dmulgdecZq++ divGPow = wrapM $ dispatchGInv dginvpowZq+ divGDec = wrapM $ dispatchGInv dginvdecZq++ {-# INLINABLE mulGPow #-}+ {-# INLINABLE mulGDec #-}+ {-# INLINABLE divGPow #-}+ {-# INLINABLE divGDec #-}++instance Reflects q Int64 => TensorCRT CT Maybe (ZqBasic q Int64) where crtFuncs = (,,,,) <$> return (CT . repl) <*>- (wrap . untag (cZipDispatch dmul) <$> gCRT) <*>- (wrap . untag (cZipDispatch dmul) <$> gInvCRT) <*>- (wrap <$> untagT ctCRT) <*>- (wrap <$> untagT ctCRTInv)+ (wrap . untag (cZipDispatch dmulZq) <$> gCRT) <*>+ (wrap . untag (cZipDispatch dmulZq) <$> gInvCRT) <*>+ (wrap <$> untagT ctCRTZq) <*>+ (wrap <$> untagT ctCRTInvZq) + crtExtFuncs = (,) <$> (wrap <$> coerceTw twaceCRT') <*> (wrap <$> coerceEm embedCRT')++ {-# NOINLINE crtFuncs #-}+ {-# NOINLINE crtExtFuncs #-}++instance TensorPowDec CT (Complex Double) where+ scalarPow = CT . scalarPow'++ decToPow = wrap $ basicDispatch dlC+ powToDec = wrap $ basicDispatch dlinvC+ twacePowDec = wrap $ runIdentity $ coerceTw twacePowDec' embedPow = wrap $ runIdentity $ coerceEm embedPow' embedDec = wrap $ runIdentity $ coerceEm embedDec' - tGaussianDec v = CT <$> cDispatchGaussian v- --tGaussianDec v = CT <$> coerceT' (gaussianDec v)+ coeffs = wrapM $ coerceCoeffs coeffs' - -- we do not wrap this function because (currently) it can only be called on lifted types- gSqNormDec (CT v) = untag gSqNormDec' v- gSqNormDec (ZV v) = gSqNormDec (CT $ zvToCT' v)+ powBasisPow = (CT <$>) <$> coerceBasis powBasisPow' - crtExtFuncs = (,) <$> (wrap <$> coerceTw twaceCRT')- <*> (wrap <$> coerceEm embedCRT')+ {-# INLINABLE scalarPow #-}+ {-# INLINABLE decToPow #-}+ {-# INLINABLE powToDec #-}+ {-# INLINABLE twacePowDec #-}+ {-# INLINABLE embedPow #-}+ {-# INLINABLE embedDec #-}+ {-# INLINABLE coeffs #-}+ {-# INLINABLE powBasisPow #-} +instance TensorG CT (Complex Double) where+ mulGPow = wrap $ basicDispatch dmulgpowC+ mulGDec = wrap $ basicDispatch dmulgdecC++ divGPow = wrapM $ dispatchGInv dginvpowC+ divGDec = wrapM $ dispatchGInv dginvdecC++ {-# INLINABLE mulGPow #-}+ {-# INLINABLE mulGDec #-}+ {-# INLINABLE divGPow #-}+ {-# INLINABLE divGDec #-}++instance TensorCRT CT Identity (Complex Double) where+ crtFuncs = (,,,,) <$>+ return (CT . repl) <*>+ (wrap . untag (cZipDispatch dmulC) <$> gCRT) <*>+ (wrap . untag (cZipDispatch dmulC) <$> gInvCRT) <*>+ (wrap <$> untagT ctCRTC) <*>+ (wrap <$> untagT ctCRTInvC)++ crtExtFuncs = (,) <$> (wrap <$> coerceTw twaceCRT') <*> (wrap <$> coerceEm embedCRT')++ {-# NOINLINE crtFuncs #-}+ {-# NOINLINE crtExtFuncs #-}++instance TensorCRT CT Maybe (Complex Double) where+ crtFuncs = return $ runIdentity crtFuncs+ crtExtFuncs = return $ runIdentity crtExtFuncs+ {-# NOINLINE crtFuncs #-}+ {-# NOINLINE crtExtFuncs #-}++instance TensorPowDec CT Double where+ scalarPow = CT . scalarPow'++ decToPow = wrap $ basicDispatch dlDouble+ powToDec = wrap $ basicDispatch dlinvDouble++ twacePowDec = wrap $ runIdentity $ coerceTw twacePowDec'+ embedPow = wrap $ runIdentity $ coerceEm embedPow'+ embedDec = wrap $ runIdentity $ coerceEm embedDec'+ coeffs = wrapM $ coerceCoeffs coeffs' powBasisPow = (CT <$>) <$> coerceBasis powBasisPow' - crtSetDec = (CT <$>) <$> coerceBasis crtSetDec'+ {-# INLINABLE scalarPow #-}+ {-# INLINABLE decToPow #-}+ {-# INLINABLE powToDec #-}+ {-# INLINABLE twacePowDec #-}+ {-# INLINABLE embedPow #-}+ {-# INLINABLE embedDec #-}+ {-# INLINABLE coeffs #-}+ {-# INLINABLE powBasisPow #-} - fmapT f = wrap $ coerce (SV.map f)+instance TensorG CT Double where+ mulGPow = wrap $ basicDispatch dmulgpowDouble+ mulGDec = wrap $ basicDispatch dmulgdecDouble - zipWithT f v1' v2' =- let (CT (CT' v1)) = toCT v1'- (CT (CT' v2)) = toCT v2'- in CT $ CT' $ SV.zipWith f v1 v2+ divGPow = wrapM $ dispatchGInv dginvpowDouble+ divGDec = wrapM $ dispatchGInv dginvdecDouble - unzipT v =- let (CT (CT' x)) = toCT v- in (CT . CT') *** (CT . CT') $ unzip x+ {-# INLINABLE mulGPow #-}+ {-# INLINABLE mulGDec #-}+ {-# INLINABLE divGPow #-}+ {-# INLINABLE divGDec #-} - {-# INLINABLE entailIndexT #-}- {-# INLINABLE entailEqT #-}- {-# INLINABLE entailZTT #-}- {-# INLINABLE entailNFDataT #-}- {-# INLINABLE entailRandomT #-}- {-# INLINABLE entailShowT #-}+instance TensorCRT CT Maybe Double where+ crtFuncs = Nothing+ crtExtFuncs = Nothing+ {-# INLINABLE crtFuncs #-}+ {-# INLINABLE crtExtFuncs #-}++instance TensorGSqNorm CT Double where+ gSqNormDec (CT v) = untag gSqNormDecDouble v+ gSqNormDec (ZV v) = gSqNormDec (CT $ zvToCT' v)++ {-# INLINABLE gSqNormDec #-}++instance TensorPowDec CT Int64 where+ scalarPow = CT . scalarPow'++ decToPow = wrap $ basicDispatch dlInt64+ powToDec = wrap $ basicDispatch dlinvInt64++ twacePowDec = wrap $ runIdentity $ coerceTw twacePowDec'+ embedPow = wrap $ runIdentity $ coerceEm embedPow'+ embedDec = wrap $ runIdentity $ coerceEm embedDec'++ coeffs = wrapM $ coerceCoeffs coeffs'++ powBasisPow = (CT <$>) <$> coerceBasis powBasisPow'+ {-# INLINABLE scalarPow #-}- {-# INLINABLE l #-}- {-# INLINABLE lInv #-}+ {-# INLINABLE decToPow #-}+ {-# INLINABLE powToDec #-}+ {-# INLINABLE twacePowDec #-}+ {-# INLINABLE embedPow #-}+ {-# INLINABLE embedDec #-}+ {-# INLINABLE coeffs #-}+ {-# INLINABLE powBasisPow #-}++instance TensorG CT Int64 where+ mulGPow = wrap $ basicDispatch dmulgpowInt64+ mulGDec = wrap $ basicDispatch dmulgdecInt64++ divGPow = wrapM $ dispatchGInv dginvpowInt64+ divGDec = wrapM $ dispatchGInv dginvdecInt64+ {-# INLINABLE mulGPow #-} {-# INLINABLE mulGDec #-} {-# INLINABLE divGPow #-} {-# INLINABLE divGDec #-}++instance TensorCRT CT Maybe Int64 where+ crtFuncs = Nothing+ crtExtFuncs = Nothing {-# INLINABLE crtFuncs #-}+ {-# INLINABLE crtExtFuncs #-}++instance TensorGSqNorm CT Int64 where+ gSqNormDec (CT v) = untag gSqNormDecInt64 v+ gSqNormDec (ZV v) = gSqNormDec (CT $ zvToCT' v)++ {-# INLINABLE gSqNormDec #-}++-- Instance constraints are due to 'fromSubgroup' in 'powBasisPow'+instance (Reflects q Int64, Reflects q Double) => TensorPowDec CT (RRq q Double) where+ scalarPow = CT . scalarPow'++ decToPow = wrap $ basicDispatch dlRRq+ powToDec = wrap $ basicDispatch dlinvRRq++ twacePowDec = wrap $ runIdentity $ coerceTw twacePowDec'+ embedPow = wrap $ runIdentity $ coerceEm embedPow'+ embedDec = wrap $ runIdentity $ coerceEm embedDec'++ coeffs = wrapM $ coerceCoeffs coeffs'++ powBasisPow :: forall m m' . (m `Divides` m') => Tagged m [CT m' (RRq q Double)]+ powBasisPow =+ let zqBasis = (CT <$>) <$> coerceBasis powBasisPow' :: Tagged m [CT m' (ZqBasic q Int64)] in+ (fmapI fromSubgroup <$>) <$> zqBasis++ {-# INLINABLE scalarPow #-}+ {-# INLINABLE decToPow #-}+ {-# INLINABLE powToDec #-} {-# INLINABLE twacePowDec #-} {-# INLINABLE embedPow #-} {-# INLINABLE embedDec #-}- {-# INLINABLE tGaussianDec #-}- {-# INLINABLE gSqNormDec #-}- {-# INLINE crtExtFuncs #-} {-# INLINABLE coeffs #-} {-# INLINABLE powBasisPow #-}- {-# INLINABLE crtSetDec #-}- {-# INLINABLE fmapT #-}- {-# INLINE zipWithT #-}- {-# INLINE unzipT #-} +---------- Helper functions for coercion ----------+ coerceTw :: (Functor mon) => TaggedT '(m, m') mon (Vector r -> Vector r) -> mon (CT' m' r -> CT' m r) coerceTw = (coerce <$>) . untagT coerceEm :: (Functor mon) => TaggedT '(m, m') mon (Vector r -> Vector r) -> mon (CT' m r -> CT' m' r) coerceEm = (coerce <$>) . untagT --- | Useful coersion for defining @coeffs@ in the @Tensor@+-- | Useful coersion for defining @coeffs@ in the @TensorPowDec@ -- interface. Using 'coerce' alone is insufficient for type inference. coerceCoeffs :: Tagged '(m,m') (Vector r -> [Vector r]) -> CT' m' r -> [CT' m r] coerceCoeffs = coerce --- | Useful coersion for defining @powBasisPow@ and @crtSetDec@ in the @Tensor@--- interface. Using 'coerce' alone is insufficient for type inference.+-- | Useful coersion for defining @powBasisPow@ and @crtSetDec@ in the @TensorPowDec@ and+-- @TensorCRT@ interfaces. Using 'coerce' alone is insufficient for type inference. coerceBasis :: Tagged '(m,m') [Vector r] -> Tagged m [CT' m' r] coerceBasis = coerce +---------- Helper Functions for dispatch ----------++{-# INLINE dispatchGInv #-} dispatchGInv :: forall m r . (Storable r, Fact m) => (Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO Int16)- -> CT' m r -> Maybe (CT' m r)-dispatchGInv f =- let factors = proxy (marshalFactors <$> ppsFact) (Proxy::Proxy m)- totm = proxy (fromIntegral <$> totientFact) (Proxy::Proxy m)+ -> CT' m r -> Maybe (CT' m r)+dispatchGInv =+ let factors = marshalFactors $ ppsFact @m+ totm = fromIntegral $ totientFact @m numFacts = fromIntegral $ SV.length factors- in \(CT' x) -> unsafePerformIO $ do+ in \f (CT' x) -> unsafePerformIO $ do yout <- SV.thaw x ret <- SM.unsafeWith yout (\pout -> SV.unsafeWith factors (\pfac ->@@ -322,50 +505,70 @@ then Just . CT' <$> unsafeFreeze yout else return Nothing +{-# INLINE withBasicArgs #-} withBasicArgs :: forall m r . (Fact m, Storable r)- => (Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ())- -> CT' m r -> IO (CT' m r)-withBasicArgs f =- let factors = proxy (marshalFactors <$> ppsFact) (Proxy::Proxy m)- totm = proxy (fromIntegral <$> totientFact) (Proxy::Proxy m)+ => (Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ())+ -> CT' m r -> IO (CT' m r)+withBasicArgs =+ let factors = marshalFactors $ ppsFact @m+ totm = fromIntegral $ totientFact @m numFacts = fromIntegral $ SV.length factors- in \(CT' x) -> do+ in \f (CT' x) -> do yout <- SV.thaw x SM.unsafeWith yout (\pout -> SV.unsafeWith factors (\pfac -> f pout totm pfac numFacts)) CT' <$> unsafeFreeze yout +{-# INLINE basicDispatch #-} basicDispatch :: (Storable r, Fact m)- => (Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ())- -> CT' m r -> CT' m r+ => (Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ())+ -> CT' m r -> CT' m r basicDispatch f = unsafePerformIO . withBasicArgs f -gSqNormDec' :: (Storable r, Fact m, Dispatch r)- => Tagged m (CT' m r -> r)-gSqNormDec' = return $ (!0) . unCT . unsafePerformIO . withBasicArgs dnorm+gSqNormDecDouble :: Fact m => Tagged m (CT' m Double -> Double)+gSqNormDecDouble = return $ (!0) . unCT' . unsafePerformIO . withBasicArgs dnormDouble -ctCRT :: (Storable r, CRTrans mon r, Dispatch r, Fact m)- => TaggedT m mon (CT' m r -> CT' m r)-ctCRT = do+gSqNormDecInt64 :: Fact m => Tagged m (CT' m Int64 -> Int64)+gSqNormDecInt64 = return $ (!0) . unCT' . unsafePerformIO . withBasicArgs dnormInt64++ctCRTZq :: (Fact m, Reflects q Int64, CRTrans mon (ZqBasic q Int64))+ => TaggedT m mon (CT' m (ZqBasic q Int64) -> CT' m (ZqBasic q Int64))+ctCRTZq = do ru' <- ru return $ \x -> unsafePerformIO $- withPtrArray ru' (flip withBasicArgs x . dcrt)+ withPtrArray ru' (flip withBasicArgs x . dcrtZq) -- CTensor CRT^(-1) functions take inverse rus-ctCRTInv :: (Storable r, CRTrans mon r, Dispatch r, Fact m)- => TaggedT m mon (CT' m r -> CT' m r)-ctCRTInv = do+ctCRTInvZq :: (Fact m, Reflects q Int64, CRTrans mon (ZqBasic q Int64))+ => TaggedT m mon (CT' m (ZqBasic q Int64) -> CT' m (ZqBasic q Int64))+ctCRTInvZq = do mhatInv <- snd <$> crtInfo ruinv' <- ruInv return $ \x -> unsafePerformIO $- withPtrArray ruinv' (\ruptr -> with mhatInv (flip withBasicArgs x . dcrtinv ruptr))+ withPtrArray ruinv' (\ruptr -> with mhatInv (flip withBasicArgs x . dcrtinvZq ruptr)) -cZipDispatch :: (Storable r, Fact m)- => (Ptr r -> Ptr r -> Int64 -> IO ())- -> Tagged m (CT' m r -> CT' m r -> CT' m r)+ctCRTC :: (CRTrans mon (Complex Double), Fact m)+ => TaggedT m mon (CT' m (Complex Double) -> CT' m (Complex Double))+ctCRTC = do+ ru' <- ru+ return $ \x -> unsafePerformIO $+ withPtrArray ru' (flip withBasicArgs x . dcrtC)++-- CTensor CRT^(-1) functions take inverse rus+ctCRTInvC :: (CRTrans mon (Complex Double), Fact m)+ => TaggedT m mon (CT' m (Complex Double) -> CT' m (Complex Double))+ctCRTInvC = do+ mhatInv <- snd <$> crtInfo+ ruinv' <- ruInv+ return $ \x -> unsafePerformIO $+ withPtrArray ruinv' (\ruptr -> with mhatInv (flip withBasicArgs x . dcrtinvC ruptr))++cZipDispatch :: forall m r . (Storable r, Fact m)+ => (Ptr r -> Ptr r -> Int64 -> IO ())+ -> Tagged m (CT' m r -> CT' m r -> CT' m r) cZipDispatch f = do -- in Tagged m- totm <- fromIntegral <$> totientFact+ let totm = fromIntegral $ totientFact @m return $ coerce $ \a b -> unsafePerformIO $ do yout <- SV.thaw a SM.unsafeWith yout (\pout ->@@ -373,82 +576,110 @@ f pout pin totm)) unsafeFreeze yout -cDispatchGaussian :: forall m r var rnd .- (Storable r, Transcendental r, Dispatch r, Ord r,- Fact m, ToRational var, Random r, MonadRandom rnd)- => var -> rnd (CT' m r)-cDispatchGaussian var = flip proxyT (Proxy::Proxy m) $ do -- in TaggedT m rnd- -- get rus for (Complex r)+cDispatchGaussianDouble :: forall m var rnd .+ (Fact m, ToRational var, MonadRandom rnd)+ => var -> rnd (CT' m Double)+cDispatchGaussianDouble var = flip proxyT (Proxy::Proxy m) $ do -- in TaggedT m rnd+ let totm = totientFact @m+ mval = valueFact @m+ rad = radicalFact @m -- takes ru (not ruInv) to match RT- ruinv' <- mapTaggedT (return . fromMaybe (error "complexGaussianRoots")) ru- totm <- pureT totientFact- mval <- pureT valueFact- rad <- pureT radicalFact+ ru' <- mapTaggedT (return . runIdentity) ru yin <- T.lift $ realGaussians (var * fromIntegral (mval `div` rad)) totm return $ unsafePerformIO $- withPtrArray ruinv' (\ruptr -> withBasicArgs (dgaussdec ruptr) (CT' yin))+ withPtrArray ru' (\ruptr -> withBasicArgs (dgaussdecDouble ruptr) (CT' yin)) +---------- Misc instances and arithmetic ----------+ instance (Storable r, Random r, Fact m) => Random (CT' m r) where- --{-# INLINABLE random #-}+ {-# SPECIALIZE instance Fact m => Random (CT' m Int64) #-}+ {-# SPECIALIZE instance Fact m => Random (CT' m Double) #-}+ {-# SPECIALIZE instance Fact m => Random (CT' m (Complex Double)) #-}+ {-# SPECIALIZE instance (Fact m, Reflects q Int64) => Random (CT' m (ZqBasic q Int64)) #-}+ {-# SPECIALIZE instance Fact m => Random (CT' m (RRq q Double)) #-}+ random = runRand $ replM (liftRand random) - randomR = error "randomR nonsensical for CT'"+ -- Interpret the range component-wise+ randomR (CT' a, CT' b) = runRand $ CT' . SV.fromList <$> l+ where l = zipWithM (\x y -> liftRand $ randomR (x, y)) (SV.toList a) (SV.toList b) -instance (Storable r, Random (CT' m r)) => Random (CT m r) where- --{-# INLINABLE random #-}+ {-# INLINABLE random #-}+ {-# INLINABLE randomR #-}++instance (Storable r, Random r, Fact m) => Random (CT m r) where+ {-# SPECIALIZE instance Fact m => Random (CT m Int64) #-}+ {-# SPECIALIZE instance Fact m => Random (CT m Double) #-}+ {-# SPECIALIZE instance Fact m => Random (CT m (Complex Double)) #-}+ {-# SPECIALIZE instance (Fact m, Reflects q Int64) => Random (CT m (ZqBasic q Int64)) #-}+ {-# SPECIALIZE instance Fact m => Random (CT m (RRq q Double)) #-}+ random = runRand $ CT <$> liftRand random - randomR = error "randomR nonsensical for CT"+ -- Drop to the CT' instance+ randomR (CT a, CT b) = runRand $ CT <$> liftRand (randomR (a, b))+ randomR (a, b) = randomR (toCT a, toCT b) + {-# INLINABLE random #-}+ {-# INLINABLE randomR #-}+ instance (NFData r) => NFData (CT m r) where+ {-# SPECIALIZE instance NFData (CT m Int64) #-}+ {-# SPECIALIZE instance NFData (CT m Double) #-}+ {-# SPECIALIZE instance NFData (CT m (Complex Double)) #-}+ {-# SPECIALIZE instance NFData (CT m (ZqBasic q Int64)) #-}+ {-# SPECIALIZE instance NFData (CT m (RRq q Double)) #-}+ rnf (CT v) = rnf v rnf (ZV v) = rnf v +instance (Protoable (IZipVector m r), Fact m, Storable r)+ => Protoable (CT m r) where+ type ProtoType (CT m r) = ProtoType (IZipVector m r)++ toProto x@(CT _) = toProto $ toZV x+ toProto (ZV x) = toProto x++ fromProto x = toCT . ZV <$> fromProto x++{-# INLINE repl #-} repl :: forall m r . (Fact m, Storable r) => r -> CT' m r-repl = let n = proxy totientFact (Proxy::Proxy m)+repl = let n = totientFact @m in coerce . SV.replicate n replM :: forall m r mon . (Fact m, Storable r, Monad mon) => mon r -> mon (CT' m r)-replM = let n = proxy totientFact (Proxy::Proxy m)+replM = let n = totientFact @m in fmap coerce . SV.replicateM n +{-# INLINE scalarPow' #-} scalarPow' :: forall m r . (Fact m, Additive r, Storable r) => r -> CT' m r -- constant-term coefficient is first entry wrt powerful basis scalarPow' =- let n = proxy totientFact (Proxy::Proxy m)+ let n = totientFact @m in \r -> CT' $ generate n (\i -> if i == 0 then r else zero) -ru, ruInv :: (CRTrans mon r, Fact m, Storable r)+{-# INLINE ru #-}+{-# INLINE ruInv #-}+ru, ruInv :: forall m mon r . (CRTrans mon r, Fact m, Storable r) => TaggedT m mon [Vector r] ru = do- mval <- pureT valueFact wPow <- fst <$> crtInfo- LP.map- (\(p,e) -> do- let pp = p^e- pow = mval `div` pp- generate pp (wPow . (*pow))) <$>- pureT ppsFact+ let go (p,e) = let pp=p^e+ in generate pp (wPow . (* (valueFact @m `div` pp)))+ return $ go <$> ppsFact @m ruInv = do- mval <- pureT valueFact wPow <- fst <$> crtInfo- LP.map- (\(p,e) -> do- let pp = p^e- pow = mval `div` pp- generate pp (\i -> wPow $ -i*pow)) <$>- pureT ppsFact+ let go (p,e) = let pp=p^e+ in generate pp (wPow . (* (valueFact @m `div` pp)) . negate)+ return $ go <$> ppsFact @m -wrapVector :: forall mon m r . (Monad mon, Fact m, Ring r, Storable r)- => TaggedT m mon (Kron r) -> mon (CT' m r)-wrapVector v = do- vmat <- proxyT v (Proxy::Proxy m)- let n = proxy totientFact (Proxy::Proxy m)- return $ CT' $ generate n (flip (indexK vmat) 0)+wrapVector :: forall m r . (Fact m, Ring r, Storable r) => Kron r -> CT' m r+wrapVector v = CT' $ generate (totientFact @m) (flip (indexK v) 0) -gCRT, gInvCRT :: (Storable r, CRTrans mon r, Fact m)- => mon (CT' m r)-gCRT = wrapVector gCRTK-gInvCRT = wrapVector gInvCRTK+{-# INLINE gCRT #-}+{-# INLINE gInvCRT #-}+gCRT, gInvCRT :: forall m mon r . (Storable r, CRTrans mon r, Fact m) => mon (CT' m r)+gCRT = wrapVector <$> gCRTK @m+gInvCRT = wrapVector <$> gInvCRTK @m
Crypto/Lol/Cyclotomic/Tensor/CPP/Backend.hs view
@@ -2,9 +2,9 @@ Module : Crypto.Lol.Cyclotomic.Tensor.CPP.Backend Description : Transforms Haskell types into C counterparts. Copyright : (c) Eric Crockett, 2011-2017- Chris Peikert, 2011-2017-License : GPL-2-Maintainer : ecrockett0@email.com+ Chris Peikert, 2011-2018+License : GPL-3+Maintainer : ecrockett0@gmail.com Stability : experimental Portability : POSIX @@ -20,6 +20,7 @@ {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-}@@ -27,41 +28,50 @@ {-# OPTIONS_GHC -fno-warn-unticked-promoted-constructors #-} module Crypto.Lol.Cyclotomic.Tensor.CPP.Backend-( Dispatch-, dcrt, dcrtinv-, dgaussdec-, dl, dlinv-, dnorm-, dmulgpow, dmulgdec-, dginvpow, dginvdec-, dmul+( dcrtZq, dcrtinvZq+, dlZq, dlinvZq+, dmulgpowZq, dmulgdecZq+, dginvpowZq, dginvdecZq+, dmulZq+, dcrtC, dcrtinvC+, dlC, dlinvC+, dmulgpowC, dmulgdecC+, dginvpowC, dginvdecC+, dmulC+, dlDouble, dlinvDouble+, dmulgpowDouble, dmulgdecDouble+, dginvpowDouble, dginvdecDouble+, dgaussdecDouble+, dnormDouble+, dlRRq,dlinvRRq+, dlInt64, dlinvInt64+, dmulgpowInt64, dmulgdecInt64+, dginvpowInt64, dginvdecInt64+, dnormInt64 , marshalFactors , CPP , withArray, withPtrArray ) where -import Crypto.Lol.Prelude as LP (Complex, PP, Proxy (..), Tagged,- map, mapM_, proxy, tag)+import Crypto.Lol.Prelude as LP (Complex, PP, map, mapM_) import Crypto.Lol.Reflects import Crypto.Lol.Types.Unsafe.RRq import Crypto.Lol.Types.Unsafe.ZqBasic +import Control.Arrow ((***)) import Data.Int import Data.Vector.Storable as SV (Vector, fromList, unsafeToForeignPtr0) import Data.Vector.Storable.Internal (getPtr) -import Foreign.ForeignPtr (touchForeignPtr)-import Foreign.Marshal.Array (withArray)-import Foreign.Marshal.Utils (with)-import Foreign.Ptr (Ptr, castPtr, plusPtr)-import Foreign.Storable (Storable (..))--import GHC.TypeLits -- for error message+import Foreign.ForeignPtr (touchForeignPtr)+import Foreign.Marshal.Array (withArray)+import Foreign.Ptr (Ptr, castPtr, plusPtr)+import Foreign.Storable (Storable (..)) -- | Convert a list of prime powers to a suitable C representation. marshalFactors :: [PP] -> Vector CPP-marshalFactors = SV.fromList . LP.map (\(p,e) -> (fromIntegral p, fromIntegral e))+marshalFactors = SV.fromList . LP.map (fromIntegral *** fromIntegral) -- http://stackoverflow.com/questions/6517387/vector-vector-foo-ptr-ptr-foo-io-a-io-a -- | Evaluates a C function that takes an "a** ptr" on a list of Vectors.@@ -89,249 +99,162 @@ poke (castPtr p :: Ptr a) a poke (castPtr (plusPtr p (sizeOf a)) :: Ptr b) b -data ZqB64D -- for type safety purposes-data ComplexD-data DoubleD-data Int64D-data RRqD+dcrtZq :: forall q . Reflects q Int64 => Ptr (Ptr (ZqBasic q Int64)) -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dcrtZq ruptr pout totm pfac numFacts =+ tensorCRTRq (castPtr pout) totm pfac numFacts (castPtr ruptr) (value @q) -type family CTypeOf x where- CTypeOf (a,b) = EqCType a b (CTypeOf a) (CTypeOf b)- CTypeOf (ZqBasic (q :: k) Int64) = ZqB64D- CTypeOf Double = DoubleD- CTypeOf Int64 = Int64D- CTypeOf (Complex Double) = ComplexD- CTypeOf (RRq (q :: k) Double) = RRqD+dcrtinvZq :: forall q . Reflects q Int64 => Ptr (Ptr (ZqBasic q Int64)) -> Ptr (ZqBasic q Int64) -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dcrtinvZq ruptr minv pout totm pfac numFacts =+ tensorCRTInvRq (castPtr pout) totm pfac numFacts (castPtr ruptr) (castPtr minv) (value @q) - -- EAC: See #12237 and #11990- CTypeOf (ZqBasic (q :: k) i) = TypeError (Text "Unsupported C type: " :<>: ShowType (ZqBasic q i) :$$: Text "Use Int64 as the base ring")- CTypeOf (Complex i) = TypeError (Text "Unsupported C type: " :<>: ShowType (Complex i) :$$: Text "Use Double as the base ring")- CTypeOf (RRq (q :: k) i) = TypeError (Text "Unsupported C type: " :<>: ShowType (RRq q i) :$$: Text "Use Double as the base ring")- CTypeOf a = TypeError (Text "Unsupported C type: " :<>: ShowType a)+dlZq :: forall q . Reflects q Int64 => Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlZq pout totm pfac numFacts =+ tensorLRq (castPtr pout) totm pfac numFacts (value @q) -type family EqCType a b c d where- EqCType a b ZqB64D ZqB64D = ZqB64D- EqCType a b RRqD RRqD = RRqD- EqCType a b ComplexD ComplexD = ComplexD- EqCType a b c c = TypeError (Text "Cannot call C code on a tuple of type " :<>: ShowType a)- EqCType a b c d = TypeError (Text "You are trying to use CTensor on a tuple," :<>:- Text " but the tuple contains two different C types: " :$$:- ShowType a :<>: Text " and " :<>: ShowType b)+dlinvZq :: forall q . Reflects q Int64 => Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlinvZq pout totm pfac numFacts =+ tensorLInvRq (castPtr pout) totm pfac numFacts (value @q) --- returns the modulus as a nested list of moduli-class (Tuple a) => ZqTuple a where- type ModPairs a- getModuli :: Tagged a (ModPairs a)+dmulgpowZq :: forall q . Reflects q Int64 => Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dmulgpowZq pout totm pfac numFacts =+ tensorGPowRq (castPtr pout) totm pfac numFacts (value @q) -instance (Reflects q Int64) => ZqTuple (ZqBasic q Int64) where- type ModPairs (ZqBasic q Int64) = Int64- getModuli = tag $ proxy value (Proxy::Proxy q)+dmulgdecZq :: forall q . Reflects q Int64 => Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dmulgdecZq pout totm pfac numFacts =+ tensorGDecRq (castPtr pout) totm pfac numFacts (value @q) -instance (Reflects q r, RealFrac r) => ZqTuple (RRq q r) where- type ModPairs (RRq q r) = Int64- getModuli = tag $ round (proxy value (Proxy::Proxy q) :: r)+dginvpowZq :: forall q . Reflects q Int64 => Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dginvpowZq pout totm pfac numFacts =+ tensorGInvPowRq (castPtr pout) totm pfac numFacts (value @q) -instance (ZqTuple a, ZqTuple b) => ZqTuple (a, b) where- type ModPairs (a,b) = (ModPairs a, ModPairs b)- getModuli =- let as = proxy getModuli (Proxy::Proxy a)- bs = proxy getModuli (Proxy :: Proxy b)- in tag (as,bs)+dginvdecZq :: forall q . Reflects q Int64 => Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dginvdecZq pout totm pfac numFacts =+ tensorGInvDecRq (castPtr pout) totm pfac numFacts (value @q) --- counts components in a nested tuple-class Tuple a where- numComponents :: Tagged a Int16+dmulZq :: forall q . Reflects q Int64 => Ptr (ZqBasic q Int64) -> Ptr (ZqBasic q Int64) -> Int64 -> IO ()+dmulZq aout bout totm =+ mulRq (castPtr aout) (castPtr bout) totm (value @q) -instance {-# Overlappable #-} Tuple a where- numComponents = tag 1+dcrtC :: Ptr (Ptr (Complex Double)) -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dcrtC ruptr pout totm pfac numFacts =+ tensorCRTC (castPtr pout) totm pfac numFacts (castPtr ruptr) -instance (Tuple a, Tuple b) => Tuple (a,b) where- numComponents = tag $ proxy numComponents (Proxy::Proxy a) + proxy numComponents (Proxy::Proxy b)+dcrtinvC :: Ptr (Ptr (Complex Double)) -> Ptr (Complex Double) -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dcrtinvC ruptr minv pout totm pfac numFacts =+ tensorCRTInvC (castPtr pout) totm pfac numFacts (castPtr ruptr) (castPtr minv) --- | Single-argument synonym for @Dispatch'@.-type Dispatch r = (Dispatch' (CTypeOf r) r)+dlC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlC pout = tensorLC (castPtr pout) --- | Class to safely match Haskell types with the appropriate C function.-class (repr ~ CTypeOf r) => Dispatch' repr r where- -- | Equivalent to 'Tensor's @crt@.- dcrt :: Ptr (Ptr r) -> Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ()- -- | Equivalent to 'Tensor's @crtInv@.- dcrtinv :: Ptr (Ptr r) -> Ptr r -> Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ()- -- | Equivalent to 'Tensor's @tGaussianDec@.- dgaussdec :: Ptr (Ptr (Complex r)) -> Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ()- -- | Equivalent to 'Tensor's @l@.- dl :: Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ()- -- | Equivalent to 'Tensor's @lInv@.- dlinv :: Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ()- -- | Equivalent to 'Tensor's @gSqNormDec@.- dnorm :: Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ()- -- | Equivalent to 'Tensor's @mulGPow@.- dmulgpow :: Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ()- -- | Equivalent to 'Tensor's @mulGDec@.- dmulgdec :: Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO ()- -- | Equivalent to 'Tensor's @divGPow@.- dginvpow :: Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO Int16- -- | Equivalent to 'Tensor's @divGDec@.- dginvdec :: Ptr r -> Int64 -> Ptr CPP -> Int16 -> IO Int16- -- | Equivalent to @zipWith (*)@- dmul :: Ptr r -> Ptr r -> Int64 -> IO ()+dlinvC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlinvC pout = tensorLInvC (castPtr pout) -instance (ZqTuple r, Storable (ModPairs r), CTypeOf r ~ RRqD)- => Dispatch' RRqD r where- dcrt = error "cannot call CT CRT on type RRq"- dcrtinv = error "cannot call CT CRTInv on type RRq"- dl = error "cannot call CT L on type RRq (though you probably should be able to)"- dlinv = error "cannot call CT LInv on type RRq (though you probably should be able to)"- dnorm = error "cannto call CT normSq on type RRq"- dmulgpow = error "cannot call CT mulGPow on type RRq"- dmulgdec = error "cannot call CT mulGDec on type RRq"- dginvpow = error "cannot call CT divGPow on type RRq"- dginvdec = error "cannot call CT divGDec on type RRq"- dmul = error "cannot call CT mul on type RRq"- dgaussdec = error "cannot call CT gaussianDec on type RRq"+dmulgpowC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dmulgpowC pout = tensorGPowC (castPtr pout) -instance (ZqTuple r, Storable (ModPairs r), CTypeOf r ~ ZqB64D)- => Dispatch' ZqB64D r where- dcrt ruptr pout totm pfac numFacts =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- tensorCRTRq numPairs (castPtr pout) totm pfac numFacts (castPtr ruptr) (castPtr qsptr)- dcrtinv ruptr minv pout totm pfac numFacts =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- tensorCRTInvRq numPairs (castPtr pout) totm pfac numFacts (castPtr ruptr) (castPtr minv) (castPtr qsptr)- dl pout totm pfac numFacts =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- tensorLRq numPairs (castPtr pout) totm pfac numFacts (castPtr qsptr)- dlinv pout totm pfac numFacts =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- tensorLInvRq numPairs (castPtr pout) totm pfac numFacts (castPtr qsptr)- dnorm = error "cannot call CT normSq on type ZqBasic"- dmulgpow pout totm pfac numFacts =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- tensorGPowRq numPairs (castPtr pout) totm pfac numFacts (castPtr qsptr)- dmulgdec pout totm pfac numFacts =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- tensorGDecRq numPairs (castPtr pout) totm pfac numFacts (castPtr qsptr)- dginvpow pout totm pfac numFacts =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- tensorGInvPowRq numPairs (castPtr pout) totm pfac numFacts (castPtr qsptr)- dginvdec pout totm pfac numFacts =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- tensorGInvDecRq numPairs (castPtr pout) totm pfac numFacts (castPtr qsptr)- dmul aout bout totm =- let qs = proxy getModuli (Proxy::Proxy r)- numPairs = proxy numComponents (Proxy::Proxy r)- in with qs $ \qsptr ->- mulRq numPairs (castPtr aout) (castPtr bout) totm (castPtr qsptr)- dgaussdec = error "cannot call CT gaussianDec on type ZqBasic"+dmulgdecC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dmulgdecC pout = tensorGDecC (castPtr pout) --- products of Complex correspond to CRTExt of a Zq product-instance (Tuple r, CTypeOf r ~ ComplexD) => Dispatch' ComplexD r where- dcrt ruptr pout totm pfac numFacts =- tensorCRTC (proxy numComponents (Proxy::Proxy r)) (castPtr pout) totm pfac numFacts (castPtr ruptr)- dcrtinv ruptr minv pout totm pfac numFacts =- tensorCRTInvC (proxy numComponents (Proxy::Proxy r)) (castPtr pout) totm pfac numFacts (castPtr ruptr) (castPtr minv)- dl pout =- tensorLC (proxy numComponents (Proxy::Proxy r)) (castPtr pout)- dlinv pout =- tensorLInvC (proxy numComponents (Proxy::Proxy r)) (castPtr pout)- dnorm = error "cannot call CT normSq on type Complex Double"- dmulgpow pout =- tensorGPowC (proxy numComponents (Proxy::Proxy r)) (castPtr pout)- dmulgdec pout =- tensorGDecC (proxy numComponents (Proxy::Proxy r)) (castPtr pout)- dginvpow pout =- tensorGInvPowC (proxy numComponents (Proxy::Proxy r)) (castPtr pout)- dginvdec pout =- tensorGInvDecC (proxy numComponents (Proxy::Proxy r)) (castPtr pout)- dmul aout bout =- mulC (proxy numComponents (Proxy::Proxy r)) (castPtr aout) (castPtr bout)- dgaussdec = error "cannot call CT gaussianDec on type Comple Double"+dginvpowC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dginvpowC pout = tensorGInvPowC (castPtr pout) --- no support for products of Double-instance Dispatch' DoubleD Double where- dcrt = error "cannot call CT Crt on type Double"- dcrtinv = error "cannot call CT CrtInv on type Double"- dl pout =- tensorLDouble 1 (castPtr pout)- dlinv pout =- tensorLInvDouble 1 (castPtr pout)- dnorm pout = tensorNormSqD 1 (castPtr pout)- dmulgpow = error "cannot call CT mulGPow on type Double"- dmulgdec = error "cannot call CT mulGDec on type Double"- dginvpow = error "cannot call CT divGPow on type Double"- dginvdec = error "cannot call CT divGDec on type Double"- dmul = error "cannot call CT (*) on type Double"- dgaussdec ruptr pout totm pfac numFacts =- tensorGaussianDec 1 (castPtr pout) totm pfac numFacts (castPtr ruptr)+dginvdecC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dginvdecC pout = tensorGInvDecC (castPtr pout) --- no support for products of Z-instance Dispatch' Int64D Int64 where- dcrt = error "cannot call CT Crt on type Int64"- dcrtinv = error "cannot call CT CrtInv on type Int64"- dl pout =- tensorLR 1 (castPtr pout)- dlinv pout =- tensorLInvR 1 (castPtr pout)- dnorm pout =- tensorNormSqR 1 (castPtr pout)- dmulgpow pout =- tensorGPowR 1 (castPtr pout)- dmulgdec pout =- tensorGDecR 1 (castPtr pout)- dginvpow pout =- tensorGInvPowR 1 (castPtr pout)- dginvdec pout =- tensorGInvDecR 1 (castPtr pout)- dmul = error "cannot call CT (*) on type Int64"- dgaussdec = error "cannot call CT gaussianDec on type Int64"+dmulC :: Ptr (Complex Double) -> Ptr (Complex Double) -> Int64 -> IO ()+dmulC aout bout = mulC (castPtr aout) (castPtr bout) -foreign import ccall unsafe "tensorLR" tensorLR :: Int16 -> Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorLInvR" tensorLInvR :: Int16 -> Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorLRq" tensorLRq :: Int16 -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr Int64 -> IO ()-foreign import ccall unsafe "tensorLInvRq" tensorLInvRq :: Int16 -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr Int64 -> IO ()-foreign import ccall unsafe "tensorLDouble" tensorLDouble :: Int16 -> Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorLInvDouble" tensorLInvDouble :: Int16 -> Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorLC" tensorLC :: Int16 -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorLInvC" tensorLInvC :: Int16 -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+-- q is nominal. C++ never sees it, so it doesn't matter what it is+dlRRq :: forall q . Ptr (RRq q Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlRRq pout = tensorLRRq (castPtr pout) -foreign import ccall unsafe "tensorNormSqR" tensorNormSqR :: Int16 -> Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorNormSqD" tensorNormSqD :: Int16 -> Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+-- q is nominal. C++ never sees it, so it doesn't matter what it is+dlinvRRq :: forall q . Ptr (RRq q Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlinvRRq pout = tensorLInvRRq (castPtr pout) -foreign import ccall unsafe "tensorGPowR" tensorGPowR :: Int16 -> Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorGPowRq" tensorGPowRq :: Int16 -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr Int64 -> IO ()-foreign import ccall unsafe "tensorGPowC" tensorGPowC :: Int16 -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorGDecR" tensorGDecR :: Int16 -> Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorGDecRq" tensorGDecRq :: Int16 -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr Int64 -> IO ()-foreign import ccall unsafe "tensorGDecC" tensorGDecC :: Int16 -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()-foreign import ccall unsafe "tensorGInvPowR" tensorGInvPowR :: Int16 -> Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO Int16-foreign import ccall unsafe "tensorGInvPowRq" tensorGInvPowRq :: Int16 -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr Int64 -> IO Int16-foreign import ccall unsafe "tensorGInvPowC" tensorGInvPowC :: Int16 -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO Int16-foreign import ccall unsafe "tensorGInvDecR" tensorGInvDecR :: Int16 -> Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO Int16-foreign import ccall unsafe "tensorGInvDecRq" tensorGInvDecRq :: Int16 -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr Int64 -> IO Int16-foreign import ccall unsafe "tensorGInvDecC" tensorGInvDecC :: Int16 -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dlDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlDouble pout = tensorLDouble (castPtr pout) -foreign import ccall unsafe "tensorCRTRq" tensorCRTRq :: Int16 -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (ZqBasic q Int64)) -> Ptr Int64 -> IO ()-foreign import ccall unsafe "tensorCRTC" tensorCRTC :: Int16 -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (Complex Double)) -> IO ()-foreign import ccall unsafe "tensorCRTInvRq" tensorCRTInvRq :: Int16 -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (ZqBasic q Int64)) -> Ptr (ZqBasic q Int64) -> Ptr Int64 -> IO ()-foreign import ccall unsafe "tensorCRTInvC" tensorCRTInvC :: Int16 -> Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (Complex Double)) -> Ptr (Complex Double) -> IO ()+dlinvDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlinvDouble pout = tensorLInvDouble (castPtr pout) -foreign import ccall unsafe "tensorGaussianDec" tensorGaussianDec :: Int16 -> Ptr Double -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (Complex Double)) -> IO ()+dnormDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+dnormDouble pout = tensorNormSqD (castPtr pout) -foreign import ccall unsafe "mulRq" mulRq :: Int16 -> Ptr (ZqBasic q Int64) -> Ptr (ZqBasic q Int64) -> Int64 -> Ptr Int64 -> IO ()-foreign import ccall unsafe "mulC" mulC :: Int16 -> Ptr (Complex Double) -> Ptr (Complex Double) -> Int64 -> IO ()+dmulgpowDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+dmulgpowDouble pout = tensorGPowDouble (castPtr pout)++dmulgdecDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+dmulgdecDouble pout = tensorGDecDouble (castPtr pout)++dginvpowDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dginvpowDouble pout = tensorGInvPowDouble (castPtr pout)++dginvdecDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dginvdecDouble pout = tensorGInvDecDouble (castPtr pout)++dgaussdecDouble :: Ptr (Ptr (Complex Double)) -> Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+dgaussdecDouble ruptr pout totm pfac numFacts =+ tensorGaussianDec (castPtr pout) totm pfac numFacts (castPtr ruptr)++dlInt64 :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlInt64 pout = tensorLR (castPtr pout)++dlinvInt64 :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+dlinvInt64 pout = tensorLInvR (castPtr pout)++dnormInt64 :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+dnormInt64 pout = tensorNormSqR (castPtr pout)++dmulgpowInt64 :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+dmulgpowInt64 pout = tensorGPowR (castPtr pout)++dmulgdecInt64 :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+dmulgdecInt64 pout = tensorGDecR (castPtr pout)++dginvpowInt64 :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dginvpowInt64 pout = tensorGInvPowR (castPtr pout)++dginvdecInt64 :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO Int16+dginvdecInt64 pout = tensorGInvDecR (castPtr pout)++foreign import ccall unsafe "tensorLR" tensorLR :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorLInvR" tensorLInvR :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorLRq" tensorLRq :: Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Int64 -> IO ()+foreign import ccall unsafe "tensorLInvRq" tensorLInvRq :: Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Int64 -> IO ()+foreign import ccall unsafe "tensorLDouble" tensorLDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorLInvDouble" tensorLInvDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorLRRq" tensorLRRq :: Ptr (RRq q Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorLInvRRq" tensorLInvRRq :: Ptr (RRq q Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorLC" tensorLC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorLInvC" tensorLInvC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()++foreign import ccall unsafe "tensorNormSqR" tensorNormSqR :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorNormSqD" tensorNormSqD :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()++foreign import ccall unsafe "tensorGPowR" tensorGPowR :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorGPowRq" tensorGPowRq :: Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Int64 -> IO ()+foreign import ccall unsafe "tensorGPowDouble" tensorGPowDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorGPowC" tensorGPowC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorGDecR" tensorGDecR :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorGDecRq" tensorGDecRq :: Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Int64 -> IO ()+foreign import ccall unsafe "tensorGDecDouble" tensorGDecDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorGDecC" tensorGDecC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO ()+foreign import ccall unsafe "tensorGInvPowR" tensorGInvPowR :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO Int16+foreign import ccall unsafe "tensorGInvPowRq" tensorGInvPowRq :: Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Int64 -> IO Int16+foreign import ccall unsafe "tensorGInvPowDouble" tensorGInvPowDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO Int16+foreign import ccall unsafe "tensorGInvPowC" tensorGInvPowC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO Int16+foreign import ccall unsafe "tensorGInvDecR" tensorGInvDecR :: Ptr Int64 -> Int64 -> Ptr CPP -> Int16 -> IO Int16+foreign import ccall unsafe "tensorGInvDecRq" tensorGInvDecRq :: Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Int64 -> IO Int16+foreign import ccall unsafe "tensorGInvDecDouble" tensorGInvDecDouble :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> IO Int16+foreign import ccall unsafe "tensorGInvDecC" tensorGInvDecC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> IO Int16++foreign import ccall unsafe "tensorCRTRq" tensorCRTRq :: Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (ZqBasic q Int64)) -> Int64 -> IO ()+foreign import ccall unsafe "tensorCRTC" tensorCRTC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (Complex Double)) -> IO ()+foreign import ccall unsafe "tensorCRTInvRq" tensorCRTInvRq :: Ptr (ZqBasic q Int64) -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (ZqBasic q Int64)) -> Ptr (ZqBasic q Int64) -> Int64 -> IO ()+foreign import ccall unsafe "tensorCRTInvC" tensorCRTInvC :: Ptr (Complex Double) -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (Complex Double)) -> Ptr (Complex Double) -> IO ()++foreign import ccall unsafe "tensorGaussianDec" tensorGaussianDec :: Ptr Double -> Int64 -> Ptr CPP -> Int16 -> Ptr (Ptr (Complex Double)) -> IO ()++foreign import ccall unsafe "mulRq" mulRq :: Ptr (ZqBasic q Int64) -> Ptr (ZqBasic q Int64) -> Int64 -> Int64 -> IO ()+foreign import ccall unsafe "mulC" mulC :: Ptr (Complex Double) -> Ptr (Complex Double) -> Int64 -> IO ()
Crypto/Lol/Cyclotomic/Tensor/CPP/Extension.hs view
@@ -3,7 +3,7 @@ Description : Embedding/twacing in various bases for CPP. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX@@ -11,6 +11,7 @@ CPP Tensor-specific functions for embedding/twacing in various bases. -} +{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-}@@ -18,6 +19,7 @@ {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} @@ -30,12 +32,14 @@ ) where import Crypto.Lol.CRTrans-import Crypto.Lol.Cyclotomic.Tensor as T-import Crypto.Lol.Prelude as LP hiding (lift, null)+import Crypto.Lol.Cyclotomic.Tensor as T+import Crypto.Lol.Cyclotomic.Tensor.CPP.Instances ()+import Crypto.Lol.Prelude as LP hiding (lift, null)+import Crypto.Lol.Reflects import Crypto.Lol.Types.FiniteField+import Crypto.Lol.Types.Unsafe.ZqBasic hiding (ZqB, unZqB) import Crypto.Lol.Types.ZmStar - import Control.Applicative hiding (empty) import Control.Monad.Trans (lift) @@ -58,39 +62,39 @@ {-# INLINABLE backpermute' #-} backpermute' is v = generate (U.length is) (\i -> v ! (is U.! i)) -embedPow', embedDec' :: (Additive r, Storable r, m `Divides` m')+embedPow', embedDec' :: forall m m' r . (Additive r, Storable r, m `Divides` m') => Tagged '(m, m') (Vector r -> Vector r) {-# INLINABLE embedPow' #-} {-# INLINABLE embedDec' #-}--- | Embeds an vector in the powerful basis of the the mth cyclotomic ring--- to an vector in the powerful basis of the m'th cyclotomic ring when @m | m'@-embedPow' = (\indices arr -> generate (U.length indices) $ \idx ->+-- | Embeds an vector in the powerful basis of the @m@th cyclotomic+-- ring to a vector in the powerful basis of the @m'@th cyclotomic+-- ring+embedPow' = tag $ (\indices arr -> generate (U.length indices) $ \idx -> let (j0,j1) = indices U.! idx in if j0 == 0 then arr ! j1- else zero) <$> baseIndicesPow--- | Embeds an vector in the decoding basis of the the mth cyclotomic ring--- to an vector in the decoding basis of the m'th cyclotomic ring when @m | m'@-embedDec' = (\indices arr -> generate (U.length indices)+ else zero) $ baseIndicesPow @m @m'+-- | Same as 'embedPow'', but for the decoding basis.+embedDec' = tag $ (\indices arr -> generate (U.length indices) (\idx -> maybe LP.zero (\(sh,b) -> if b then negate (arr ! sh) else arr ! sh)- (indices U.! idx))) <$> baseIndicesDec+ (indices U.! idx))) $ baseIndicesDec @m @m' -- | Embeds an vector in the CRT basis of the the mth cyclotomic ring -- to an vector in the CRT basis of the m'th cyclotomic ring when @m | m'@-embedCRT' :: forall mon m m' r . (CRTrans mon r, Storable r, m `Divides` m')+embedCRT' :: forall m m' mon r . (CRTrans mon r, Storable r, m `Divides` m') => TaggedT '(m, m') mon (Vector r -> Vector r) embedCRT' =- (lift (proxyT crtInfo (Proxy::Proxy m') :: mon (CRTInfo r))) >>- (pureT $ backpermute' <$> baseIndicesCRT)+ lift (proxyT crtInfo (Proxy::Proxy m') :: mon (CRTInfo r)) >>+ tagT (pure $ backpermute' $ baseIndicesCRT @m @m') -- | maps a vector in the powerful/decoding basis, representing an -- O_m' element, to a vector of arrays representing O_m elements in -- the same type of basis-coeffs' :: (Storable r, m `Divides` m')+coeffs' :: forall m m' r . (Storable r, m `Divides` m') => Tagged '(m, m') (Vector r -> [Vector r])-coeffs' = flip (\x -> V.toList . V.map (`backpermute'` x))- <$> extIndicesCoeffs+coeffs' = tag $ flip (\x -> V.toList . V.map (`backpermute'` x))+ $ extIndicesCoeffs @m @m' -- | The "tweaked trace" function in either the powerful or decoding -- basis of the m'th cyclotomic ring to the mth cyclotomic ring when@@ -98,32 +102,28 @@ twacePowDec' :: forall m m' r . (Storable r, m `Divides` m') => Tagged '(m, m') (Vector r -> Vector r) {-# INLINABLE twacePowDec' #-}-twacePowDec' = backpermute' <$> extIndicesPowDec+twacePowDec' = tag $ backpermute' $ extIndicesPowDec @m @m' -kronToVec :: forall mon m r . (Monad mon, Fact m, Ring r, Storable r)- => TaggedT m mon (Kron r) -> TaggedT m mon (Vector r)-kronToVec v = do- vmat <- v- let n = proxy totientFact (Proxy::Proxy m)- return $ generate n (flip (indexK vmat) 0)+kronToVec :: forall m r . (Fact m, Ring r, Storable r) => Kron r -> Vector r+kronToVec v = generate (totientFact @m) (flip (indexK v) 0) twaceCRT' :: forall mon m m' r . (Storable r, CRTrans mon r, m `Divides` m') => TaggedT '(m, m') mon (Vector r -> Vector r)-{-# INLINE twaceCRT' #-}+{-# INLINABLE twaceCRT' #-} twaceCRT' = tagT $ do- g' <- proxyT (kronToVec gCRTK) (Proxy::Proxy m')- gInv <- proxyT (kronToVec gInvCRTK) (Proxy::Proxy m)- embed <- proxyT embedCRT' (Proxy::Proxy '(m,m'))- indices <- pure $ proxy extIndicesCRT (Proxy::Proxy '(m,m'))+ g' <- kronToVec @m' <$> gCRTK @m'+ gInv <- kronToVec @m <$> gInvCRTK @m+ embed <- untagT $ embedCRT' @m @m' (_, m'hatinv) <- proxyT crtInfo (Proxy::Proxy m')- let phi = proxy totientFact (Proxy::Proxy m)- phi' = proxy totientFact (Proxy::Proxy m')- mhat = fromIntegral $ proxy valueHatFact (Proxy::Proxy m)+ let phi = totientFact @m+ phi' = totientFact @m'+ mhat = fromIntegral $ valueHatFact @m hatRatioInv = m'hatinv * mhat reltot = phi' `div` phi -- tweak = mhat * g' / (m'hat * g) tweak = SV.map (* hatRatioInv) $ SV.zipWith (*) (embed gInv) g'+ indices = extIndicesCRT @m @m' return $ \ arr -> -- take true trace after mul-by-tweak let v = backpermute' indices (SV.zipWith (*) tweak arr) in generate phi $ \i -> foldl1' (+) $ SV.unsafeSlice (i*reltot) reltot v@@ -133,8 +133,8 @@ powBasisPow' :: forall m m' r . (m `Divides` m', Ring r, SV.Storable r) => Tagged '(m, m') [SV.Vector r] powBasisPow' = do- (_, phi, phi', _) <- indexInfo- idxs <- baseIndicesPow+ let (_, phi, phi', _) = indexInfo @m @m'+ idxs = baseIndicesPow @m @m' return $ LP.map (\k -> generate phi' $ \j -> let (j0,j1) = idxs U.! j in if j0==k && j1==0 then one else zero)@@ -142,23 +142,24 @@ -- | A list of vectors representing the mod-p CRT set of the -- extension O_m'/O_m-crtSetDec' :: forall m m' fp .- (m `Divides` m', PrimeField fp, Coprime (PToF (CharOf fp)) m', SV.Storable fp)- => Tagged '(m, m') [SV.Vector fp]+crtSetDec' :: forall m m' p .+ (m `Divides` m', Prime p, Coprime (PToF p) m',+ Reflects p Int64, IrreduciblePoly (ZqBasic p Int64))+-- previously: ToInteger z, Enum z, SV.Storable z, NFData z+ => Tagged '(m, m') [SV.Vector (ZqBasic p Int64)]+{-# INLINABLE crtSetDec' #-} crtSetDec' =- let m'p = Proxy :: Proxy m'- p = proxy valuePrime (Proxy::Proxy (CharOf fp))- phi = proxy totientFact m'p- d = proxy (order p) m'p- h :: Int = proxy valueHatFact m'p+ let p = valuePrime @p+ phi = totientFact @m'+ d = order @m' p+ h :: Int = valueHatFact @m' hinv = recip $ fromIntegral h in reify d $ \(_::Proxy d) -> do- let twCRTs' :: Kron (GF fp d)- = fromMaybe (error "internal error: crtSetDec': twCRTs") $ proxyT twCRTs m'p- zmsToIdx = proxy T.zmsToIndexFact m'p+ let twCRTs' :: Kron (GF (ZqBasic p Int64) d)+ = fromMaybe (error "internal error: crtSetDec': twCRTs") $ twCRTs @m'+ zmsToIdx = T.zmsToIndexFact @m' elt j i = indexK twCRTs' j (zmsToIdx i)- trace' = trace :: GF fp d -> fp -- to avoid recomputing powTraces- cosets <- partitionCosets p+ cosets = partitionCosets @m @m' p return $ LP.map (\is -> generate phi- (\j -> hinv * trace'+ (\j -> hinv * trace (LP.sum $ LP.map (elt j) is))) cosets
Crypto/Lol/Cyclotomic/Tensor/CPP/Instances.hs view
@@ -3,7 +3,7 @@ Description : CPP Tensor-specific instances. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX
Crypto/Lol/Cyclotomic/Tensor/CPP/common.cpp view
@@ -3,12 +3,13 @@ Description : Shared functions and data. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017 -License : GPL-2 +License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX */ +#include <cstdio> #include "types.h" hInt_t Zq::q; // should be in zq.cpp; here due to GHC #12152 @@ -24,4 +25,15 @@ base *= base; } return result; +} + +void* lolAlloc(size_t size) +{ + void *ret = malloc(size); + if (ret == NULL && size != 0) { + fprintf(stderr, "FATAL: Out of memory"); + fflush(stderr); + exit(1); + } + return ret; }
Crypto/Lol/Cyclotomic/Tensor/CPP/common.h view
@@ -3,7 +3,7 @@ Description : Shared functions and data. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX@@ -12,9 +12,13 @@ #ifndef COMMON_H_ #define COMMON_H_ +#include <cstddef> #include "types.h" // calculates base ** exp hDim_t ipow(hDim_t base, hShort_t exp);++// thin wrapper around malloc+void* lolAlloc(size_t size); #endif /* COMMON_H_ */
Crypto/Lol/Cyclotomic/Tensor/CPP/crt.cpp view
@@ -3,7 +3,7 @@ Description : Chinese remainder transform. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX@@ -32,8 +32,7 @@ return acc; } -template <typename ring> void crtTwiddle (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,- PrimeExponent pe, ring* ru)+template <typename ring> void crtTwiddle (ring* y, hDim_t lts, hDim_t rts, PrimeExponent pe, ring* ru) { hDim_t p = pe.prime; hShort_t e = pe.exponent;@@ -46,12 +45,12 @@ for(hDim_t i0 = 1; i0 < mprime; i0++) { // loops over i/(p-1) for i = 0..(m'-1), we can skip i0 = 0 hDim_t temp2 = i0*rts;- ring twid = ru[bitrev(pe, i0)*tupSize];+ ring twid = ru[bitrev(pe, i0)]; for(hDim_t blockIdx = 0; blockIdx < lts; blockIdx++) { hDim_t temp3 = blockIdx*blockDim + temp2; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) {- hDim_t idx = (temp3 + modOffset)*tupSize;+ hDim_t idx = (temp3 + modOffset); y[idx] *= twid; } }@@ -66,12 +65,12 @@ hDim_t temp1 = i0*(p-1); for(hDim_t i1 = 0; i1 < (p-1); i1++) { // loops over i%(p-1) for i = 0..(m'-1) hDim_t temp2 = (temp1+i1)*rts;- ring twid = ru[bitrev(pe, i0)*(i1+1)*tupSize];+ ring twid = ru[bitrev(pe, i0)*(i1+1)]; for(hDim_t blockIdx = 0; blockIdx < lts; blockIdx++) { hDim_t temp3 = blockIdx*blockDim + temp2; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) {- hDim_t idx = (temp3 + modOffset)*tupSize;+ hDim_t idx = (temp3 + modOffset); y[idx] *= twid; } }@@ -81,7 +80,7 @@ } // dim is power of p-template <typename ring> void dftTwiddle (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,+template <typename ring> void dftTwiddle (ring* y, hDim_t lts, hDim_t rts, PrimeExponent pe, hDim_t dim, hDim_t rustride, ring* ru) { hDim_t idx;@@ -94,12 +93,12 @@ hDim_t temp1 = rts*dim; // for use in computing [modified] tensorOffset for(hDim_t i0 = 1; i0 < mprime; i0++) { // loops over i/p for i = 0..(dim-1), but we skip i0=0 hDim_t temp3 = rts*(i0*p+1);- ring twid = ru[bitrev(pe,i0)*rustride*tupSize];+ ring twid = ru[bitrev(pe,i0)*rustride]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1 + temp3; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) {- idx = (temp2 + modOffset)*tupSize;+ idx = (temp2 + modOffset); y[idx] *= twid; } }@@ -111,12 +110,12 @@ for(hDim_t i0 = 1; i0 < mprime; i0++) { // loops over i/p for i = 0..(dim-1), but we skip i0=0 for(hDim_t i1 = 1; i1 < p; i1++) { // loops over i%p for i = 0..(dim-1), but we skip i1=0 hDim_t temp3 = rts*(i0*p+i1);- ring twid = ru[bitrev(pe,i0)*i1*rustride*tupSize];+ ring twid = ru[bitrev(pe,i0)*i1*rustride]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1 + temp3; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) {- idx = (temp2 + modOffset)*tupSize;+ idx = (temp2 + modOffset); y[idx] *= twid; } }@@ -128,7 +127,7 @@ //implied length of ru is rustride*p //implied length of tempSpace is p, if p is not a special case // temp is allowed to be NULL if p < DFTP_GENERIC_SIZE-template <typename ring> void dftp (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,+template <typename ring> void dftp (ring* y, hDim_t lts, hDim_t rts, hDim_t p, hDim_t rustride, ring* ru, ring* tempSpace) { hDim_t tensorOffset;@@ -140,16 +139,16 @@ hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset;- ring u = y[tensorOffset*tupSize];- ring t = y[(tensorOffset+rts)*tupSize];- y[tensorOffset*tupSize] = u + t;- y[(tensorOffset+rts)*tupSize] = u - t;+ ring u = y[tensorOffset];+ ring t = y[(tensorOffset+rts)];+ y[tensorOffset] = u + t;+ y[(tensorOffset+rts)] = u - t; } } } else if(p == 3) {- ring ru1 = ru[rustride*tupSize];- ring ru2 = ru[(rustride<<1)*tupSize];+ ring ru1 = ru[rustride];+ ring ru2 = ru[(rustride<<1)]; hDim_t temp1 = rts*3; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) {@@ -157,69 +156,69 @@ for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2, y3;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];- y3 = y[(tensorOffset+(rts<<1))*tupSize];+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)];+ y3 = y[(tensorOffset+(rts<<1))]; //q is <32 bits, so we can do 3 additions without overflow- y[tensorOffset*tupSize] += (y2 + y3);- y[(tensorOffset+rts)*tupSize] = y1 + (ru1*y2) + (ru2*y3);- y[(tensorOffset+(rts<<1))*tupSize] = y1 + (ru2*y2) + (ru1*y3);+ y[tensorOffset] += (y2 + y3);+ y[(tensorOffset+rts)] = y1 + (ru1*y2) + (ru2*y3);+ y[(tensorOffset+(rts<<1))] = y1 + (ru2*y2) + (ru1*y3); } } } else if(p == 5) { hDim_t temp1 = rts*5;- ring ru1 = ru[rustride*tupSize];- ring ru2 = ru[(rustride<<1)*tupSize];- ring ru3 = ru[(rustride*3)*tupSize];- ring ru4 = ru[(rustride<<2)*tupSize];+ ring ru1 = ru[rustride];+ ring ru2 = ru[(rustride<<1)];+ ring ru3 = ru[(rustride*3)];+ ring ru4 = ru[(rustride<<2)]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2, y3, y4, y5;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];- y3 = y[(tensorOffset+(rts<<1))*tupSize];- y4 = y[(tensorOffset+3*rts)*tupSize];- y5 = y[(tensorOffset+(rts<<2))*tupSize];- y[tensorOffset*tupSize] += y2 + y3 + y4 + y5;- y[(tensorOffset+rts)*tupSize] = y1 + (ru1*y2) + (ru2*y3) + (ru3*y4) + (ru4*y5);- y[(tensorOffset+(rts<<1))*tupSize] = y1 + (ru2*y2) + (ru4*y3) + (ru1*y4) + (ru3*y5);- y[(tensorOffset+rts*3)*tupSize] = y1 + (ru3*y2) + (ru1*y3) + (ru4*y4) + (ru2*y5);- y[(tensorOffset+(rts<<2))*tupSize] = y1 + (ru4*y2) + (ru3*y3) + (ru2*y4) + (ru1*y5);+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)];+ y3 = y[(tensorOffset+(rts<<1))];+ y4 = y[(tensorOffset+3*rts)];+ y5 = y[(tensorOffset+(rts<<2))];+ y[tensorOffset] += y2 + y3 + y4 + y5;+ y[(tensorOffset+rts)] = y1 + (ru1*y2) + (ru2*y3) + (ru3*y4) + (ru4*y5);+ y[(tensorOffset+(rts<<1))] = y1 + (ru2*y2) + (ru4*y3) + (ru1*y4) + (ru3*y5);+ y[(tensorOffset+rts*3)] = y1 + (ru3*y2) + (ru1*y3) + (ru4*y4) + (ru2*y5);+ y[(tensorOffset+(rts<<2))] = y1 + (ru4*y2) + (ru3*y3) + (ru2*y4) + (ru1*y5); } } } else if(p == 7) { hDim_t temp1 = rts*7;- ring ru1 = ru[rustride*tupSize];- ring ru2 = ru[(rustride<<1)*tupSize];- ring ru3 = ru[(rustride*3)*tupSize];- ring ru4 = ru[(rustride<<2)*tupSize];- ring ru5 = ru[(rustride*5)*tupSize];- ring ru6 = ru[(rustride*6)*tupSize];+ ring ru1 = ru[rustride];+ ring ru2 = ru[(rustride<<1)];+ ring ru3 = ru[(rustride*3)];+ ring ru4 = ru[(rustride<<2)];+ ring ru5 = ru[(rustride*5)];+ ring ru6 = ru[(rustride*6)]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2, y3, y4, y5, y6, y7;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];- y3 = y[(tensorOffset+(rts<<1))*tupSize];- y4 = y[(tensorOffset+3*rts)*tupSize];- y5 = y[(tensorOffset+(rts<<2))*tupSize];- y6 = y[(tensorOffset+rts*5)*tupSize];- y7 = y[(tensorOffset+rts*6)*tupSize];- y[tensorOffset*tupSize] += y2 + y3 + y4 + y5 + y6 + y7;- y[(tensorOffset+rts)*tupSize] = y1 + (ru1*y2) + (ru2*y3) + (ru3*y4) + (ru4*y5) + (ru5*y6) + (ru6*y7);- y[(tensorOffset+(rts<<1))*tupSize] = y1 + (ru2*y2) + (ru4*y3) + (ru6*y4) + (ru1*y5) + (ru3*y6) + (ru5*y7);- y[(tensorOffset+rts*3)*tupSize] = y1 + (ru3*y2) + (ru6*y3) + (ru2*y4) + (ru5*y5) + (ru1*y6) + (ru4*y7);- y[(tensorOffset+(rts<<2))*tupSize] = y1 + (ru4*y2) + (ru1*y3) + (ru5*y4) + (ru2*y5) + (ru6*y6) + (ru3*y7);- y[(tensorOffset+rts*5)*tupSize] = y1 + (ru5*y2) + (ru3*y3) + (ru1*y4) + (ru6*y5) + (ru4*y6) + (ru2*y7);- y[(tensorOffset+rts*6)*tupSize] = y1 + (ru6*y2) + (ru5*y3) + (ru4*y4) + (ru3*y5) + (ru2*y6) + (ru1*y7);+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)];+ y3 = y[(tensorOffset+(rts<<1))];+ y4 = y[(tensorOffset+3*rts)];+ y5 = y[(tensorOffset+(rts<<2))];+ y6 = y[(tensorOffset+rts*5)];+ y7 = y[(tensorOffset+rts*6)];+ y[tensorOffset] += y2 + y3 + y4 + y5 + y6 + y7;+ y[(tensorOffset+rts)] = y1 + (ru1*y2) + (ru2*y3) + (ru3*y4) + (ru4*y5) + (ru5*y6) + (ru6*y7);+ y[(tensorOffset+(rts<<1))] = y1 + (ru2*y2) + (ru4*y3) + (ru6*y4) + (ru1*y5) + (ru3*y6) + (ru5*y7);+ y[(tensorOffset+rts*3)] = y1 + (ru3*y2) + (ru6*y3) + (ru2*y4) + (ru5*y5) + (ru1*y6) + (ru4*y7);+ y[(tensorOffset+(rts<<2))] = y1 + (ru4*y2) + (ru1*y3) + (ru5*y4) + (ru2*y5) + (ru6*y6) + (ru3*y7);+ y[(tensorOffset+rts*5)] = y1 + (ru5*y2) + (ru3*y3) + (ru1*y4) + (ru6*y5) + (ru4*y6) + (ru2*y7);+ y[(tensorOffset+rts*6)] = y1 + (ru6*y2) + (ru5*y3) + (ru4*y4) + (ru3*y5) + (ru2*y6) + (ru1*y7); } } }@@ -233,19 +232,19 @@ tempSpace[row] = 0; //p is small (<< 30 bits), so we can do p additions of mod-q values without overflow for(hDim_t col = 0; col < p; col++) {- tempSpace[row] += (y[(tensorOffset+col*rts)*tupSize]*ru[((col*row) % p)*rustride*tupSize]);+ tempSpace[row] += (y[(tensorOffset+col*rts)]*ru[((col*row) % p)*rustride]); } } for(hDim_t row = 0; row < p; row++) {- y[(tensorOffset+rts*row)*tupSize] = tempSpace[row];+ y[(tensorOffset+rts*row)] = tempSpace[row]; } } } } } -template <typename ring> void crtp (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,+template <typename ring> void crtp (ring* y, hDim_t lts, hDim_t rts, hDim_t p, hDim_t rustride, ring* ru) { hDim_t tensorOffset;@@ -254,75 +253,75 @@ } else if(p == 3) { hDim_t temp1 = rts*2;- ring ru1 = ru[rustride*tupSize];- ring ru2 = ru[(rustride<<1)*tupSize];+ ring ru1 = ru[rustride];+ ring ru2 = ru[(rustride<<1)]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];- y[tensorOffset*tupSize] += (ru1*y2);- y[(tensorOffset+rts)*tupSize] = y1 + (ru2*y2);+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)];+ y[tensorOffset] += (ru1*y2);+ y[(tensorOffset+rts)] = y1 + (ru2*y2); } } } else if(p == 5) { hDim_t temp1 = rts*4;- ring ru1 = ru[rustride*tupSize];- ring ru2 = ru[(rustride<<1)*tupSize];- ring ru3 = ru[(rustride*3)*tupSize];- ring ru4 = ru[(rustride<<2)*tupSize];+ ring ru1 = ru[rustride];+ ring ru2 = ru[(rustride<<1)];+ ring ru3 = ru[(rustride*3)];+ ring ru4 = ru[(rustride<<2)]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2, y3, y4;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];- y3 = y[(tensorOffset+(rts<<1))*tupSize];- y4 = y[(tensorOffset+3*rts)*tupSize];+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)];+ y3 = y[(tensorOffset+(rts<<1))];+ y4 = y[(tensorOffset+3*rts)]; - y[tensorOffset*tupSize] += ((ru1*y2) + (ru2*y3) + (ru3*y4));- y[(tensorOffset+rts)*tupSize] = y1 + (ru2*y2) + (ru4*y3) + (ru1*y4);- y[(tensorOffset+(rts<<1))*tupSize] = y1 + (ru3*y2) + (ru1*y3) + (ru4*y4);- y[(tensorOffset+rts*3)*tupSize] = y1 + (ru4*y2) + (ru3*y3) + (ru2*y4);+ y[tensorOffset] += ((ru1*y2) + (ru2*y3) + (ru3*y4));+ y[(tensorOffset+rts)] = y1 + (ru2*y2) + (ru4*y3) + (ru1*y4);+ y[(tensorOffset+(rts<<1))] = y1 + (ru3*y2) + (ru1*y3) + (ru4*y4);+ y[(tensorOffset+rts*3)] = y1 + (ru4*y2) + (ru3*y3) + (ru2*y4); } } } else if(p == 7) { hDim_t temp1 = rts*6;- ring ru1 = ru[rustride*tupSize];- ring ru2 = ru[(rustride<<1)*tupSize];- ring ru3 = ru[(rustride*3)*tupSize];- ring ru4 = ru[(rustride<<2)*tupSize];- ring ru5 = ru[(rustride*5)*tupSize];- ring ru6 = ru[(rustride*6)*tupSize];+ ring ru1 = ru[rustride];+ ring ru2 = ru[(rustride<<1)];+ ring ru3 = ru[(rustride*3)];+ ring ru4 = ru[(rustride<<2)];+ ring ru5 = ru[(rustride*5)];+ ring ru6 = ru[(rustride*6)]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2, y3, y4, y5, y6;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];- y3 = y[(tensorOffset+(rts<<1))*tupSize];- y4 = y[(tensorOffset+3*rts)*tupSize];- y5 = y[(tensorOffset+(rts<<2))*tupSize];- y6 = y[(tensorOffset+rts*5)*tupSize];- y[tensorOffset*tupSize] += ((ru1*y2) + (ru2*y3) + (ru3*y4) + (ru4*y5) + (ru5*y6));- y[(tensorOffset+rts)*tupSize] = y1 + (ru2*y2) + (ru4*y3) + (ru6*y4) + (ru1*y5) + (ru3*y6);- y[(tensorOffset+(rts<<1))*tupSize] = y1 + (ru3*y2) + (ru6*y3) + (ru2*y4) + (ru5*y5) + (ru1*y6);- y[(tensorOffset+rts*3)*tupSize] = y1 + (ru4*y2) + (ru1*y3) + (ru5*y4) + (ru2*y5) + (ru6*y6);- y[(tensorOffset+(rts<<2))*tupSize] = y1 + (ru5*y2) + (ru3*y3) + (ru1*y4) + (ru6*y5) + (ru4*y6);- y[(tensorOffset+rts*5)*tupSize] = y1 + (ru6*y2) + (ru5*y3) + (ru4*y4) + (ru3*y5) + (ru2*y6);+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)];+ y3 = y[(tensorOffset+(rts<<1))];+ y4 = y[(tensorOffset+3*rts)];+ y5 = y[(tensorOffset+(rts<<2))];+ y6 = y[(tensorOffset+rts*5)];+ y[tensorOffset] += ((ru1*y2) + (ru2*y3) + (ru3*y4) + (ru4*y5) + (ru5*y6));+ y[(tensorOffset+rts)] = y1 + (ru2*y2) + (ru4*y3) + (ru6*y4) + (ru1*y5) + (ru3*y6);+ y[(tensorOffset+(rts<<1))] = y1 + (ru3*y2) + (ru6*y3) + (ru2*y4) + (ru5*y5) + (ru1*y6);+ y[(tensorOffset+rts*3)] = y1 + (ru4*y2) + (ru1*y3) + (ru5*y4) + (ru2*y5) + (ru6*y6);+ y[(tensorOffset+(rts<<2))] = y1 + (ru5*y2) + (ru3*y3) + (ru1*y4) + (ru6*y5) + (ru4*y6);+ y[(tensorOffset+rts*5)] = y1 + (ru6*y2) + (ru5*y3) + (ru4*y4) + (ru3*y5) + (ru2*y6); } } } else {- ring* tempSpace = (ring*)malloc((p-1)*sizeof(ring));+ ring* tempSpace = (ring*)lolAlloc((p-1)*sizeof(ring)); hDim_t temp1 = rts*(p-1); for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1;@@ -332,12 +331,12 @@ for(hDim_t row = 1; row < p; row++) { tempSpace[row-1] = 0; for(hDim_t col = 0; col < p-1; col++) {- tempSpace[row-1] += (y[(tensorOffset+col*rts)*tupSize]*ru[((col*row) % p)*rustride*tupSize]);+ tempSpace[row-1] += (y[(tensorOffset+col*rts)]*ru[((col*row) % p)*rustride]); } } for(hDim_t row = 0; row < p-1; row++) {- y[(tensorOffset+rts*row)*tupSize] = tempSpace[row];+ y[(tensorOffset+rts*row)] = tempSpace[row]; } } }@@ -346,7 +345,7 @@ } //takes inverse rus-template <typename ring> void crtpinv (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,+template <typename ring> void crtpinv (ring* y, hDim_t lts, hDim_t rts, hDim_t p, hDim_t rustride, ring* ruinv) { hDim_t tensorOffset;@@ -355,83 +354,83 @@ } else if(p == 3) { hDim_t temp1 = rts*2;- ring ru1 = ruinv[rustride*tupSize];- ring ru2 = ruinv[(rustride<<1)*tupSize];+ ring ru1 = ruinv[rustride];+ ring ru2 = ruinv[(rustride<<1)]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2, shift;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)]; shift = (ru2*y1) + (ru1*y2); - y[tensorOffset*tupSize] += y2 - shift;- y[(tensorOffset+rts)*tupSize] = (ru1*y1) + (ru2*y2) - shift;+ y[tensorOffset] += y2 - shift;+ y[(tensorOffset+rts)] = (ru1*y1) + (ru2*y2) - shift; } } } else if(p == 5) { hDim_t temp1 = rts*4;- ring ru1 = ruinv[rustride*tupSize];- ring ru2 = ruinv[(rustride<<1)*tupSize];- ring ru3 = ruinv[(rustride*3)*tupSize];- ring ru4 = ruinv[(rustride<<2)*tupSize];+ ring ru1 = ruinv[rustride];+ ring ru2 = ruinv[(rustride<<1)];+ ring ru3 = ruinv[(rustride*3)];+ ring ru4 = ruinv[(rustride<<2)]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2, y3, y4, shift;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];- y3 = y[(tensorOffset+(rts<<1))*tupSize];- y4 = y[(tensorOffset+3*rts)*tupSize];+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)];+ y3 = y[(tensorOffset+(rts<<1))];+ y4 = y[(tensorOffset+3*rts)]; shift = (ru4*y1) + (ru3*y2) + (ru2*y3) + (ru1*y4); - y[tensorOffset*tupSize] += y2 + y3 + y4 - shift;- y[(tensorOffset+rts)*tupSize] = (ru1*y1) + (ru2*y2) + (ru3*y3) + (ru4*y4) - shift;- y[(tensorOffset+(rts<<1))*tupSize] = (ru2*y1) + (ru4*y2) + (ru1*y3) + (ru3*y4) - shift;- y[(tensorOffset+rts*3)*tupSize] = (ru3*y1) + (ru1*y2) + (ru4*y3) + (ru2*y4) - shift;+ y[tensorOffset] += y2 + y3 + y4 - shift;+ y[(tensorOffset+rts)] = (ru1*y1) + (ru2*y2) + (ru3*y3) + (ru4*y4) - shift;+ y[(tensorOffset+(rts<<1))] = (ru2*y1) + (ru4*y2) + (ru1*y3) + (ru3*y4) - shift;+ y[(tensorOffset+rts*3)] = (ru3*y1) + (ru1*y2) + (ru4*y3) + (ru2*y4) - shift; } } } else if(p == 7) { hDim_t temp1 = rts*6;- ring ru1 = ruinv[rustride*tupSize];- ring ru2 = ruinv[(rustride<<1)*tupSize];- ring ru3 = ruinv[(rustride*3)*tupSize];- ring ru4 = ruinv[(rustride<<2)*tupSize];- ring ru5 = ruinv[(rustride*5)*tupSize];- ring ru6 = ruinv[(rustride*6)*tupSize];+ ring ru1 = ruinv[rustride];+ ring ru2 = ruinv[(rustride<<1)];+ ring ru3 = ruinv[(rustride*3)];+ ring ru4 = ruinv[(rustride<<2)];+ ring ru5 = ruinv[(rustride*5)];+ ring ru6 = ruinv[(rustride*6)]; for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1; for(hDim_t modOffset = 0; modOffset < rts; modOffset++) { tensorOffset = temp2 + modOffset; ring y1, y2, y3, y4, y5, y6, shift;- y1 = y[tensorOffset*tupSize];- y2 = y[(tensorOffset+rts)*tupSize];- y3 = y[(tensorOffset+(rts<<1))*tupSize];- y4 = y[(tensorOffset+3*rts)*tupSize];- y5 = y[(tensorOffset+(rts<<2))*tupSize];- y6 = y[(tensorOffset+rts*5)*tupSize];+ y1 = y[tensorOffset];+ y2 = y[(tensorOffset+rts)];+ y3 = y[(tensorOffset+(rts<<1))];+ y4 = y[(tensorOffset+3*rts)];+ y5 = y[(tensorOffset+(rts<<2))];+ y6 = y[(tensorOffset+rts*5)]; shift = (ru6*y1) + (ru5*y2) + (ru4*y3) + (ru3*y4) + (ru2*y5) + (ru1*y6); - y[tensorOffset*tupSize] += y2 + y3 + y4 + y5 + y6 - shift;- y[(tensorOffset+rts)*tupSize] = (ru1*y1) + (ru2*y2) + (ru3*y3) + (ru4*y4) + (ru5*y5) + (ru6*y6) - shift;- y[(tensorOffset+(rts<<1))*tupSize] = (ru2*y1) + (ru4*y2) + (ru6*y3) + (ru1*y4) + (ru3*y5) + (ru5*y6) - shift;- y[(tensorOffset+rts*3)*tupSize] = (ru3*y1) + (ru6*y2) + (ru2*y3) + (ru5*y4) + (ru1*y5) + (ru4*y6) - shift;- y[(tensorOffset+(rts<<2))*tupSize] = (ru4*y1) + (ru1*y2) + (ru5*y3) + (ru2*y4) + (ru6*y5) + (ru3*y6) - shift;- y[(tensorOffset+rts*5)*tupSize] = (ru5*y1) + (ru3*y2) + (ru1*y3) + (ru6*y4) + (ru4*y5) + (ru2*y6) - shift;+ y[tensorOffset] += y2 + y3 + y4 + y5 + y6 - shift;+ y[(tensorOffset+rts)] = (ru1*y1) + (ru2*y2) + (ru3*y3) + (ru4*y4) + (ru5*y5) + (ru6*y6) - shift;+ y[(tensorOffset+(rts<<1))] = (ru2*y1) + (ru4*y2) + (ru6*y3) + (ru1*y4) + (ru3*y5) + (ru5*y6) - shift;+ y[(tensorOffset+rts*3)] = (ru3*y1) + (ru6*y2) + (ru2*y3) + (ru5*y4) + (ru1*y5) + (ru4*y6) - shift;+ y[(tensorOffset+(rts<<2))] = (ru4*y1) + (ru1*y2) + (ru5*y3) + (ru2*y4) + (ru6*y5) + (ru3*y6) - shift;+ y[(tensorOffset+rts*5)] = (ru5*y1) + (ru3*y2) + (ru1*y3) + (ru6*y4) + (ru4*y5) + (ru2*y6) - shift; } } } else {- ring* tempSpace = (ring*)malloc((p-1)*sizeof(ring));+ ring* tempSpace = (ring*)lolAlloc((p-1)*sizeof(ring)); hDim_t temp1 = rts*(p-1); for(hDim_t blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1;@@ -440,15 +439,15 @@ ring shift; shift = 0; for(hDim_t row = 0; row < p-1; row++) {- shift += (y[(tensorOffset+row*rts)*tupSize]*ruinv[(p-row-1)*rustride*tupSize]);+ shift += (y[(tensorOffset+row*rts)]*ruinv[(p-row-1)*rustride]); tempSpace[row] = 0; for(hDim_t col = 0; col < p-1; col++) {- tempSpace[row] += (y[(tensorOffset+col*rts)*tupSize]*ruinv[((row*(col+1)) % p)*rustride*tupSize]);+ tempSpace[row] += (y[(tensorOffset+col*rts)]*ruinv[((row*(col+1)) % p)*rustride]); } } for(hDim_t row = 0; row < p-1; row++) {- y[(tensorOffset+rts*row)*tupSize] = tempSpace[row] - shift;+ y[(tensorOffset+rts*row)] = tempSpace[row] - shift; } } }@@ -456,7 +455,7 @@ } } -template <typename ring> void ppDFT (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,+template <typename ring> void ppDFT (ring* y, hDim_t lts, hDim_t rts, PrimeExponent pe, hDim_t rustride, ring* ru, ring* temp) { hDim_t p = pe.prime;@@ -475,8 +474,8 @@ hDim_t twidRuStride = rustride; for(i = 0; i < e; i++) { hDim_t rtsDim = rts*rtsScale;- dftp (y, tupSize, lts*ltsScale, rtsDim, p, primeRuStride, ru, temp);- dftTwiddle (y, tupSize, lts, rtsDim, pe, ltsScale*p, twidRuStride, ru);+ dftp (y, lts*ltsScale, rtsDim, p, primeRuStride, ru, temp);+ dftTwiddle (y, lts, rtsDim, pe, ltsScale*p, twidRuStride, ru); ltsScale /= p; rtsScale *= p;@@ -485,7 +484,7 @@ } } -template <typename ring> void ppDFTInv (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,+template <typename ring> void ppDFTInv (ring* y, hDim_t lts, hDim_t rts, PrimeExponent pe, hDim_t rustride, ring* ru, ring* temp) { hDim_t p = pe.prime;@@ -505,8 +504,8 @@ for(i = 0; i < e; i++) { hDim_t rtsDim = rts*rtsScale; hDim_t ltsScaleP = ltsScale*p;- dftTwiddle (y, tupSize, lts, rtsDim, pe, ltsScaleP, twidRuStride, ru);- dftp (y, tupSize, lts*ltsScale, rtsDim, p, primeRuStride, ru, temp);+ dftTwiddle (y, lts, rtsDim, pe, ltsScaleP, twidRuStride, ru);+ dftp (y, lts*ltsScale, rtsDim, p, primeRuStride, ru, temp); ltsScale = ltsScaleP; rtsScale /= p;@@ -515,7 +514,7 @@ } } -template <typename ring> void ppcrt (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,+template <typename ring> void ppcrt (ring* y, hDim_t lts, hDim_t rts, PrimeExponent pe, ring* ru) { hDim_t p = pe.prime;@@ -523,13 +522,13 @@ hDim_t mprime = ipow(p,e-1); ring* temp = 0; if(p >= DFTP_GENERIC_SIZE) {- temp = (ring*)malloc(p*sizeof(ring));+ temp = (ring*)lolAlloc(p*sizeof(ring)); } - crtp (y, tupSize, lts*mprime, rts, p, mprime, ru);- crtTwiddle (y, tupSize, lts, rts, pe, ru);+ crtp (y, lts*mprime, rts, p, mprime, ru);+ crtTwiddle (y, lts, rts, pe, ru); pe.exponent -= 1;- ppDFT (y, tupSize, lts, rts*(p-1), pe, p, ru, temp);+ ppDFT (y, lts, rts*(p-1), pe, p, ru, temp); pe.exponent += 1; if(p >= DFTP_GENERIC_SIZE) {@@ -537,7 +536,7 @@ } } -template <typename ring> void ppcrtinv (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts,+template <typename ring> void ppcrtinv (ring* y, hDim_t lts, hDim_t rts, PrimeExponent pe, ring* ru) { hDim_t p = pe.prime;@@ -545,54 +544,51 @@ hDim_t mprime = ipow(p,e-1); ring* temp = 0; if(p >= DFTP_GENERIC_SIZE) {- temp = (ring*)malloc(p*sizeof(ring));+ temp = (ring*)lolAlloc(p*sizeof(ring)); } pe.exponent -= 1;- ppDFTInv (y, tupSize, lts, rts*(p-1), pe, p, ru, temp);+ ppDFTInv (y, lts, rts*(p-1), pe, p, ru, temp); pe.exponent += 1;- crtTwiddle (y, tupSize, lts, rts, pe, ru);- crtpinv (y, tupSize, lts*mprime, rts, p, mprime, ru);+ crtTwiddle (y, lts, rts, pe, ru);+ crtpinv (y, lts*mprime, rts, p, mprime, ru); if(p >= DFTP_GENERIC_SIZE) { free(temp); } } -extern "C" void tensorCRTRq (hShort_t tupSize, Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, Zq** ru, hInt_t* qs)+extern "C" void tensorCRTRq (Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, Zq** ru, hInt_t q) {- tensorFuserCRT (y, tupSize, ppcrt, totm, peArr, sizeOfPE, ru, qs);- canonicalizeZq(y,tupSize,totm,qs);+ Zq::q = q;+ tensorFuserCRT (y, ppcrt, totm, peArr, sizeOfPE, ru, q);+ canonicalizeZq(y,totm,q); } //takes inverse rus-extern "C" void tensorCRTInvRq (hShort_t tupSize, Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE,- Zq** ruinv, Zq* mhatInv, hInt_t* qs)+extern "C" void tensorCRTInvRq (Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE,+ Zq** ruinv, Zq* mhatInv, hInt_t q) {- tensorFuserCRT (y, tupSize, ppcrtinv, totm, peArr, sizeOfPE, ruinv, qs);- for (hShort_t i = 0; i < tupSize; i++) {- Zq::q = qs[i];- for (hDim_t j = 0; j < totm; j++) {- //careful here! I'm not setting the global q, so I can't rely on Zq multiplication- y[j*tupSize+i] = y[j*tupSize+i]*mhatInv[i];- }+ Zq::q = q;+ // TODO: Make mhatInv not a pointer?+ tensorFuserCRT (y, ppcrtinv, totm, peArr, sizeOfPE, ruinv, q);+ for (hDim_t j = 0; j < totm; j++) {+ y[j] = y[j] * (*mhatInv); }- canonicalizeZq(y,tupSize,totm,qs);+ canonicalizeZq(y,totm,q); } -extern "C" void tensorCRTC (hShort_t tupSize, Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, Complex** ru)+extern "C" void tensorCRTC (Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, Complex** ru) {- tensorFuserCRT (y, tupSize, ppcrt, totm, peArr, sizeOfPE, ru, (hInt_t*)0);+ tensorFuserCRT (y, ppcrt, totm, peArr, sizeOfPE, ru, 0); } //takes inverse rus-extern "C" void tensorCRTInvC (hShort_t tupSize, Complex* y, hDim_t totm, PrimeExponent* peArr,+extern "C" void tensorCRTInvC (Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, Complex** ruinv, Complex* mhatInv) {- tensorFuserCRT (y, tupSize, ppcrtinv, totm, peArr, sizeOfPE, ruinv, (hInt_t*)0);- for (hShort_t i = 0; i < tupSize; i++) {- for (hDim_t j = 0; j < totm; j++) {- y[j*tupSize+i] *= mhatInv[i];- }+ tensorFuserCRT (y, ppcrtinv, totm, peArr, sizeOfPE, ruinv, 0);+ for (hDim_t j = 0; j < totm; j++) {+ y[j] *= (*mhatInv); } }
Crypto/Lol/Cyclotomic/Tensor/CPP/g.cpp view
@@ -3,7 +3,7 @@ Description : Multiplication and division by 'g' in different bases. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017 -License : GPL-2 +License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX @@ -13,147 +13,134 @@ #include "tensor.h" #include "common.h" -template <typename ring> void gPow (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts, hDim_t p) +template <typename abgrp> void gPow (abgrp* y, hDim_t lts, hDim_t rts, hDim_t p) { if (p == 2) {return;} - hDim_t tmp1 = rts*(p-1); - hDim_t tmp2 = tmp1 - rts; - hDim_t blockOffset, modOffset; - hDim_t i; - for (blockOffset = 0; blockOffset < lts; ++blockOffset) { - hDim_t tmp3 = blockOffset * tmp1; - for (modOffset = 0; modOffset < rts; ++modOffset) { - hDim_t tensorOffset = tmp3 + modOffset; - ring last = y[(tensorOffset + tmp2)*tupSize]; - for (i = p-2; i != 0; --i) { - hDim_t idx = tensorOffset + i * rts; - y[idx*tupSize] += (last - y[(idx-rts)*tupSize]); + + for (hDim_t lblock = 0, lidx = 0; lblock < lts; ++lblock, lidx += (p-1)*rts) { + for (hDim_t rblock = 0, ridx = lidx; rblock < rts; ++rblock, ++ridx) { + // The new value y'_i = y_i + y_{p-1} - y_{i-1} where i > 0 + abgrp y_last = y[ridx + (p-2)*rts]; + for (hDim_t off = ridx + (p-2)*rts; off > ridx; off -= rts) { + y[off] += (y_last - y[off-rts]); } - y[tensorOffset*tupSize] += last; + // y_0 = y_0 + y_{p-2} + y[ridx] += y_last; } } } -template <typename ring> void gDec (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts, hDim_t p) +template <typename abgrp> void gDec (abgrp* y, hDim_t lts, hDim_t rts, hDim_t p) { if (p == 2) {return;} - hDim_t tmp1 = rts*(p-1); - hDim_t blockOffset; - hDim_t modOffset; - hDim_t i; - for (blockOffset = 0; blockOffset < lts; ++blockOffset) { - hDim_t tmp2 = blockOffset * tmp1; - for (modOffset = 0; modOffset < rts; ++modOffset) { - hDim_t tensorOffset = tmp2 + modOffset; - ring acc = y[tensorOffset*tupSize]; - for (i = p-2; i != 0; --i) { - hDim_t idx = tensorOffset + i * rts; - acc += y[idx*tupSize]; - y[idx*tupSize] -= y[(idx-rts)*tupSize]; + for (hDim_t lblock = 0, lidx = 0; lblock < lts; ++lblock, lidx += (p-1)*rts) { + for (hDim_t rblock = 0, ridx = lidx; rblock < rts; ++rblock, ++ridx) { + abgrp sum = y[ridx]; + // The new value y'_i = y_i - y_{i-1} where i > 0 + for (hDim_t off = ridx + (p-2)*rts; off > ridx; off -= rts) { + sum += y[off]; + y[off] -= y[off-rts]; } - y[tensorOffset*tupSize] += acc; + // At this point, sum = Σ y_i + // y_0 = y_0 + Σ y_i + y[ridx] += sum; } } } -template <typename ring> void gInvPow (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts, hDim_t p) +template <typename abgrp> void gInvPow (abgrp* y, hDim_t lts, hDim_t rts, hDim_t p) { if (p == 2) {return;} - hDim_t tmp1 = rts * (p-1); - hDim_t blockOffset, modOffset; - hDim_t i; - for (blockOffset = 0; blockOffset < lts; ++blockOffset) { - hDim_t tmp2 = blockOffset * tmp1; - for (modOffset = 0; modOffset < rts; ++modOffset) { - hDim_t tensorOffset = tmp2 + modOffset; - ring lelts; - lelts = 0; - for (i = 0; i < p-1; ++i) { - lelts += y[(tensorOffset + i*rts)*tupSize]; + for (hDim_t lblock = 0, lidx = 0; lblock < lts; ++lblock, lidx += (p-1)*rts) { + for (hDim_t rblock = 0, ridx = lidx; rblock < rts; ++rblock, ++ridx) { + // The new value y'_i = (p-i+1) * Σ_{j=1}^i y_j - i * + // Σ_{j=i+1}^{p-1} y_j We do this by letting sum = Σ y_i and + // having acc = sum at first. On each iteration, we let acc += + // (sum - p*y_i) + abgrp sum; + sum = 0; + for (hDim_t off = ridx; off < ridx + (p-1)*rts; off += rts) { + sum += y[off]; } - ring relts; - relts = 0; - for (i = p-2; i >= 0; --i) { - hDim_t idx = tensorOffset + i*rts; - ring z = y[idx*tupSize]; - ring lmul, rmul; - lmul = p-1-i; - rmul = i+1; - y[idx*tupSize] = lmul * lelts - rmul * relts; - lelts -= z; - relts += z; + abgrp acc = sum; + for (hDim_t off = ridx + (p-2)*rts; off >= ridx; off -= rts) { + abgrp tmp = y[off] * p; + y[off] = acc; + acc += (sum - tmp); } } } } -template <typename ring> void gInvDec (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts, hDim_t p) +template <typename abgrp> void gInvDec (abgrp* y, hDim_t lts, hDim_t rts, hDim_t p) { if (p == 2) {return;} - hDim_t blockOffset; - hDim_t modOffset; - hDim_t i; - hDim_t tmp1 = rts*(p-1); - for (blockOffset = 0; blockOffset < lts; ++blockOffset) { - hDim_t tmp2 = blockOffset*tmp1; - for (modOffset = 0; modOffset < rts; ++modOffset) { - hDim_t tensorOffset = tmp2 + modOffset; - ring lastOut; - lastOut = 0; - for (i=1; i < p; ++i) { - ring ri; - ri = i; - lastOut += (ri * y[(tensorOffset + (i-1)*rts)*tupSize]); + for (hDim_t lblock = 0, lidx = 0; lblock < lts; ++lblock, lidx += (p-1)*rts) { + for (hDim_t rblock = 0, ridx = lidx; rblock < rts; ++rblock, ++ridx) { + // sum = Σ (i+1)*y_i, i=0, ..., p-2 + abgrp sum; + sum = 0; + for (hDim_t i = 0, off = ridx; i < p-1; ++i, off += rts) { + sum += (y[off] * (i+1)); } - ring rp; - rp = p; - ring acc = lastOut; - for (i = p-2; i > 0; --i) { - hDim_t idx = tensorOffset + i*rts; - ring tmp = acc; - acc -= y[idx*tupSize]*rp; - y[idx*tupSize] = tmp; + // The new value y'_i = Σ j*y_j - p*Σ{j=i+1}^{p-1} y_j + // We do this by setting y'_i = sum and then letting sum -= p*y_i + for (hDim_t off = ridx + (p-2)*rts; off >= ridx; off -= rts) { + abgrp tmp = y[off]; + y[off] = sum; + sum -= (tmp * p); } - y[tensorOffset*tupSize] = acc; } } } -extern "C" void tensorGPowR (hShort_t tupSize, hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" void tensorGPowR (hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, gPow, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, gPow, totm, peArr, sizeOfPE, 0); } -extern "C" void tensorGPowRq (hShort_t tupSize, Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t* qs) +extern "C" void tensorGPowRq (Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t q) { - tensorFuserPrime (y, tupSize, gPow, totm, peArr, sizeOfPE, qs); - canonicalizeZq(y,tupSize,totm,qs); + Zq::q = q; + tensorFuserPrime(y, gPow, totm, peArr, sizeOfPE, q); + canonicalizeZq(y,totm,q); } -extern "C" void tensorGPowC (hShort_t tupSize, Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" void tensorGPowDouble (double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, gPow, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, gPow, totm, peArr, sizeOfPE, 0); } -extern "C" void tensorGDecR (hShort_t tupSize, hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" void tensorGPowC (Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, gDec, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, gPow, totm, peArr, sizeOfPE, 0); } -extern "C" void tensorGDecRq (hShort_t tupSize, Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t* qs) +extern "C" void tensorGDecR (hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, gDec, totm, peArr, sizeOfPE, qs); - canonicalizeZq(y,tupSize,totm,qs); + tensorFuserPrime (y, gDec, totm, peArr, sizeOfPE, 0); } -extern "C" void tensorGDecC (hShort_t tupSize, Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" void tensorGDecRq (Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t q) { - tensorFuserPrime (y, tupSize, gDec, totm, peArr, sizeOfPE, (hInt_t*)0); + Zq::q = q; + tensorFuserPrime (y, gDec, totm, peArr, sizeOfPE, q); + canonicalizeZq(y,totm,q); } +extern "C" void tensorGDecDouble (double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +{ + tensorFuserPrime (y, gDec, totm, peArr, sizeOfPE, 0); +} + +extern "C" void tensorGDecC (Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +{ + tensorFuserPrime (y, gDec, totm, peArr, sizeOfPE, 0); +} + hInt_t oddRad(PrimeExponent* peArr, hShort_t sizeOfPE) { hInt_t oddrad; oddrad = 1; @@ -166,14 +153,14 @@ return oddrad; } -extern "C" hShort_t tensorGInvPowR (hShort_t tupSize, hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" hShort_t tensorGInvPowR (hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, gInvPow, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, gInvPow, totm, peArr, sizeOfPE, 0); hInt_t oddrad = oddRad(peArr, sizeOfPE); - for(int i = 0; i < tupSize*totm; i++) { - if (y[i] % oddrad) { + for(int i = 0; i < totm; i++) { + if (y[i] % oddrad == 0) { y[i] /= oddrad; } else { @@ -183,50 +170,60 @@ return 1; } -extern "C" hShort_t tensorGInvPowRq (hShort_t tupSize, Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t* qs) +extern "C" hShort_t tensorGInvPowRq (Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t q) { - tensorFuserPrime (y, tupSize, gInvPow, totm, peArr, sizeOfPE, qs); + Zq::q = q; + tensorFuserPrime (y, gInvPow, totm, peArr, sizeOfPE, q); hInt_t oddrad = oddRad(peArr, sizeOfPE); - for(int i = 0; i < tupSize; i++) { - Zq::q = qs[i]; // global update - hInt_t ori = reciprocal(Zq::q, oddrad); - Zq oddradInv; - oddradInv = ori; - if (ori == 0) { - return 0; // error condition - } - for(hDim_t j = 0; j < totm; j++) { - y[j*tupSize+i] *= oddradInv; - } + hInt_t ori = reciprocal(Zq::q, oddrad); + Zq oddradInv; + oddradInv = ori; + if (ori == 0) { + return 0; // error condition } + for(hDim_t j = 0; j < totm; j++) { + y[j] *= oddradInv; + } - canonicalizeZq(y,tupSize,totm,qs); + canonicalizeZq(y,totm,q); return 1; } -extern "C" hShort_t tensorGInvPowC (hShort_t tupSize, Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" hShort_t tensorGInvPowDouble (double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, gInvPow, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, gInvPow, totm, peArr, sizeOfPE, 0); + double oddrad = (double)oddRad(peArr, sizeOfPE); + + for(int i = 0; i < totm; i++) { + y[i] /= oddrad; + } + return 1; +} + +extern "C" hShort_t tensorGInvPowC (Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +{ + tensorFuserPrime (y, gInvPow, totm, peArr, sizeOfPE, 0); + hInt_t oddrad = oddRad(peArr, sizeOfPE); - Complex oddradInv; - oddradInv = 1 / oddrad; - for(int i = 0; i < tupSize*totm; i++) { - y[i] *= oddradInv; + Complex oddradC = Complex((double)oddrad, 0.0); + + for(int i = 0; i < totm; i++) { + y[i] /= oddradC; } return 1; } -extern "C" hShort_t tensorGInvDecR (hShort_t tupSize, hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" hShort_t tensorGInvDecR (hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, gInvDec, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, gInvDec, totm, peArr, sizeOfPE, 0); hInt_t oddrad = oddRad(peArr, sizeOfPE); - for(int i = 0; i < tupSize*totm; i++) { - if (y[i] % oddrad) { + for(int i = 0; i < totm; i++) { + if (y[i] % oddrad == 0) { y[i] /= oddrad; } else { @@ -236,38 +233,48 @@ return 1; } -extern "C" hShort_t tensorGInvDecRq (hShort_t tupSize, Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t* qs) +extern "C" hShort_t tensorGInvDecRq (Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t q) { - tensorFuserPrime (y, tupSize, gInvDec, totm, peArr, sizeOfPE, qs); + Zq::q = q; + tensorFuserPrime (y, gInvDec, totm, peArr, sizeOfPE, q); hInt_t oddrad = oddRad(peArr, sizeOfPE); - for(int i = 0; i < tupSize; i++) { - Zq::q = qs[i]; // global update - hInt_t ori = reciprocal(Zq::q, oddrad); - Zq oddradInv; - oddradInv = ori; - if (ori == 0) { - return 0; // error condition - } - for(hDim_t j = 0; j < totm; j++) { - y[j*tupSize+i] *= oddradInv; - } + hInt_t ori = reciprocal(Zq::q, oddrad); + Zq oddradInv; + oddradInv = ori; + if (ori == 0) { + return 0; // error condition } + for(hDim_t j = 0; j < totm; j++) { + y[j] *= oddradInv; + } - canonicalizeZq(y,tupSize,totm,qs); + canonicalizeZq(y,totm,q); return 1; } -extern "C" hShort_t tensorGInvDecC (hShort_t tupSize, Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" hShort_t tensorGInvDecDouble (double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, gInvDec, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, gInvDec, totm, peArr, sizeOfPE, 0); + double oddrad = (double)oddRad(peArr, sizeOfPE); + + for(int i = 0; i < totm; i++) { + y[i] /= oddrad; + } + return 1; +} + +extern "C" hShort_t tensorGInvDecC (Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +{ + tensorFuserPrime (y, gInvDec, totm, peArr, sizeOfPE, 0); + hInt_t oddrad = oddRad(peArr, sizeOfPE); - Complex oddradInv; - oddradInv = 1 / oddrad; - for(int i = 0; i < tupSize*totm; i++) { - y[i] *= oddradInv; + Complex oddradC = Complex((double)oddrad, 0.0); + + for(int i = 0; i < totm; i++) { + y[i] /= oddradC; } return 1; -}+}
Crypto/Lol/Cyclotomic/Tensor/CPP/l.cpp view
@@ -3,96 +3,160 @@ Description : Powerful <-> Decoding basis conversion. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017 -License : GPL-2 +License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX + +Prime- and arbitrary-index transformations for the L operator +(see LPR13: https://eprint.iacr.org/2013/293) which converts between the +powerful and decoding basis representation for cyclotomic ring elements. +L converts decoding -> powerful represenation, L^{-1} is the reverse. */ #include "types.h" #include "tensor.h" -template <typename ring> void lp (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts, hDim_t p) +/* The prime-index transform that converts decoding basis coefficients (over any + * abelian group) to powerful basis coefficients. + * 'y' is an array of decoding basis coefficients in a three-dimensional tensor: + * [lts]x[rts]x[p-1]. + * We can think of the operator as (I_lts \otimes L_p \otimes I_rts). + */ +template <typename abgrp> void lp (abgrp* y, hDim_t lts, hDim_t rts, hDim_t p) { - hDim_t blockOffset; - hDim_t modOffset; - int i; - + // L_2 = id if(p == 2) {return;} - hDim_t tmp1 = rts*(p-1); - for (blockOffset = 0; blockOffset < lts; ++blockOffset) { - hDim_t tmp2 = blockOffset*tmp1; - for (modOffset = 0; modOffset < rts; ++modOffset) { - hDim_t idx = tmp2 + modOffset + rts; - for (i = 1; i < p-1; ++i) { - y[idx*tupSize] += y[(idx-rts)*tupSize]; - idx += rts; + // operate on the chunk of 'y' corresponding to each matrix on the diagonal. + // each square diagonal matrix in I_lts \otimes L_p \otimes I_rts has + // size (p-1)*rts + // lidx is the offset into y corresponding to the block diagonal matrix + for (hDim_t lblock = 0, lidx = 0; lblock < lts; ++lblock, lidx += (p-1)*rts) { + for (hDim_t rblock = 0, ridx = lidx; rblock < rts; ++rblock, ++ridx) { + // The new value y'_i = Σ_{j=1}^i y_i + // We do this from left to right, letting y'_i = y_i + y'_{i-1} + for (hDim_t off = ridx + rts; off < ridx + (p-1)*rts; off += rts) { + y[off] += y[off-rts]; } } } } -template <typename ring> void lpInv (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts, hDim_t p) +/* The prime-index transform that converts powerful basis coefficients (over any + * abelian group) to powerful basis coefficients. + * 'y' is an array of powerful basis coefficients in a three-dimensional tensor: + * [lts]x[rts]x[p-1]. + * We can think of the operator as I_lts \otimes L_p^{-1} \otimes I_rts). + */ +template <typename abgrp> void lpInv (abgrp* y, hDim_t lts, hDim_t rts, hDim_t p) { - hDim_t blockOffset; - hDim_t modOffset; - int i; - + // (L_2)^{-1} = id if(p == 2) {return;} - hDim_t tmp1 = rts*(p-1); - for (blockOffset = 0; blockOffset < lts; ++blockOffset) { - hDim_t tmp2 = blockOffset*tmp1; - for (modOffset = 0; modOffset < rts; ++ modOffset) { - hDim_t tensorOffset = tmp2 + modOffset; - hDim_t idx = tensorOffset + (p-2) * rts; - for (i = p-2; i != 0; --i) { - y[idx*tupSize] -= y[(idx-rts)*tupSize] ; - idx -= rts; + // operate on the chunk of 'y' corresponding to each matrix on the diagonal. + // each square diagonal matrix in I_lts \otimes (L_p \otimes I_rts) has + // size (p-1)*rts + // lidx is the offset into y corresponding to the block diagonal matrix + for (hDim_t lblock = 0, lidx = 0; lblock < lts; ++lblock, lidx += (p-1)*rts) { + for (hDim_t rblock = 0, ridx = lidx; rblock < rts; ++rblock, ++ridx) { + // The new value y'_i = y_i - y_{i-1} when i > 1 and y'_1 = y_1 + // We do this from right to left, letting y'_i = y_i - y_{i-1} + for (hDim_t off = ridx + (p-2)*rts; off > ridx; off -= rts) { + y[off] -= y[off-rts]; } } } } -extern "C" void tensorLRq (hShort_t tupSize, Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t* qs) +/* Arbitrary-index transformation that converts decoding basis coefficients + * (over a ring R mod (q1xq2x...), where the q_i's are pairwise coprime) into + * powerful basis coefficients. The input 'y' represents a three-dimensional + * tensor indexed as [lts]x[rts]x[p-1] + * + * Use "extern "C"" to avoid C++ name mangling, which makes it hard to call + * from Haskell. + */ +extern "C" void tensorLRq (Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t q) { - tensorFuserPrime (y, tupSize, lp, totm, peArr, sizeOfPE, qs); - canonicalizeZq(y,tupSize,totm,qs); + Zq::q = q; + tensorFuserPrime (y, lp, totm, peArr, sizeOfPE, q); + // Haskell expects each Z_q coefficient to be in the range 0 <= x < q_i, so + // ensure that is the case. + canonicalizeZq(y,totm,q); } -extern "C" void tensorLR (hShort_t tupSize, hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +/* Arbitrary-index transformation that converts decoding basis coefficients + * (over a ring R ~ Z[x]/(f(x)), so the coefficients are in Z) into + * powerful basis coefficients. The input 'y' represents a three-dimensional + * tensor indexed as [lts]x[rts]x[p-1]. + * + * Use "extern "C"" to avoid C++ name mangling, which makes it hard to call + * from Haskell. + */ +extern "C" void tensorLR (hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, lp, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, lp, totm, peArr, sizeOfPE, 0); } -extern "C" void tensorLDouble (hShort_t tupSize, double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" void tensorLDouble (double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, lp, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, lp, totm, peArr, sizeOfPE, 0); } -extern "C" void tensorLC (hShort_t tupSize, Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" void tensorLRRq (RRq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, lp, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, lp, totm, peArr, sizeOfPE, 0); + canonicalizeRRq(y,totm); } -extern "C" void tensorLInvRq (hShort_t tupSize, Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t* qs) +extern "C" void tensorLC (Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, lpInv, totm, peArr, sizeOfPE, qs); - canonicalizeZq(y,tupSize,totm,qs); + tensorFuserPrime (y, lp, totm, peArr, sizeOfPE, 0); } -extern "C" void tensorLInvR (hShort_t tupSize, hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +/* Arbitrary-index transformation that converts powerful basis coefficients + * (over a ring R mod (q1xq2x...), where the q_i's are pairwise coprime) into + * decoding basis coefficients. The input 'y' represents a three-dimensional + * tensor indexed as [lts]x[rts]x[p-1] + * + * Use "extern "C"" to avoid C++ name mangling, which makes it hard to call + * from Haskell. + */ +extern "C" void tensorLInvRq (Zq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t q) { - tensorFuserPrime (y, tupSize, lpInv, totm, peArr, sizeOfPE, (hInt_t*)0); + Zq::q = q; + tensorFuserPrime (y, lpInv, totm, peArr, sizeOfPE, q); + // Haskell expects each Z_q coefficient to be in the range 0 <= x < q_i, so + // ensure that is the case. + canonicalizeZq(y,totm,q); } -extern "C" void tensorLInvDouble (hShort_t tupSize, double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +/* Arbitrary-index transformation that converts powerful basis coefficients + * (over a ring R ~ Z[x]/(f(x)), so the coefficients are in Z) into + * decoding basis coefficients. The input 'y' represents a three-dimensional + * tensor indexed as [lts]x[rts]x[p-1]. + * + * Use "extern "C"" to avoid C++ name mangling, which makes it hard to call + * from Haskell. + */ +extern "C" void tensorLInvR (hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, lpInv, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, lpInv, totm, peArr, sizeOfPE, 0); } -extern "C" void tensorLInvC (hShort_t tupSize, Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +extern "C" void tensorLInvDouble (double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) { - tensorFuserPrime (y, tupSize, lpInv, totm, peArr, sizeOfPE, (hInt_t*)0); + tensorFuserPrime (y, lpInv, totm, peArr, sizeOfPE, 0); +} + +extern "C" void tensorLInvRRq (RRq* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +{ + tensorFuserPrime (y, lpInv, totm, peArr, sizeOfPE, 0); + canonicalizeRRq(y,totm); +} + +extern "C" void tensorLInvC (Complex* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) +{ + tensorFuserPrime (y, lpInv, totm, peArr, sizeOfPE, 0); }
Crypto/Lol/Cyclotomic/Tensor/CPP/mul.cpp view
@@ -3,7 +3,7 @@ Description : zipWith (*). Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX@@ -11,25 +11,26 @@ #include "types.h" -template <typename ring> void zipWithStar (ring* a, ring* b, hShort_t tupSize, hDim_t totm, hInt_t* qs)+template <typename ring> void zipWithStar (ring* a, ring* b, hDim_t totm, hInt_t q) {- for(int tupIdx = 0; tupIdx < tupSize; tupIdx++) {- if(qs) {- Zq::q = qs[tupIdx];- }- for(int i = 0; i < totm; i++) {- a[i*tupSize+tupIdx] *= b[i*tupSize+tupIdx];- }+ for(int i = 0; i < totm; i++) {+ a[i] *= b[i]; } } //a = zipWith (*) a b-extern "C" void mulRq (hShort_t tupSize, Zq* a, Zq* b, hDim_t totm, hInt_t* qs)+extern "C" void mulRq (Zq* a, Zq* b, hDim_t totm, hInt_t q) {- zipWithStar(a, b, tupSize, totm, qs);+ Zq::q = q;+ zipWithStar(a, b, totm, q); } -extern "C" void mulC (hShort_t tupSize, Complex* a, Complex* b, hDim_t totm)+extern "C" void mulC (Complex* a, Complex* b, hDim_t totm) {- zipWithStar(a, b, tupSize, totm, (hInt_t*)0);+ zipWithStar(a, b, totm, 0);+}++extern "C" void mulDouble (double* a, double* b, hDim_t totm)+{+ zipWithStar(a, b, totm, 0); }
Crypto/Lol/Cyclotomic/Tensor/CPP/norm.cpp view
@@ -3,7 +3,7 @@ Description : Compute g*norm(x)^2. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX@@ -12,7 +12,7 @@ #include "types.h" #include "tensor.h" -template <typename ring> void pNormSq (ring* y, hShort_t tupSize, hDim_t lts, hDim_t rts, hDim_t p)+template <typename ring> void pNormSq (ring* y, hDim_t lts, hDim_t rts, hDim_t p) { hDim_t blockOffset; hDim_t modOffset;@@ -27,54 +27,50 @@ hDim_t tensorOffset = tmp2 + modOffset; ring sum = 0; for (i = 0; i < p-1; ++i) {- sum += y[(tensorOffset + i*rts)*tupSize];+ sum += y[(tensorOffset + i*rts)]; } for (i = 0; i < p-1; ++i) {- y[(tensorOffset + i*rts)*tupSize] += sum;+ y[(tensorOffset + i*rts)] += sum; } } } } -extern "C" void tensorNormSqR (hShort_t tupSize, hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE)+extern "C" void tensorNormSqR (hInt_t* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) {- hInt_t* tempSpace = (hInt_t*)malloc(totm*tupSize*sizeof(hInt_t));- for(hDim_t i = 0; i < totm*tupSize; i++) {+ hInt_t* tempSpace = (hInt_t*)lolAlloc(totm*sizeof(hInt_t));+ for(hDim_t i = 0; i < totm; i++) { tempSpace[i]=y[i]; } - tensorFuserPrime(y, tupSize, pNormSq, totm, peArr, sizeOfPE, (hInt_t*)0);+ tensorFuserPrime(y, pNormSq, totm, peArr, sizeOfPE, 0); //do dot product and return in index 0- for(int tupIdx = 0; tupIdx < tupSize; tupIdx++) {- hInt_t dotprod = 0;- for(hDim_t i = 0; i < totm; i++) {- dotprod += (tempSpace[i*tupSize+tupIdx]*y[i*tupSize+tupIdx]);- }-- y[tupIdx] = dotprod;+ hInt_t dotprod = 0;+ for(hDim_t i = 0; i < totm; i++) {+ dotprod += (tempSpace[i]*y[i]); } + y[0] = dotprod;+ free(tempSpace); } -extern "C" void tensorNormSqD (hShort_t tupSize, double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE)+extern "C" void tensorNormSqD (double* y, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE) {- double* tempSpace = (double*)malloc(totm*tupSize*sizeof(double));- for(hDim_t i = 0; i < totm*tupSize; i++) {+ double* tempSpace = (double*)lolAlloc(totm*sizeof(double));+ for(hDim_t i = 0; i < totm; i++) { tempSpace[i]=y[i]; }- tensorFuserPrime(y, tupSize, pNormSq, totm, peArr, sizeOfPE, (hInt_t*)0);+ tensorFuserPrime(y, pNormSq, totm, peArr, sizeOfPE, 0); //do dot product and return in index 0- for(int tupIdx = 0; tupIdx < tupSize; tupIdx++) {- double dotprod = 0;- for(hDim_t i = 0; i < totm; i++) {- dotprod += (tempSpace[i*tupSize+tupIdx]*y[i*tupSize+tupIdx]);- }-- y[tupIdx] = dotprod;+ double dotprod = 0;+ for(hDim_t i = 0; i < totm; i++) {+ dotprod += (tempSpace[i]*y[i]); }++ y[0] = dotprod; free(tempSpace); }
Crypto/Lol/Cyclotomic/Tensor/CPP/random.cpp view
@@ -3,7 +3,7 @@ Description : Gaussian sampling on a lattice. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX@@ -16,13 +16,13 @@ // I had been negating the ru-idx, but this was causing a *negative* mod, resulting in a hard-to-find bug // current behavior (taking rus, rather than ruInv) matches RT-void primeD (double *y, hShort_t tupSize, hDim_t lts, hDim_t rts, hDim_t p, hDim_t rustride, Complex* ru)+void primeD (double *y, hDim_t lts, hDim_t rts, hDim_t p, hDim_t rustride, Complex* ru) {- if(p == 2) {+ if(p == 2) { return; } hDim_t blockOffset, modOffset, tensorOffset;- double *tempSpace = (double*)malloc((p-1)*sizeof(double));+ double *tempSpace = (double*)lolAlloc((p-1)*sizeof(double)); hDim_t temp1 = rts*(p-1); for(blockOffset = 0; blockOffset < lts; blockOffset++) { hDim_t temp2 = blockOffset*temp1;@@ -33,32 +33,32 @@ for(row = 0; row < p-1; row++) { double acc = 0; for(col = 1; col <= (p>>1); col++) {- acc += 2 * ru[((row*col) % p)*rustride*tupSize].real * y[(tensorOffset+rts*(col-1))*tupSize];+ acc += 2 * ru[((row*col) % p)*rustride].real * y[(tensorOffset+rts*(col-1))]; } for(col = (p>>1)+1; col <= p-1; col++) {- acc += 2 * ru[((row*col) % p)*rustride*tupSize].imag * y[(tensorOffset+rts*(col-1))*tupSize];+ acc += 2 * ru[((row*col) % p)*rustride].imag * y[(tensorOffset+rts*(col-1))]; } tempSpace[row] = acc/sqrt(2); } for(row = 0; row < p-1; row++) {- y[(tensorOffset+rts*row)*tupSize] = tempSpace[row];+ y[(tensorOffset+rts*row)] = tempSpace[row]; } } } free(tempSpace); } -void ppD (double *y, hShort_t tupSize, hDim_t lts, hDim_t rts, PrimeExponent pe, Complex *ru)+void ppD (double *y, hDim_t lts, hDim_t rts, PrimeExponent pe, Complex *ru) { hDim_t p = pe.prime; hDim_t e = pe.exponent; hDim_t mprime = ipow(p,e-1);- primeD (y, tupSize, lts*mprime, rts, p, mprime, ru);+ primeD (y, lts*mprime, rts, p, mprime, ru); } //the contents of y will be destroyed, but should be initialized in Haskell-land to independent Guassians over the reals-extern "C" void tensorGaussianDec (hShort_t tupSize, double *y, hDim_t totm, PrimeExponent *peArr, hShort_t sizeOfPE, Complex** ru)+extern "C" void tensorGaussianDec (double *y, hDim_t totm, PrimeExponent *peArr, hShort_t sizeOfPE, Complex** ru) {- tensorFuserCRT (y, tupSize, ppD, totm, peArr, sizeOfPE, ru, (hInt_t*)0);+ tensorFuserCRT (y, ppD, totm, peArr, sizeOfPE, ru, 0); }
+ Crypto/Lol/Cyclotomic/Tensor/CPP/rrq.cpp view
@@ -0,0 +1,23 @@+/*+Module : rrq.cpp+Description : Implementation of Z_q-specific functions.+Copyright : (c) Chris Peikert, 2018+License : GPL-3+Maintainer : cpeikert@alum.mit.edu+Stability : experimental+Portability : POSIX++A helper function for arithmetic in R/qZ: obtains the canonical representative of a RR_q element.+*/++#include "types.h"++// Put a RR_q coefficient in the range -1 < x < 1 into the range 0 <= x < 1+void canonicalizeRRq (RRq* y, hDim_t totm) {+ // canonicalize every coefficient with this modulus+ for (hDim_t i = 0; i < totm; i++) {+ if (y[i].x < 0) {+ y[i].x += 1;+ }+ }+}
Crypto/Lol/Cyclotomic/Tensor/CPP/tensor.h view
@@ -3,10 +3,15 @@ Description : Templates for the tensor DSL. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX++A miniature DSL for converting (some) prime-index operators into arbitrary-index+operators via the tensorial decomposition for cyclotomic rings. In particular,+this DSL applies when the prime-power operator is just the tensor (with identity)+of the prime-index operator. */ #ifndef TENSOR_CPP_@@ -15,35 +20,56 @@ #include "types.h" #include "common.h" #ifdef __cplusplus++// templated function pointer for prime-index transformations template <typename ring>-using primeFunc = void (*) (ring*, hShort_t, hDim_t, hDim_t, hDim_t);+using primeFunc = void (*) (ring*, hDim_t, hDim_t, hDim_t); +// templated function pointer for prime-index CRT-style transformations, which+// also have pointers to roots of unity template <typename ringy, typename ringru>-using primeCRTFunc = void (*) (ringy*, hShort_t, hDim_t, hDim_t, PrimeExponent, ringru*);+using primeCRTFunc = void (*) (ringy*, hDim_t, hDim_t, PrimeExponent, ringru*); -//for square transforms-template <typename ring> void tensorFuserPrime (ring* y, hShort_t tupSize, primeFunc<ring> f, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t* qs)+// Turns a prime-index transformation A_p which satisfies into+// A_{p^e} = I_{p^(e-1)} \otimes A_p into an arbitrary-index transformation.+// This mimics the tensor DSL in Haskell by turning A_m into+// A_{pp1} \otimes A_{pp2} \otimes ... \otimes A_{ppk}, where the prime-power+// factorization of m is pp1*pp2*...*ppk. It then applies turns each prime-power+// component into a tensor of prime-index transformations.+template <typename ring> void+ tensorFuserPrime(ring* y, primeFunc<ring> f, hDim_t totm,+ PrimeExponent* peArr, hShort_t sizeOfPE, hInt_t q) {+ // The first matrix to be applied (starting on the right) is+ // (I_totient(pp2..ppk) \otimes A_pp1 \otimes I_1).+ // From there, we shift pp2 to the right tensor, then pp3, etc. hDim_t lts = totm; hDim_t rts = 1; hShort_t i; for (i = 0; i < sizeOfPE; ++i) { PrimeExponent pe = peArr[i];+ // compute p^(e-1) hDim_t ipow_pe = ipow(pe.prime, (pe.exponent-1));- hDim_t dim = (pe.prime-1) * ipow_pe; // the totient of pe+ // totient(ppi)+ hDim_t dim = (pe.prime-1) * ipow_pe;+ // remove the totient for this operator from the left lts /= dim;- for(int tupIdx = 0; tupIdx < tupSize; tupIdx++) {- if(qs) {- Zq::q = qs[tupIdx]; // global update- }- (*f) (y+tupIdx, tupSize, lts*ipow_pe, rts, pe.prime);- }+ // apply the matrix+ // (I_totient((ppi+1)..ppk) \otimes A_ppi \otimes I_(pp1..(ppi-1)))+ // for a prime power++ // since A_ppi (where ppi = p^e) is I_{p^(e-1)} \otimes A_p,+ // add an additional p^(e-1) factor to lts and use the function+ // pointer to call the *prime*-index transform.+ (*f) (y, lts*ipow_pe, rts, pe.prime);++ // Add the prime power for the transform we just applied to the right tensor. rts *= dim; } } -template <typename ringy, typename ringru> void tensorFuserCRT (ringy* y, hShort_t tupSize, primeCRTFunc<ringy,ringru> f, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, ringru** ru, hInt_t* qs)+template <typename ringy, typename ringru> void tensorFuserCRT(ringy* y, primeCRTFunc<ringy,ringru> f, hDim_t totm, PrimeExponent* peArr, hShort_t sizeOfPE, ringru** ru, hInt_t q) { hDim_t lts = totm; hDim_t rts = 1;@@ -54,14 +80,10 @@ hDim_t ipow_pe = ipow(pe.prime, (pe.exponent-1)); hDim_t dim = (pe.prime-1) * ipow_pe; // the totient of pe lts /= dim;- for(int tupIdx = 0; tupIdx < tupSize; tupIdx++) {- if(qs) {- Zq::q = qs[tupIdx]; // global update- }- (*f) (y+tupIdx, tupSize, lts, rts, pe, ru[i]+tupIdx);- }+ (*f) (y, lts, rts, pe, ru[i]); rts *= dim; } }+ #endif /* __cplusplus */ #endif /* TENSOR_CPP_ */
Crypto/Lol/Cyclotomic/Tensor/CPP/types.h view
@@ -3,31 +3,35 @@ Description : C++ types and function declarations. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017 -License : GPL-2 +License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX + +Typedefs and data type for modular arithmetic. */ #ifndef TENSORTYPES_H_ #define TENSORTYPES_H_ -#include <inttypes.h> -#include <stdio.h> -#include <stdlib.h> +#include <cinttypes> +#include <cmath> +#include <cstdio> +#include <cstdlib> -typedef int64_t hInt_t ; -typedef int32_t hDim_t ; -typedef int16_t hShort_t ; -typedef int8_t hByte_t ; +typedef int64_t hInt_t; +typedef int32_t hDim_t; +typedef int16_t hShort_t; +typedef int8_t hByte_t; +// data type for a prime/exponent pair typedef struct { hShort_t prime; hShort_t exponent; } PrimeExponent; - +// computes the reciprocal of b mod a hInt_t reciprocal (hInt_t a, hInt_t b); #define ASSERT(EXP) { \ @@ -37,16 +41,35 @@ } \ } -//http://stackoverflow.com/questions/37572628 +// GHC can't handle C++ code in header files, so we must put guards around C++ +// code in header files: http://stackoverflow.com/questions/37572628 #ifdef __cplusplus //http://stackoverflow.com/a/4421719 + +// Class for integers modulo a number q. +// For efficiency, all operators output values in the range -q < x < q. +// This allows us to do the final conversion to canonical form only once at the +// end. class Zq { public: + // value in the range -q < x < q hInt_t x; - static hInt_t q; // declared here, defined in generalfuncs.cpp + // global modulus, which allows us to cast values to a Zq type for efficiency. + static hInt_t q; // declared here, defined in common.cpp due to GHC #12152. + // default constructor + Zq() : x(0) {} + + inline Zq operator-() + { + Zq out; + out.x = -x; + return out; + } + + // turn an hInt_t into a Zq with modular reduction. Zq& operator=(const hInt_t& c) { this->x = c % q; @@ -70,6 +93,14 @@ this->x %= q; return *this; } + Zq& operator*=(const hInt_t& b) + { + Zq c; + c = b; + *this *= c; + return *this; + } + // fails if b is not invertible mod q Zq& operator/=(const Zq& b) { Zq binv; @@ -79,6 +110,8 @@ return *this; } }; + +// binary operators defined in terms of the unary operators inline Zq operator+(Zq a, const Zq& b) { a += b; @@ -94,20 +127,107 @@ a *= b; return a; } +inline Zq operator*(Zq a, const hInt_t& b) +{ + a *= b; + return a; +} inline Zq operator/(Zq a, const Zq& b) { a /= b; return a; } -void canonicalizeZq (Zq* y, hShort_t tupSize, hDim_t totm, hInt_t* qs); +// Converts a Zq value into the range 0 <= x < q. This should be called +// before returning to Haskell. +void canonicalizeZq (Zq* y, hDim_t totm, hInt_t q); + +// Helper function. Outputs the fractional part of a given double, i.e., things in the range (-1, 1) +inline double fractional_part(double x) +{ + double _dummy; + return modf(x, &_dummy); +} + +// Class for real numbers modulo qZ. +// For efficiency, all operators output values in the range -1 < x < 1. +// This allows us to do the final conversion to canonical form only once at the +// end. +class RRq +{ +public: + // value in the range -1 < x < 1 + double x; + + // default constructor + RRq() : x(0) {} + + inline RRq operator-() + { + RRq out; + out.x = -x; + return out; + } + + // turn an hInt_t into a Zq with modular reduction. + RRq& operator=(const double& c) + { + this->x = fractional_part(c); + return *this; + } + RRq& operator+=(const RRq& b) + { + this->x += b.x; + this->x = fractional_part(this->x); + return *this; + } + RRq& operator-=(const RRq& b) + { + this->x -= b.x; + this->x = fractional_part(this->x); + return *this; + } +}; + +// binary operators defined in terms of the unary operators +inline RRq operator+(RRq a, const RRq& b) +{ + a += b; + return a; +} +inline RRq operator-(RRq a, const RRq& b) +{ + a -= b; + return a; +} + +// Converts an RRq value into the range 0 <= x < 1. This should be called +// before returning to Haskell +void canonicalizeRRq (RRq* y, hDim_t totm); + class Complex { public: double real; double imag; + // default constructor + Complex() : real(0.0), imag(0.0) {} + + Complex(const double& a, const double& b) { + this->real = a; + this->imag = b; + } + + inline Complex operator-() + { + Complex out; + out.real = -real; + out.imag = -imag; + return out; + } + Complex& operator=(const hInt_t& c) { this->real = c; @@ -133,6 +253,13 @@ this->imag = (a*b.imag)+(this->imag*b.real); return *this; } + Complex& operator*=(const hInt_t& b) + { + Complex c; + c = b; + *this *= c; + return *this; + } Complex& operator/=(const Complex& b) { Complex bconj; @@ -145,6 +272,7 @@ return *this; } }; + inline Complex operator+(Complex a, const Complex& b) { a += b; @@ -156,6 +284,11 @@ return a; } inline Complex operator*(Complex a, const Complex& b) +{ + a *= b; + return a; +} +inline Complex operator*(Complex a, const hInt_t& b) { a *= b; return a;
Crypto/Lol/Cyclotomic/Tensor/CPP/zq.cpp view
@@ -3,48 +3,62 @@ Description : Implementation of Z_q-specific functions. Copyright : (c) Eric Crockett, 2011-2017 Chris Peikert, 2011-2017-License : GPL-2+License : GPL-3 Maintainer : ecrockett0@email.com Stability : experimental Portability : POSIX++Helper functions for modular arithmetic, including computing the inverse of a+mod-q value, and obtaining the canonical representative of a Z_q element. */ #include "types.h" #include "common.h" -// a is the field size. we are looking for reciprocal of b+// Compute b^{-1} mod a (not necessarily in canonical form)+// Returns 0 if b is not invertible mod a. hInt_t reciprocal (hInt_t a, hInt_t b) {+ // extended Euclidean algorithm, matching description from wikipedia:+ // https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm+ // In this implementation, a an b track the 'r' sequence, t0/t1 track+ // the t sequence, which computes the inverse of b.+ hInt_t fieldSize = a; - hInt_t y = 1;- hInt_t lasty = 0;+ // t0/t1 help compute the Bezout coefficient for b (i.e., b inverse mod a)+ hInt_t t0 = 0;+ hInt_t t1 = 1;++ // Euclid's algorithm is done when we get a remainder of 0 while (b != 0) {+ // a = b*quotient + tmp hInt_t quotient = a / b; hInt_t tmp = a % b;+ // prepare for the next iteration a = b; b = tmp;- tmp = y;- y = lasty - quotient*y;- lasty = tmp;+ // store the next 't' coefficient into t1, and move the old t1 into t0+ tmp = t1;+ t1 = t0 - quotient*t1;+ t0 = tmp; }- // if a!=1, then b is not invertible mod a+ // if a (the last non-zero remainder) !=1, then b is not invertible mod a if(a!=1) { return 0; } // this actually returns EITHER the reciprocal OR reciprocal + fieldSize- hInt_t res = lasty + fieldSize;+ hInt_t res = t0 + fieldSize; return res; } -void canonicalizeZq (Zq* y, hShort_t tupSize, hDim_t totm, hInt_t* qs) {- for(int tupIdx = 0; tupIdx<tupSize; tupIdx++) {- hInt_t q = qs[tupIdx];- for(hDim_t j = 0; j < totm; j++) {- if(y[j*tupSize+tupIdx].x<0) {- y[j*tupSize+tupIdx].x+=q;- }+/* Put a Z_q coefficient in the range -q < x < q into the range 0 <= x < q*/+void canonicalizeZq (Zq* y, hDim_t totm, hInt_t q) {+ // canonicalize every coefficient with this modulus+ for(hDim_t j = 0; j < totm; j++) {+ if(y[j].x<0) {+ y[j].x+=q; } } }
LICENSE view
@@ -1,282 +1,623 @@- GNU GENERAL PUBLIC LICENSE- Version 2, June 1991+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc.,- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The licenses for most software are designed to take away your-freedom to share and change it. By contrast, the GNU General Public-License is intended to guarantee your freedom to share and change free-software--to make sure the software is free for all its users. This-General Public License applies to most of the Free Software-Foundation's software and to any other program whose authors commit to-using it. (Some other Free Software Foundation software is covered by-the GNU Lesser General Public License instead.) You can apply it to+ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for-this service if you wish), that you receive source code or can get it-if you want it, that you can change the software or use pieces of it-in new free programs; and that you know you can do these things.+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid-anyone to deny you these rights or to ask you to surrender the rights.-These restrictions translate to certain responsibilities for you if you-distribute copies of the software, or if you modify it.+ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether-gratis or for a fee, you must give the recipients all the rights that-you have. You must make sure that they, too, receive or can get the-source code. And you must show them these terms so they know their-rights.+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights. - We protect your rights with two steps: (1) copyright the software, and-(2) offer you this license which gives you legal permission to copy,-distribute and/or modify the software.+ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it. - Also, for each author's protection and ours, we want to make certain-that everyone understands that there is no warranty for this free-software. If the software is modified by someone else and passed on, we-want its recipients to know that what they have is not the original, so-that any problems introduced by others will not reflect on the original-authors' reputations.+ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions. - Finally, any free program is threatened constantly by software-patents. We wish to avoid the danger that redistributors of a free-program will individually obtain patent licenses, in effect making the-program proprietary. To prevent this, we have made it clear that any-patent must be licensed for everyone's free use or not licensed at all.+ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users. + Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.+ The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION+ TERMS AND CONDITIONS - 0. This License applies to any program or other work which contains-a notice placed by the copyright holder saying it may be distributed-under the terms of this General Public License. The "Program", below,-refers to any such program or work, and a "work based on the Program"-means either the Program or any derivative work under copyright law:-that is to say, a work containing the Program or a portion of it,-either verbatim or with modifications and/or translated into another-language. (Hereinafter, translation is included without limitation in-the term "modification".) Each licensee is addressed as "you".+ 0. Definitions. -Activities other than copying, distribution and modification are not-covered by this License; they are outside its scope. The act of-running the Program is not restricted, and the output from the Program-is covered only if its contents constitute a work based on the-Program (independent of having been made by running the Program).-Whether that is true depends on what the Program does.+ "This License" refers to version 3 of the GNU General Public License. - 1. You may copy and distribute verbatim copies of the Program's-source code as you receive it, in any medium, provided that you-conspicuously and appropriately publish on each copy an appropriate-copyright notice and disclaimer of warranty; keep intact all the-notices that refer to this License and to the absence of any warranty;-and give any other recipients of the Program a copy of this License-along with the Program.+ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks. -You may charge a fee for the physical act of transferring a copy, and-you may at your option offer warranty protection in exchange for a fee.+ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations. - 2. You may modify your copy or copies of the Program or any portion-of it, thus forming a work based on the Program, and copy and-distribute such modifications or work under the terms of Section 1-above, provided that you also meet all of these conditions:+ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work. - a) You must cause the modified files to carry prominent notices- stating that you changed the files and the date of any change.+ A "covered work" means either the unmodified Program or a work based+on the Program. - b) You must cause any work that you distribute or publish, that in- whole or in part contains or is derived from the Program or any- part thereof, to be licensed as a whole at no charge to all third- parties under the terms of this License.+ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well. - c) If the modified program normally reads commands interactively- when run, you must cause it, when started running for such- interactive use in the most ordinary way, to print or display an- announcement including an appropriate copyright notice and a- notice that there is no warranty (or else, saying that you provide- a warranty) and that users may redistribute the program under- these conditions, and telling the user how to view a copy of this- License. (Exception: if the Program itself is interactive but- does not normally print such an announcement, your work based on- the Program is not required to print an announcement.)+ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying. -These requirements apply to the modified work as a whole. If-identifiable sections of that work are not derived from the Program,-and can be reasonably considered independent and separate works in-themselves, then this License, and its terms, do not apply to those-sections when you distribute them as separate works. But when you-distribute the same sections as part of a whole which is a work based-on the Program, the distribution of the whole must be on the terms of-this License, whose permissions for other licensees extend to the-entire whole, and thus to each and every part regardless of who wrote it.+ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion. -Thus, it is not the intent of this section to claim rights or contest-your rights to work written entirely by you; rather, the intent is to-exercise the right to control the distribution of derivative or-collective works based on the Program.+ 1. Source Code. -In addition, mere aggregation of another work not based on the Program-with the Program (or with a work based on the Program) on a volume of-a storage or distribution medium does not bring the other work under-the scope of this License.+ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work. - 3. You may copy and distribute the Program (or a work based on it,-under Section 2) in object code or executable form under the terms of-Sections 1 and 2 above provided that you also do one of the following:+ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language. - a) Accompany it with the complete corresponding machine-readable- source code, which must be distributed under the terms of Sections- 1 and 2 above on a medium customarily used for software interchange; or,+ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it. - b) Accompany it with a written offer, valid for at least three- years, to give any third party, for a charge no more than your- cost of physically performing source distribution, a complete- machine-readable copy of the corresponding source code, to be- distributed under the terms of Sections 1 and 2 above on a medium- customarily used for software interchange; or,+ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work. - c) Accompany it with the information you received as to the offer- to distribute corresponding source code. (This alternative is- allowed only for noncommercial distribution and only if you- received the program in object code or executable form with such- an offer, in accord with Subsection b above.)+ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source. -The source code for a work means the preferred form of the work for-making modifications to it. For an executable work, complete source-code means all the source code for all modules it contains, plus any-associated interface definition files, plus the scripts used to-control compilation and installation of the executable. However, as a-special exception, the source code distributed need not include-anything that is normally distributed (in either source or binary-form) with the major components (compiler, kernel, and so on) of the-operating system on which the executable runs, unless that component-itself accompanies the executable.+ The Corresponding Source for a work in source code form is that+same work. -If distribution of executable or object code is made by offering-access to copy from a designated place, then offering equivalent-access to copy the source code from the same place counts as-distribution of the source code, even though third parties are not-compelled to copy the source along with the object code.+ 2. Basic Permissions. - 4. You may not copy, modify, sublicense, or distribute the Program-except as expressly provided under this License. Any attempt-otherwise to copy, modify, sublicense or distribute the Program is-void, and will automatically terminate your rights under this License.-However, parties who have received copies, or rights, from you under-this License will not have their licenses terminated so long as such-parties remain in full compliance.+ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law. - 5. You are not required to accept this License, since you have not-signed it. However, nothing else grants you permission to modify or-distribute the Program or its derivative works. These actions are-prohibited by law if you do not accept this License. Therefore, by-modifying or distributing the Program (or any work based on the-Program), you indicate your acceptance of this License to do so, and-all its terms and conditions for copying, distributing or modifying-the Program or works based on it.+ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you. - 6. Each time you redistribute the Program (or any work based on the-Program), the recipient automatically receives a license from the-original licensor to copy, distribute or modify the Program subject to-these terms and conditions. You may not impose any further-restrictions on the recipients' exercise of the rights granted herein.-You are not responsible for enforcing compliance by third parties to+ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent-infringement or for any other reason (not limited to patent issues),-conditions are imposed on you (whether by court order, agreement or-otherwise) that contradict the conditions of this License, they do not-excuse you from the conditions of this License. If you cannot-distribute so as to satisfy simultaneously your obligations under this-License and any other pertinent obligations, then as a consequence you-may not distribute the Program at all. For example, if a patent-license would not permit royalty-free redistribution of the Program by-all those who receive copies directly or indirectly through you, then-the only way you could satisfy both it and this License would be to-refrain entirely from distribution of the Program.+ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version. -If any portion of this section is held invalid or unenforceable under-any particular circumstance, the balance of the section is intended to-apply and the section as a whole is intended to apply in other-circumstances.+ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party. -It is not the purpose of this section to induce you to infringe any-patents or other property right claims or to contest validity of any-such claims; this section has the sole purpose of protecting the-integrity of the free software distribution system, which is-implemented by public license practices. Many people have made-generous contributions to the wide range of software distributed-through that system in reliance on consistent application of that-system; it is up to the author/donor to decide if he or she is willing-to distribute software through any other system and a licensee cannot-impose that choice.+ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid. -This section is intended to make thoroughly clear what is believed to-be a consequence of the rest of this License.+ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it. - 8. If the distribution and/or use of the Program is restricted in-certain countries either by patents or by copyrighted interfaces, the-original copyright holder who places the Program under this License-may add an explicit geographical distribution limitation excluding-those countries, so that distribution is permitted only in or among-countries not thus excluded. In such case, this License incorporates-the limitation as if written in the body of this License.+ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007. - 9. The Free Software Foundation may publish revised and/or new versions-of the General Public License from time to time. Such new versions will+ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program-specifies a version number of this License which applies to it and "any-later version", you have the option of following the terms and conditions-either of that version or of any later version published by the Free-Software Foundation. If the Program does not specify a version number of-this License, you may choose any version ever published by the Free Software-Foundation.+ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation. - 10. If you wish to incorporate parts of the Program into other free-programs whose distribution conditions are different, write to the author-to ask for permission. For software which is copyrighted by the Free-Software Foundation, write to the Free Software Foundation; we sometimes-make exceptions for this. Our decision will be guided by the two goals-of preserving the free status of all derivatives of our free software and-of promoting the sharing and reuse of software generally.+ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program. - NO WARRANTY+ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version. - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,-REPAIR OR CORRECTION.+ 15. Disclaimer of Warranty. - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE-POSSIBILITY OF SUCH DAMAGES.+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.+ END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs@@ -287,15 +628,15 @@ To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively-convey the exclusion of warranty; and each file should have at least+state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> - This program is free software; you can redistribute it and/or modify+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by- the Free Software Foundation; either version 2 of the License, or+ the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful,@@ -303,37 +644,31 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License along- with this program; if not, write to the Free Software Foundation, Inc.,- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.+ You should have received a copy of the GNU General Public License+ along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this-when it starts in an interactive mode:+ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode: - Gnomovision version 69, Copyright (C) year name of author- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate-parts of the General Public License. Of course, the commands you use may-be called something other than `show w' and `show c'; they could even be-mouse-clicks or menu items--whatever suits your program.--You should also get your employer (if you work as a programmer) or your-school, if any, to sign a "copyright disclaimer" for the program, if-necessary. Here is a sample; alter the names:-- Yoyodyne, Inc., hereby disclaims all copyright interest in the program- `Gnomovision' (which makes passes at compilers) written by James Hacker.+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box". - <signature of Ty Coon>, 1 April 1989- Ty Coon, President of Vice+ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>. -This General Public License does not permit incorporating your program into-proprietary programs. If your program is a subroutine library, you may-consider it more useful to permit linking proprietary applications with the-library. If this is what you want to do, use the GNU Lesser General-Public License instead of this License.+ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ benchmarks/BenchAppsCPPMain.hs view
@@ -0,0 +1,31 @@+{-|+Module : BenchAppsCPPMain+Description : Main driver for lol-apps benchmarks with CPP.+Copyright : (c) Eric Crockett, 2011-2017+ Chris Peikert, 2011-2017+License : GPL-3+Maintainer : ecrockett0@email.com+Stability : experimental+Portability : POSIX++Main driver for lol-apps benchmarks with CPP.+-}++{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DuplicateRecordFields #-}++module BenchAppsCPPMain where++import Crypto.Lol+import Crypto.Lol.Applications.Benchmarks+import Crypto.Lol.Benchmarks+import Crypto.Lol.Cyclotomic.Tensor.CPP+import Crypto.Random.DRBG++main :: IO ()+main = do+ let o = defaultTableOpts Nothing+ pct = Proxy::Proxy CT+ bgv <- defaultBGVBenches pct (Proxy::Proxy TrivGad) (Proxy::Proxy HashDRBG)+ khprf <- defaultKHPRFBenches pct (Proxy::Proxy (BaseBGad 2))+ mapM_ (prettyBenchesTable o) (bgv ++ khprf)
− benchmarks/BenchCPPMain.hs
@@ -1,83 +0,0 @@-{-|-Module : BenchCPPMain-Description : Main driver for CPP benchmarks.-Copyright : (c) Eric Crockett, 2011-2017- Chris Peikert, 2011-2017-License : GPL-2-Maintainer : ecrockett0@email.com-Stability : experimental-Portability : POSIX--Main driver for CPP benchmarks.--}--{-# LANGUAGE DataKinds #-}-{-# LANGUAGE NamedFieldPuns #-}-{-# LANGUAGE TypeOperators #-}--module BenchCPPMain where--import Crypto.Lol.Benchmarks-import Crypto.Lol.Benchmarks.Standard-import Crypto.Lol.Cyclotomic.Tensor.CPP-import Crypto.Lol.Factored-import qualified Crypto.Lol.Utils.PrettyPrint.Diagnostic as D-import qualified Crypto.Lol.Utils.PrettyPrint.Table as T-import Crypto.Random.DRBG--import Data.Proxy---- choose which layers of Lol to benchmark-ls :: [String]-ls = [- "STensor",- "Tensor",- "SUCyc",- "UCyc",- "Cyc"- ]---- choose which operations to benchmark-bs :: [String]-bs = [- "unzipPow",- "unzipDec",- "unzipCRT",- "zipWith (*)",- "crt",- "crtInv",- "l",- "lInv",- "*g Pow",- "*g Dec",- "*g CRT",- "divg Pow",- "divg Dec",- "divg CRT",- "lift",- "error",- "twacePow",- "twaceDec",- "twaceCRT",- "embedPow",- "embedDec",- "embedCRT"- ]--main :: IO ()-main = diagnosticMain--tableMain :: IO ()-tableMain = do- let opts = (T.defaultOpts $ Just "UCyc"){T.benches=bs}- g1 <- defaultBenches (Proxy::Proxy CT)- mapM_ (T.prettyBenches opts) g1--diagnosticMain :: IO ()-diagnosticMain = do- let opts = D.defaultOpts{D.levels=ls, D.benches=bs}- b1 <- benchGroup "Single Index"- [oneIdxBenches (Proxy::Proxy '(F64*F9*F25, Zq 14401)) (Proxy::Proxy CT) (Proxy::Proxy HashDRBG)]- b2 <- benchGroup "Twace-Embed"- [twoIdxBenches (Proxy::Proxy '(F64*F9*F25, F64*F9*F25, Zq 14401)) (Proxy::Proxy CT)]- mapM_ (D.prettyBenches opts) [b1,b2]
+ benchmarks/BenchLolCPPMain.hs view
@@ -0,0 +1,70 @@+{-|+Module : BenchLolCPPMain+Description : Main driver for lol benchmarks with CPP.+Copyright : (c) Eric Crockett, 2011-2017+ Chris Peikert, 2011-2017+License : GPL-3+Maintainer : ecrockett0@email.com+Stability : experimental+Portability : POSIX++Main driver for lol benchmarks with CPP.+-}++{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE NoStarIsType #-}+{-# LANGUAGE TypeOperators #-}++module BenchLolCPPMain where++import Crypto.Lol.Benchmarks+import Crypto.Lol.Cyclotomic.Tensor.CPP+import Crypto.Lol.Factored+import Crypto.Random.DRBG++import Data.Proxy++-- choose which layers of Lol to benchmark+ls :: [String]+ls = [+ "Tensor",+ "Cyc",+ "CycRep"+ ]++-- choose which operations to benchmark+bs :: [String]+bs = [+ "zipWith (*)",+ "crt",+ "crtInv",+ "l",+ "lInv",+ "*g Pow",+ "*g Dec",+ "*g CRT",+ "divG Pow",+ "divG Dec",+ "divG CRT",+ "lift",+ "error",+ "twacePow",+ "twaceDec",+ "twaceCRT",+ "embedPow",+ "embedDec",+ "embedCRT"+ ]++main :: IO ()+main = diagnosticMain++diagnosticMain :: IO ()+diagnosticMain = do+ let opts = defaultDiagnosticOpts{levels=ls, benches=bs}+ b1 = bgroup "Single Index"+ [oneIdxBenches (Proxy::Proxy '(F64*F9*F25, Zq 14401)) (Proxy::Proxy CT) (Proxy::Proxy HashDRBG)]+ b2 = bgroup "Twace-Embed"+ [twoIdxBenches (Proxy::Proxy '(F64*F9*F25, F64*F9*F25, Zq 14401)) (Proxy::Proxy CT)]+ mapM_ (prettyBenchesDiagnostic opts) [b1,b2]
lol-cpp.cabal view
@@ -1,119 +1,153 @@-name: lol-cpp--- The package version. See the Haskell package versioning policy (PVP)--- for standards guiding when and how versions should be incremented.--- http://www.haskell.org/haskellwiki/Package_versioning_policy--- PVP summary: +-+------- breaking API changes--- | | +----- non-breaking API additions--- | | | +--- code changes with no API change-version: 0.0.0.3-synopsis: A fast C++ backend for <https://hackage.haskell.org/package/lol lol>.-homepage: https://github.com/cpeikert/Lol-Bug-Reports: https://github.com/cpeikert/Lol/issues-license: GPL-2-license-file: LICENSE-author: Eric Crockett <ecrockett0@gmail.com>, Chris Peikert <cpeikert@alum.mit.edu>-maintainer: Eric Crockett <ecrockett0@gmail.com>-copyright: Eric Crockett, Chris Peikert-category: Crypto-stability: experimental-build-type: Simple-extra-source-files: README, CHANGES.md,- Crypto/Lol/Cyclotomic/Tensor/CPP/*.h,- Crypto/Lol/Cyclotomic/Tensor/CPP/*.cpp-cabal-version: >= 1.10-description:- Λ ∘ λ (Lol) is a general-purpose library for ring-based lattice cryptography.- This package provides a C++ implementation of Lol's Tensor interface.+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.31.2.+--+-- see: https://github.com/sol/hpack+--+-- hash: 41473b16ac120bfa8af8737be73585f746c046280949af8d0bd13fcb50bf8491++name: lol-cpp+version: 0.2.0.0+synopsis: A fast C++ backend for <https://hackage.haskell.org/package/lol lol>.+description: Λ ⚬ λ (Lol) is a general-purpose library for ring-based lattice cryptography. This package provides a C++ implementation of Lol's Tensor interface.+category: Crypto+stability: experimental+homepage: https://github.com/cpeikert/lol#readme+bug-reports: https://github.com/cpeikert/lol/issues+author: Eric Crockett <ecrockett0@gmail.com>,+ Chris Peikert <cpeikert@alum.mit.edu>+maintainer: Eric Crockett <ecrockett@gmail.com>,+ Chad Sharp <cmlsharp@umich.edu>+copyright: Eric Crockett,+ Chris Peikert+license: GPL-3+license-file: LICENSE+build-type: Simple+extra-source-files:+ README+ CHANGES.md+ Crypto/Lol/Cyclotomic/Tensor/CPP/common.h+ Crypto/Lol/Cyclotomic/Tensor/CPP/tensor.h+ Crypto/Lol/Cyclotomic/Tensor/CPP/types.h+ Crypto/Lol/Cyclotomic/Tensor/CPP/common.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/crt.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/g.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/l.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/mul.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/norm.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/random.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/rrq.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/zq.cpp+ source-repository head type: git- location: https://github.com/cpeikert/Lol---- For information on compiling C with cabal: http://blog.ezyang.com/2010/06/setting-up-cabal-the-ffi-and-c2hs/+ location: https://github.com/cpeikert/lol -Flag llvm- Description: Compile via LLVM. This produces much better object code,- but you need to have the LLVM compiler installed.- -- If you enable this and get errors like "Error: can't resolve `.rodata' {.rodata section}"- -- then GHC doesn't like your version of LLVM!- Default: False+flag llvm+ description: Compile via LLVM. This produces much better object code, but you need to have the LLVM compiler installed.+ manual: False+ default: False -Flag opt- Description: Turn on library optimizations- Default: True+flag opt+ description: Turn on library optimizations+ manual: False+ default: True -library- default-language: Haskell2010- ghc-options: -fwarn-dodgy-imports- cc-options: -std=c++11- Include-dirs: Crypto/Lol/Cyclotomic/Tensor/CPP- -- Due to #12152, the file containing the definition of `Zq::q` must be linked first,- -- otherwise dynamic linking (`cabal repl` or `stack ghci`) results in the error:- -- "Loading temp shared object failed: /tmp/ghc54651_0/libghc_1.so: undefined symbol _ZN2Zq1qE"- -- For `cabal repl`, we can simply reorder the list so that the file that should be linked- -- first comes first in the list. However `stack ghci` always links alphabetically,- -- so we really just have to define `Zq::q` in the first file alphabetically.- C-sources: Crypto/Lol/Cyclotomic/Tensor/CPP/common.cpp,- Crypto/Lol/Cyclotomic/Tensor/CPP/crt.cpp,- Crypto/Lol/Cyclotomic/Tensor/CPP/g.cpp,- Crypto/Lol/Cyclotomic/Tensor/CPP/l.cpp,- Crypto/Lol/Cyclotomic/Tensor/CPP/mul.cpp,- Crypto/Lol/Cyclotomic/Tensor/CPP/norm.cpp,- Crypto/Lol/Cyclotomic/Tensor/CPP/random.cpp,- Crypto/Lol/Cyclotomic/Tensor/CPP/zq.cpp+flag with-apps+ description: When this flag is enabled, lol-apps tests and benchmarks are buildable.+ manual: False+ default: True - if flag(llvm)- ghc-options: -fllvm -optlo-O3+flag with-execs+ description: When this flag and `with-apps` are both enabled, the lol-apps executables are buildable+ manual: False+ default: False - -- ghc optimizations- if flag(opt)- -- makes lift much faster!- ghc-options: -funfolding-use-threshold1000+library exposed-modules:- Crypto.Lol.Cyclotomic.Tensor.CPP-+ Crypto.Lol.Cyclotomic.Tensor.CPP other-modules:- Crypto.Lol.Cyclotomic.Tensor.CPP.Backend- Crypto.Lol.Cyclotomic.Tensor.CPP.Extension- Crypto.Lol.Cyclotomic.Tensor.CPP.Instances-+ Crypto.Lol.Cyclotomic.Tensor.CPP.Backend+ Crypto.Lol.Cyclotomic.Tensor.CPP.Extension+ Crypto.Lol.Cyclotomic.Tensor.CPP.Instances+ cc-options: -std=c++11 -O3+ include-dirs:+ Crypto/Lol/Cyclotomic/Tensor/CPP+ c-sources:+ Crypto/Lol/Cyclotomic/Tensor/CPP/common.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/crt.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/g.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/l.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/mul.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/norm.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/random.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/rrq.cpp+ Crypto/Lol/Cyclotomic/Tensor/CPP/zq.cpp build-depends:- base >= 4.9 && < 5,- constraints < 0.10,- deepseq >= 1.4.1.1 && < 1.5,- lol >= 0.6.0.0 && < 0.7,- MonadRandom >= 0.2 && < 0.6,- mtl >= 2.2.1 && < 2.3,- numeric-prelude >= 0.4.2 && < 0.5,- reflection >= 1.5.1 && < 2.2,- vector>=0.11 && < 0.13-- other-extensions: TemplateHaskell--Benchmark bench-lol-cpp- type: exitcode-stdio-1.0+ MonadRandom >=0.5.1 && <0.6+ , base >=4.12.0 && <4.13+ , constraints >=0.10 && <0.11+ , deepseq >=1.4.4 && <1.5+ , lol >=0.7.0.0 && <0.8+ , mtl >=2.2.2 && <2.3+ , numeric-prelude >=0.4.3 && <0.5+ , reflection >=2.1.5 && <2.2+ , vector >=0.12.0 && <0.13+ if flag(llvm)+ ghc-options: -fllvm -optlo-O3 -pgmlo opt default-language: Haskell2010- main-is: BenchCPPMain.hs- ghc-options: -main-is BenchCPPMain- hs-source-dirs: benchmarks - ghc-options: -O2 -funfolding-creation-threshold=15000 -funfolding-use-threshold=1000-+test-suite test-lol-apps-cpp+ type: exitcode-stdio-1.0+ main-is: TestAppsCPPMain.hs+ other-modules:+ TestLolCPPMain+ Paths_lol_cpp+ hs-source-dirs:+ tests+ ghc-options: -main-is TestAppsCPPMain build-depends:- base >= 4.9 && < 5,- DRBG < 0.6,- lol >= 0.6.0.0 && < 0.7,- lol-benches >= 0.0.0.3 && < 0.1,- lol-cpp+ base+ , lol >=0.7.0.0 && <0.8+ , lol-apps >=0.3 && <0.4+ , lol-cpp+ , test-framework+ if flag(llvm)+ ghc-options: -fllvm -optlo-O3 -pgmlo opt+ if !flag(with-apps)+ buildable: False+ default-language: Haskell2010 -test-suite test-lol-cpp- type: exitcode-stdio-1.0+benchmark bench-lol-apps-cpp+ type: exitcode-stdio-1.0+ main-is: BenchAppsCPPMain.hs+ hs-source-dirs:+ benchmarks+ ghc-options: -main-is BenchAppsCPPMain+ build-depends:+ DRBG+ , MonadRandom+ , base+ , lol >=0.7.0.0 && <0.8+ , lol-apps >=0.3 && <0.4+ , lol-cpp+ if flag(llvm)+ ghc-options: -fllvm -optlo-O3 -pgmlo opt+ if !flag(with-apps)+ buildable: False default-language: Haskell2010- main-is: TestCPPMain.hs- ghc-options: -main-is TestCPPMain- hs-source-dirs: tests- ghc-options: -threaded -O2 +benchmark bench-lol-cpp+ type: exitcode-stdio-1.0+ main-is: BenchLolCPPMain.hs+ hs-source-dirs:+ benchmarks+ ghc-options: -main-is BenchLolCPPMain build-depends:- base >= 4.9 && < 5,- lol-cpp,- lol-tests < 0.1+ DRBG+ , base+ , lol >=0.7.0.0 && <0.8+ , lol-cpp+ if flag(llvm)+ ghc-options: -fllvm -optlo-O3 -pgmlo opt+ default-language: Haskell2010
+ tests/TestAppsCPPMain.hs view
@@ -0,0 +1,26 @@+{-|+Module : TestAppsCPPMain+Description : Main driver for lol-apps tests with CPP.+Copyright : (c) Eric Crockett, 2011-2017+ Chris Peikert, 2011-2017+License : GPL-3+Maintainer : ecrockett0@email.com+Stability : experimental+Portability : POSIX++Main driver for lol-apps tests with CPP.+-}++module TestAppsCPPMain where++import Crypto.Lol (TrivGad)+import Crypto.Lol.Applications.Tests+import Crypto.Lol.Cyclotomic.Tensor.CPP+import Data.Proxy++import Test.Framework++main :: IO ()+main =+ flip defaultMainWithArgs ["--threads=1","--maximum-generated-tests=20"] $+ defaultAppsTests (Proxy::Proxy CT) (Proxy::Proxy TrivGad)
− tests/TestCPPMain.hs
@@ -1,21 +0,0 @@-{-|-Module : TestCPPMain-Description : Main driver for CPP tests.-Copyright : (c) Eric Crockett, 2011-2017- Chris Peikert, 2011-2017-License : GPL-2-Maintainer : ecrockett0@email.com-Stability : experimental-Portability : POSIX--Main driver for CPP tests.--}--module TestCPPMain where--import Crypto.Lol.Cyclotomic.Tensor.CPP-import Crypto.Lol.Tests.Standard-import Data.Proxy--main :: IO ()-main = defaultTestMain (Proxy::Proxy CT)
+ tests/TestLolCPPMain.hs view
@@ -0,0 +1,30 @@+{-|+Module : TestLolCPPMain+Description : Main driver for lol tests with CPP.+Copyright : (c) Eric Crockett, 2011-2017+ Chris Peikert, 2011-2017+License : GPL-3+Maintainer : ecrockett0@gmail.com+Stability : experimental+Portability : POSIX++Main driver for lol tests with CPP.+-}++module TestLolCPPMain where++import Crypto.Lol.Cyclotomic.Tensor.CPP+import Crypto.Lol.Tests+import Data.Proxy+import Test.Framework++main :: IO ()+main = defaultMainWithArgs+ [ defaultZqTests+ , zqTensorTests (Proxy::Proxy CT)+ , int64TensorTests (Proxy::Proxy CT)+ , dblTensorTests (Proxy::Proxy CT)+ , cpxTensorTests (Proxy::Proxy CT)+ , cycTests (Proxy::Proxy CT)+ ]+ ["--maximum-generated-tests=20"]