Palisade encoding headers
文章目录
- Palisade encoding headers
- \core\include\encoding\encodings.h
- \core\include\encoding\encodingparams.h
- \core\include\encoding\plaintextfactory.h
- \core\include\encoding\plaintext.h
- \core\include\encoding\stringencoding.h
- \core\include\encoding\packedencoding.h
- \core\include\encoding\coefpackedencoding.h
- \core\include\encoding\ckkspackedencoding.h
\core\include\encoding\encodings.h
all supported encodings of plaintext objects in Palisade.
#ifndef SRC_CORE_LIB_ENCODING_ENCODINGS_H_
#define SRC_CORE_LIB_ENCODING_ENCODINGS_H_
#include "encoding/ckkspackedencoding.h"
#include "encoding/coefpackedencoding.h"
#include "encoding/encodingparams.h"
#include "encoding/packedencoding.h"
#include "encoding/plaintext.h"
#include "encoding/stringencoding.h"
#endif /* SRC_CORE_LIB_ENCODING_ENCODINGS_H_ */
\core\include\encoding\encodingparams.h
Represents and defines parameters for plaintext encoding.
EncodingParams and PlaintextModulus
#ifndef LBCRYPTO_ENCODING_ENCODINGPARAMS_H
#define LBCRYPTO_ENCODING_ENCODINGPARAMS_H
#include <memory>
#include <string>
#include <utility>
#include "math/backend.h"
namespace lbcrypto {
class EncodingParamsImpl;
typedef std::shared_ptr<EncodingParamsImpl> EncodingParams;
typedef uint64_t PlaintextModulus;
EncodingParamsImpl类
private成员
private:
std::ostream &doprint(std::ostream &out) const {
out << "[p=" << m_plaintextModulus << " rootP =" << m_plaintextRootOfUnity
<< " bigP =" << m_plaintextBigModulus
<< " rootBigP =" << m_plaintextBigRootOfUnity
<< " g=" << m_plaintextGenerator << " L=" << m_batchSize << "]";
return out;
}
// plaintext modulus that is used by all schemes
PlaintextModulus m_plaintextModulus;
// root of unity for plaintext modulus
NativeInteger m_plaintextRootOfUnity;
// big plaintext modulus that is used for arbitrary cyclotomics
NativeInteger m_plaintextBigModulus;
// root of unity for big plaintext modulus
NativeInteger m_plaintextBigRootOfUnity;
// plaintext generator is used for packed encoding (to find the correct
// automorphism index)
uint32_t m_plaintextGenerator;
// maximum batch size used by EvalSumKeyGen for packed encoding
uint32_t m_batchSize;
public成员
/**
* @class EncodingParamsImpl
* @brief All parameters for plaintext encodings into ciphertext space.
*/
class EncodingParamsImpl : public lbcrypto::Serializable {
public:
/**
* Main constructor. Supports (1) default constructor, (2) regular encoding
* with plaintext modulus set, (3) packed encoding with at least first two
* parameters set. All of the private members not explicitly included as
* arguments will be initialized to zero.
*
* @param plaintextModulus plainext modulus (used by all encodings)
* @param plaintextGenerator (used by packed encoding for plaintext slot
* rotation)
* @param batchSize sets the maximum batch size (as a power of 2) needed for
* EvalSum
*/
EncodingParamsImpl(PlaintextModulus plaintextModulus = 0,
uint32_t batchSize = 0, uint32_t plaintextGenerator = 0,
NativeInteger plaintextRootOfUnity = 0,
NativeInteger plaintextBigModulus = 0,
NativeInteger plaintextBigRootOfUnity = 0) {
m_plaintextModulus = plaintextModulus;
m_plaintextRootOfUnity = plaintextRootOfUnity;
m_plaintextBigModulus = plaintextBigModulus;
m_plaintextBigRootOfUnity = plaintextBigRootOfUnity;
m_batchSize = batchSize;
m_plaintextGenerator = plaintextGenerator;
}
/**
* Copy constructor.
*
* @param &rhs the input set of parameters which is copied.
*/
EncodingParamsImpl(const EncodingParamsImpl &rhs) {
m_plaintextModulus = rhs.m_plaintextModulus;
m_plaintextRootOfUnity = rhs.m_plaintextRootOfUnity;
m_plaintextBigModulus = rhs.m_plaintextBigModulus;
m_plaintextBigRootOfUnity = rhs.m_plaintextBigRootOfUnity;
m_plaintextGenerator = rhs.m_plaintextGenerator;
m_batchSize = rhs.m_batchSize;
}
/**
* Move constructor.
*
* @param &rhs the input set of parameters which is copied.
*/
EncodingParamsImpl(const EncodingParamsImpl &&rhs) {
m_plaintextModulus = std::move(rhs.m_plaintextModulus);
m_plaintextRootOfUnity = std::move(rhs.m_plaintextRootOfUnity);
m_plaintextBigModulus = std::move(rhs.m_plaintextBigModulus);
m_plaintextBigRootOfUnity = std::move(rhs.m_plaintextBigRootOfUnity);
m_plaintextGenerator = std::move(rhs.m_plaintextGenerator);
m_batchSize = rhs.m_batchSize;
}
/**
* Assignment Operator.
*
* @param &rhs the EncodingParamsImpl to be copied.
* @return the resulting EncodingParamsImpl.
*/
const EncodingParamsImpl &operator=(const EncodingParamsImpl &rhs) {
m_plaintextModulus = rhs.m_plaintextModulus;
m_plaintextRootOfUnity = rhs.m_plaintextRootOfUnity;
m_plaintextBigModulus = rhs.m_plaintextBigModulus;
m_plaintextBigRootOfUnity = rhs.m_plaintextBigRootOfUnity;
m_plaintextGenerator = rhs.m_plaintextGenerator;
m_batchSize = rhs.m_batchSize;
return *this;
}
/**
* Destructor.
*/
virtual ~EncodingParamsImpl() {}
// ACCESSORS
// Get accessors
/**
* @brief Getter for the plaintext modulus.
* @return The plaintext modulus.
*/
const PlaintextModulus &GetPlaintextModulus() const {
return m_plaintextModulus;
}
/**
* @brief Setter for the plaintext modulus.
*/
void SetPlaintextModulus(PlaintextModulus plaintextModulus) {
m_plaintextModulus = plaintextModulus;
}
/**
* @brief Getter for the plaintext modulus root of unity.
* @return The plaintext modulus root of unity.
*/
const NativeInteger &GetPlaintextRootOfUnity() const {
return m_plaintextRootOfUnity;
}
/**
* @brief Setter for the plaintext modulus root of unity.
*/
void SetPlaintextRootOfUnity(const NativeInteger &plaintextRootOfUnity) {
m_plaintextRootOfUnity = plaintextRootOfUnity;
}
/**
* @brief Getter for the big plaintext modulus.
* @return The plaintext modulus.
*/
const NativeInteger &GetPlaintextBigModulus() const {
return m_plaintextBigModulus;
}
/**
* @brief Setter for the big plaintext modulus.
*/
void SetPlaintextBigModulus(const NativeInteger &plaintextBigModulus) {
m_plaintextBigModulus = plaintextBigModulus;
}
/**
* @brief Getter for the big plaintext modulus root of unity.
* @return The big plaintext modulus root of unity.
*/
const NativeInteger &GetPlaintextBigRootOfUnity() const {
return m_plaintextBigRootOfUnity;
}
/**
* @brief Setter for the big plaintext modulus root of unity.
*/
void SetPlaintextBigRootOfUnity(
const NativeInteger &plaintextBigRootOfUnity) {
m_plaintextBigRootOfUnity = plaintextBigRootOfUnity;
}
/**
* @brief Getter for the plaintext generator.
* @return The plaintext generator.
*/
usint GetPlaintextGenerator() const { return m_plaintextGenerator; }
/**
* @brief Setter for the plaintext generator.
*/
void SetPlaintextGenerator(usint &plaintextGenerator) {
m_plaintextGenerator = plaintextGenerator;
}
/**
* @brief Getter for the plaintext batch size.
* @return The plaintext batch size.
*/
uint32_t GetBatchSize() const { return m_batchSize; }
/**
* @brief Setter for the batch size
*/
void SetBatchSize(usint batchSize) { m_batchSize = batchSize; }
// Operators
/**
* @brief output stream operator.
* @param out the output stream to output.
* @param item the following object to output.
* @return the string output.
*/
friend std::ostream &operator<<(std::ostream &out,
const EncodingParamsImpl &item) {
return item.doprint(out);
}
/**
* @brief Equality operator for the parameters. Tests that all the parameters
* are equal.
* @param other the other parameter set to compare to.
* @return true if values of all data are equal.
*/
bool operator==(const EncodingParamsImpl &other) const {
return m_plaintextModulus == other.m_plaintextModulus &&
m_plaintextRootOfUnity == other.m_plaintextRootOfUnity &&
m_plaintextBigModulus == other.m_plaintextBigModulus &&
m_plaintextBigRootOfUnity == other.m_plaintextBigRootOfUnity &&
m_plaintextGenerator == other.m_plaintextGenerator &&
m_batchSize == other.m_batchSize;
}
/**
* @brief Inequality operator for the parameters. Tests that all the
* parameters are not equal.
* @param other the other parameter set to compare to.
* @return true if values of any data is not equal.
*/
bool operator!=(const EncodingParamsImpl &other) const {
return !(*this == other);
}
public:
template <class Archive>
void save(Archive &ar, std::uint32_t const version) const {
ar(::cereal::make_nvp("m", m_plaintextModulus));
ar(::cereal::make_nvp("ru", m_plaintextRootOfUnity));
ar(::cereal::make_nvp("bm", m_plaintextBigModulus));
ar(::cereal::make_nvp("bru", m_plaintextBigRootOfUnity));
ar(::cereal::make_nvp("g", m_plaintextGenerator));
ar(::cereal::make_nvp("bs", m_batchSize));
}
template <class Archive>
void load(Archive &ar, std::uint32_t const version) {
if (version > SerializedVersion()) {
PALISADE_THROW(deserialize_error,
"serialized object version " + std::to_string(version) +
" is from a later version of the library");
}
ar(::cereal::make_nvp("m", m_plaintextModulus));
ar(::cereal::make_nvp("ru", m_plaintextRootOfUnity));
ar(::cereal::make_nvp("bm", m_plaintextBigModulus));
ar(::cereal::make_nvp("bru", m_plaintextBigRootOfUnity));
ar(::cereal::make_nvp("g", m_plaintextGenerator));
ar(::cereal::make_nvp("bs", m_batchSize));
}
std::string SerializedObjectName() const { return "EncodingParms"; }
static uint32_t SerializedVersion() { return 1; }
};
类外操作符重载
inline std::ostream &operator<<(std::ostream &out,
std::shared_ptr<EncodingParamsImpl> o) {
if (o) out << *o;
return out;
}
inline bool operator==(std::shared_ptr<EncodingParamsImpl> o1,
std::shared_ptr<EncodingParamsImpl> o2) {
if (o1 && o2) return *o1 == *o2;
if (!o1 && !o2) return true;
return false;
}
} // namespace lbcrypto
#endif
\core\include\encoding\plaintextfactory.h
包含一个PlaintextFactory类,里面成员函数全是static,从来不创建PlaintextFactory对象,成员函数全是 MakePlaintext重载,返回Plaintext对象
三种:Poly,NativePoly,DCRTPoly
#ifndef SRC_CORE_LIB_ENCODING_PLAINTEXTFACTORY_H_
#define SRC_CORE_LIB_ENCODING_PLAINTEXTFACTORY_H_
#include <memory>
#include <string>
#include <vector>
#include "encoding/encodings.h"
// TODO: when the parms are polymorphic, reduce the tuple of methods to a
// single one
namespace lbcrypto {
class PlaintextFactory {
PlaintextFactory() {} // never construct one!
public:
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<Poly::Params> vp,
EncodingParams ep) {
Plaintext pt;
switch (encoding) {
case Unknown:
PALISADE_THROW(type_error,
"Unknown plaintext encoding type in MakePlaintext");
break;
case CoefPacked:
pt = std::make_shared<CoefPackedEncoding>(vp, ep);
break;
case Packed:
pt = std::make_shared<PackedEncoding>(vp, ep);
break;
case String:
pt = std::make_shared<StringEncoding>(vp, ep);
break;
case CKKSPacked:
pt = std::make_shared<CKKSPackedEncoding>(vp, ep);
break;
}
return pt;
}
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<NativePoly::Params> vp,
EncodingParams ep) {
Plaintext pt;
switch (encoding) {
case Unknown:
PALISADE_THROW(type_error,
"Unknown plaintext encoding type in MakePlaintext");
break;
case CoefPacked:
pt = std::make_shared<CoefPackedEncoding>(vp, ep);
break;
case Packed:
pt = std::make_shared<PackedEncoding>(vp, ep);
break;
case String:
pt = std::make_shared<StringEncoding>(vp, ep);
break;
case CKKSPacked:
pt = std::make_shared<CKKSPackedEncoding>(vp, ep);
break;
}
return pt;
}
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<DCRTPoly::Params> vp,
EncodingParams ep) {
Plaintext pt;
switch (encoding) {
case Unknown:
PALISADE_THROW(type_error,
"Unknown plaintext encoding type in MakePlaintext");
break;
case CoefPacked:
pt = std::make_shared<CoefPackedEncoding>(vp, ep);
break;
case Packed:
pt = std::make_shared<PackedEncoding>(vp, ep);
break;
case String:
pt = std::make_shared<StringEncoding>(vp, ep);
break;
case CKKSPacked:
pt = std::make_shared<CKKSPackedEncoding>(vp, ep);
break;
}
return pt;
}
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<Poly::Params> vp, EncodingParams ep,
const vector<int64_t>& value) {
Plaintext pt = MakePlaintext(encoding, vp, ep);
pt->SetIntVectorValue(value);
pt->Encode();
return pt;
}
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<NativePoly::Params> vp,
EncodingParams ep,
const vector<int64_t>& value) {
Plaintext pt = MakePlaintext(encoding, vp, ep);
pt->SetIntVectorValue(value);
pt->Encode();
return pt;
}
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<DCRTPoly::Params> vp,
EncodingParams ep,
const vector<int64_t>& value) {
Plaintext pt = MakePlaintext(encoding, vp, ep);
pt->SetIntVectorValue(value);
pt->Encode();
return pt;
}
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<Poly::Params> vp, EncodingParams ep,
const string& value) {
Plaintext pt = MakePlaintext(encoding, vp, ep);
pt->SetStringValue(value);
pt->Encode();
return pt;
}
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<NativePoly::Params> vp,
EncodingParams ep, const string& value) {
Plaintext pt = MakePlaintext(encoding, vp, ep);
pt->SetStringValue(value);
pt->Encode();
return pt;
}
static Plaintext MakePlaintext(PlaintextEncodings encoding,
shared_ptr<DCRTPoly::Params> vp,
EncodingParams ep, const string& value) {
Plaintext pt = MakePlaintext(encoding, vp, ep);
pt->SetStringValue(value);
pt->Encode();
return pt;
}
};
} /* namespace lbcrypto */
#endif /* SRC_CORE_LIB_ENCODING_PLAINTEXTFACTORY_H_ */
\core\include\encoding\plaintext.h
Represents and defines plaintext objects in Palisade.
PlaintextEncodings
enum PlaintextEncodings {
Unknown = 0,
CoefPacked,
Packed,
String,
CKKSPacked,
};
PlaintextImpl类
PlaintextImpl is primarily intended to be used as a container and in conjunction with specific encodings which inherit from this class which depend on the application the plaintext is used with It provides virtual methods for encoding and decoding of data.
PlaintextImpl主要用于作为一个容器,并与继承自该类的特定编码结合使用,这些编码依赖于使用明文的应用程序。它提供了对数据进行编码和解码的虚拟方法。
#ifndef LBCRYPTO_UTILS_PLAINTEXT_H
#define LBCRYPTO_UTILS_PLAINTEXT_H
#include <initializer_list>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "encoding/encodingparams.h"
#include "lattice/backend.h"
#include "math/backend.h"
#include "utils/inttypes.h"
using std::shared_ptr;
namespace lbcrypto {
enum PlaintextEncodings {
Unknown = 0,
CoefPacked,
Packed,
String,
CKKSPacked,
};
inline std::ostream& operator<<(std::ostream& out, const PlaintextEncodings p) {
switch (p) {
case Unknown:
out << "Unknown";
break;
case CoefPacked:
out << "CoefPacked";
break;
case Packed:
out << "Packed";
break;
case String:
out << "String";
break;
case CKKSPacked:
out << "CKKSPacked";
break;
}
return out;
}
class PlaintextImpl;
typedef shared_ptr<PlaintextImpl> Plaintext;
typedef shared_ptr<const PlaintextImpl> ConstPlaintext;
/**
* @class PlaintextImpl
* @brief This class represents plaintext in the Palisade library.
*
* PlaintextImpl is primarily intended to be
* used as a container and in conjunction with specific encodings which inherit
* from this class which depend on the application the plaintext is used with.
* It provides virtual methods for encoding and decoding of data.
*/
enum PtxtPolyType { IsPoly, IsDCRTPoly, IsNativePoly };
class PlaintextImpl {
protected:
bool isEncoded;
PtxtPolyType typeFlag;
EncodingParams encodingParams;
mutable Poly encodedVector;
mutable NativePoly encodedNativeVector;
mutable DCRTPoly encodedVectorDCRT;
static const int intCTOR = 0x01;
static const int vecintCTOR = 0x02;
static const int fracCTOR = 0x04;
static const int vecuintCTOR = 0x08;
double scalingFactor;
size_t level;
size_t depth;
public:
PlaintextImpl(shared_ptr<Poly::Params> vp, EncodingParams ep,
bool isEncoded = false)
: isEncoded(isEncoded),
typeFlag(IsPoly),
encodingParams(ep),
encodedVector(vp, Format::COEFFICIENT),
scalingFactor(1),
level(0),
depth(1) {}
PlaintextImpl(shared_ptr<NativePoly::Params> vp, EncodingParams ep,
bool isEncoded = false)
: isEncoded(isEncoded),
typeFlag(IsNativePoly),
encodingParams(ep),
encodedNativeVector(vp, Format::COEFFICIENT),
scalingFactor(1),
level(0),
depth(1) {}
PlaintextImpl(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep,
bool isEncoded = false)
: isEncoded(isEncoded),
typeFlag(IsDCRTPoly),
encodingParams(ep),
encodedVector(vp, Format::COEFFICIENT),
encodedVectorDCRT(vp, Format::COEFFICIENT),
scalingFactor(1),
level(0),
depth(1) {}
PlaintextImpl(const PlaintextImpl& rhs)
: isEncoded(rhs.isEncoded),
typeFlag(rhs.typeFlag),
encodingParams(rhs.encodingParams),
encodedVector(rhs.encodedVector),
encodedVectorDCRT(rhs.encodedVectorDCRT),
scalingFactor(rhs.scalingFactor),
level(rhs.level),
depth(rhs.depth) {}
PlaintextImpl(const PlaintextImpl&& rhs)
: isEncoded(rhs.isEncoded),
typeFlag(rhs.typeFlag),
encodingParams(std::move(rhs.encodingParams)),
encodedVector(std::move(rhs.encodedVector)),
encodedVectorDCRT(std::move(rhs.encodedVectorDCRT)),
scalingFactor(rhs.scalingFactor),
level(rhs.level),
depth(rhs.depth) {}
virtual ~PlaintextImpl() {}
/**
* GetEncodingType
* @return Encoding type used by this plaintext
*/
virtual PlaintextEncodings GetEncodingType() const = 0;
/**
* Get the scaling factor of the plaintext.
*/
double GetScalingFactor() const { return scalingFactor; }
/**
* Set the scaling factor of the plaintext.
*/
void SetScalingFactor(double sf) { scalingFactor = sf; }
/**
* IsEncoded
* @return true when encoding is done
*/
bool IsEncoded() const { return isEncoded; }
/**
* GetEncodingParams
* @return Encoding params used with this plaintext
*/
const EncodingParams GetEncodingParams() const { return encodingParams; }
/**
* Encode the plaintext into a polynomial
* @return true on success
*/
virtual bool Encode() = 0;
/**
* Decode the polynomial into the plaintext
* @return
*/
virtual bool Decode() = 0;
/**
* Calculate and return lower bound that can be encoded with the plaintext
* modulus the number to encode MUST be greater than this value
* @return floor(-p/2)
*/
int64_t LowBound() const {
uint64_t half = GetEncodingParams()->GetPlaintextModulus() >> 1;
bool odd = (GetEncodingParams()->GetPlaintextModulus() & 0x1) == 1;
int64_t bound = -1 * half;
if (odd) bound--;
return bound;
}
/**
* Calculate and return upper bound that can be encoded with the plaintext
* modulus the number to encode MUST be less than or equal to this value
* @return floor(p/2)
*/
int64_t HighBound() const {
return GetEncodingParams()->GetPlaintextModulus() >> 1;
}
/**
* SetFormat - allows format to be changed for PlaintextImpl evaluations
*
* @param fmt
*/
void SetFormat(Format fmt) const {
if (typeFlag == IsPoly)
encodedVector.SetFormat(fmt);
else if (typeFlag == IsNativePoly)
encodedNativeVector.SetFormat(fmt);
else
encodedVectorDCRT.SetFormat(fmt);
}
/**
* GetElement
* @return the Polynomial that the element was encoded into
*/
template <typename Element>
Element& GetElement();
template <typename Element>
const Element& GetElement() const;
/**
* GetElementRingDimension
* @return ring dimension on the underlying element
*/
usint GetElementRingDimension() const {
return typeFlag == IsPoly ? encodedVector.GetRingDimension()
: (typeFlag == IsNativePoly
? encodedNativeVector.GetRingDimension()
: encodedVectorDCRT.GetRingDimension());
}
/**
* GetElementModulus
* @return modulus on the underlying elemenbt
*/
const BigInteger GetElementModulus() const {
return typeFlag == IsPoly
? encodedVector.GetModulus()
: (typeFlag == IsNativePoly
? BigInteger(encodedNativeVector.GetModulus())
: encodedVectorDCRT.GetModulus());
}
/**
* Get method to return the length of plaintext
*
* @return the length of the plaintext in terms of the number of bits.
*/
virtual size_t GetLength() const = 0;
/**
* resize the plaintext; only works for plaintexts that support a resizable
* vector (coefpacked)
* @param newSize
*/
virtual void SetLength(size_t newSize) {
PALISADE_THROW(not_implemented_error, "resize not supported");
}
/*
* Method to get the depth of a plaintext.
*
* @return the depth of the plaintext
*/
size_t GetDepth() const { return depth; }
/*
* Method to set the depth of a plaintext.
*/
void SetDepth(size_t d) { depth = d; }
/*
* Method to get the level of a plaintext.
*
* @return the level of the plaintext
*/
size_t GetLevel() const { return level; }
/*
* Method to set the level of a plaintext.
*/
void SetLevel(size_t l) { level = l; }
virtual double GetLogError() const {
PALISADE_THROW(not_available_error,
"no estimate of noise available for the current scheme");
}
virtual double GetLogPrecision() const {
PALISADE_THROW(not_available_error,
"no estimate of precision available for the current scheme");
}
virtual const std::string& GetStringValue() const {
PALISADE_THROW(type_error, "not a string");
}
virtual const vector<int64_t>& GetCoefPackedValue() const {
PALISADE_THROW(type_error, "not a packed coefficient vector");
}
virtual const vector<int64_t>& GetPackedValue() const {
PALISADE_THROW(type_error, "not a packed coefficient vector");
}
virtual const std::vector<std::complex<double>>& GetCKKSPackedValue() const {
PALISADE_THROW(type_error, "not a packed vector of complex numbers");
}
virtual const std::vector<double> GetRealPackedValue() const {
PALISADE_THROW(type_error, "not a packed vector of real numbers");
}
virtual void SetStringValue(const std::string&) {
PALISADE_THROW(type_error, "does not support a string");
}
virtual void SetIntVectorValue(const vector<int64_t>&) {
PALISADE_THROW(type_error, "does not support an int vector");
}
/**
* Method to compare two plaintext to test for equivalence.
* This method is called by operator==
*
* @param other - the other plaintext to compare to.
* @return whether the two plaintext are equivalent.
*/
virtual bool CompareTo(const PlaintextImpl& other) const = 0;
/**
* operator== for plaintexts. This method makes sure the plaintexts are of
* the same type.
*
* @param other - the other plaintext to compare to.
* @return whether the two plaintext are the same.
*/
bool operator==(const PlaintextImpl& other) const { return CompareTo(other); }
bool operator!=(const PlaintextImpl& other) const {
return !(*this == other);
}
/**
* operator<< for ostream integration - calls PrintValue
* @param out
* @param item
* @return
*/
friend std::ostream& operator<<(std::ostream& out, const PlaintextImpl& item);
/**
* PrintValue is called by operator<<
* @param out
*/
virtual void PrintValue(std::ostream& out) const = 0;
};
inline std::ostream& operator<<(std::ostream& out, const PlaintextImpl& item) {
item.PrintValue(out);
return out;
}
inline std::ostream& operator<<(std::ostream& out, const Plaintext item) {
item->PrintValue(out);
return out;
}
inline bool operator==(const Plaintext p1, const Plaintext p2) {
return *p1 == *p2;
}
inline bool operator!=(const Plaintext p1, const Plaintext p2) {
return *p1 != *p2;
}
/**
* GetElement
* @return the Polynomial that the element was encoded into
*/
template <>
inline const Poly& PlaintextImpl::GetElement<Poly>() const {
return encodedVector;
}
template <>
inline Poly& PlaintextImpl::GetElement<Poly>() {
return encodedVector;
}
/**
* GetElement
* @return the NativePolynomial that the element was encoded into
*/
template <>
inline const NativePoly& PlaintextImpl::GetElement<NativePoly>() const {
return encodedNativeVector;
}
template <>
inline NativePoly& PlaintextImpl::GetElement<NativePoly>() {
return encodedNativeVector;
}
/**
* GetElement
* @return the DCRTPolynomial that the element was encoded into
*/
template <>
inline const DCRTPoly& PlaintextImpl::GetElement<DCRTPoly>() const {
return encodedVectorDCRT;
}
template <>
inline DCRTPoly& PlaintextImpl::GetElement<DCRTPoly>() {
return encodedVectorDCRT;
}
} // namespace lbcrypto
#endif
\core\include\encoding\stringencoding.h
Represents and defines string-encoded plaintext objects in Palisade.
#ifndef SRC_CORE_LIB_ENCODING_STRINGENCODING_H_
#define SRC_CORE_LIB_ENCODING_STRINGENCODING_H_
#include <memory>
#include <string>
#include "encoding/plaintext.h"
using std::string;
namespace lbcrypto {
class StringEncoding : public PlaintextImpl {
string ptx;
// enum EncodingType { CHAR7bit } encoding = CHAR7bit;
public:
// these three constructors are used inside of Decrypt
StringEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
StringEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
StringEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
StringEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep, string str)
: PlaintextImpl(vp, ep), ptx(str) {}
StringEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep,
string str)
: PlaintextImpl(vp, ep), ptx(str) {}
StringEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep, string str)
: PlaintextImpl(vp, ep), ptx(str) {}
// TODO provide wide-character version (for unicode); right now this class
// only supports strings of 7-bit ASCII characters
virtual ~StringEncoding() {}
/**
* GetStringValue
* @return the un-encoded string
*/
const string& GetStringValue() const { return ptx; }
/**
* SetStringValue
* @param val to initialize the Plaintext
*/
void SetStringValue(const std::string& value) { ptx = value; }
/**
* Encode the plaintext into the Poly
* @return true on success
*/
bool Encode();
/**
* Decode the Poly into the string
* @return true on success
*/
bool Decode();
/**
* GetEncodingType
* @return this is a String encoding
*/
PlaintextEncodings GetEncodingType() const { return String; }
/**
* Get length of the plaintext
*
* @return number of elements in this plaintext
*/
size_t GetLength() const { return ptx.size(); }
/**
* Method to compare two plaintext to test for equivalence
* Testing that the plaintexts are of the same type done in operator==
*
* @param other - the other plaintext to compare to.
* @return whether the two plaintext are equivalent.
*/
bool CompareTo(const PlaintextImpl& other) const {
const auto& oth = static_cast<const StringEncoding&>(other);
return oth.ptx == this->ptx;
}
/**
* PrintValue - used by operator<< for this object
* @param out
*/
void PrintValue(std::ostream& out) const { out << ptx; }
};
} /* namespace lbcrypto */
#endif /* SRC_CORE_LIB_ENCODING_STRINGENCODING_H_ */
\core\include\encoding\packedencoding.h
Represents and defines plaintext encodings in Palisade with packing capabilities.
#ifndef LBCRYPTO_UTILS_PACKEDEXTENCODING_H
#define LBCRYPTO_UTILS_PACKEDEXTENCODING_H
#include <functional>
#include <initializer_list>
#include <map>
#include <memory>
#include <numeric>
#include <utility>
#include <vector>
#include "encoding/encodingparams.h"
#include "encoding/plaintext.h"
#include "utils/inttypes.h"
namespace lbcrypto {
// STL pair used as a key for some tables in PackedEncoding
using ModulusM = std::pair<NativeInteger, uint64_t>;
/**
* @class PackedEncoding
* @brief Type used for representing IntArray types.
* Provides conversion functions to encode and decode plaintext data as type
* vector<int64_t>. This class uses bit packing techniques to enable efficient
* computing on vectors of integers. It is NOT supported for DCRTPoly
*/
class PackedEncoding : public PlaintextImpl {
vector<int64_t> value;
public:
// these two constructors are used inside of Decrypt
PackedEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
PackedEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
PackedEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
PackedEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep,
vector<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
PackedEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep,
vector<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
PackedEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep,
vector<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
PackedEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep,
std::initializer_list<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
PackedEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep,
std::initializer_list<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
PackedEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep,
std::initializer_list<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
/**
* @brief Constructs a container with a copy of each of the elements in rhs,
* in the same order.
* @param rhs - The input object to copy.
*/
explicit PackedEncoding(const std::vector<int64_t> &rhs)
: PlaintextImpl(shared_ptr<Poly::Params>(0), nullptr), value(rhs) {}
/**
* @brief Constructs a container with a copy of each of the elements in il, in
* the same order.
* @param arr the list to copy.
*/
PackedEncoding(std::initializer_list<int64_t> arr)
: PlaintextImpl(shared_ptr<Poly::Params>(0), nullptr), value(arr) {}
/**
* @brief Default empty constructor with empty uninitialized data elements.
*/
PackedEncoding()
: PlaintextImpl(shared_ptr<Poly::Params>(0), nullptr), value() {}
static usint GetAutomorphismGenerator(usint m) {
return m_automorphismGenerator[m];
}
bool Encode();
bool Decode();
const vector<int64_t> &GetPackedValue() const { return value; }
/**
* SetIntVectorValue
* @param val integer vector to initialize the plaintext
*/
void SetIntVectorValue(const vector<int64_t> &val) { value = val; }
/**
* GetEncodingType
* @return this is a Packed encoding
*/
PlaintextEncodings GetEncodingType() const { return Packed; }
/**
* Get method to return the length of plaintext
*
* @return the length of the plaintext in terms of the number of bits.
*/
size_t GetLength() const { return value.size(); }
/**
* @brief Method to set encoding params
* @param m the encoding cyclotomic order.
* @params params data structure storing encoding parameters
*/
static void SetParams(usint m, EncodingParams params);
/**
* @brief Method to set encoding params (this method should eventually be
* replaced by void SetParams(usint m, EncodingParams params);)
* @param m the encoding cyclotomic order.
* @params modulus is the plaintext modulus
*/
static void SetParams(usint m, const PlaintextModulus &modulus)
__attribute__((deprecated("use SetParams(usint m, EncodingParams p)")));
/**
* SetLength of the plaintext to the given size
* @param siz
*/
void SetLength(size_t siz) { value.resize(siz); }
/**
* Method to compare two plaintext to test for equivalence. This method does
* not test that the plaintext are of the same type.
*
* @param other - the other plaintext to compare to.
* @return whether the two plaintext are equivalent.
*/
bool CompareTo(const PlaintextImpl &other) const {
const auto &rv = static_cast<const PackedEncoding &>(other);
return this->value == rv.value;
}
/**
* @brief Destructor method.
*/
static void Destroy();
void PrintValue(std::ostream &out) const {
// for sanity's sake, trailing zeros get elided into "..."
out << "(";
size_t i = value.size();
while (--i > 0)
if (value[i] != 0) break;
for (size_t j = 0; j <= i; j++) out << ' ' << value[j];
out << " ... )";
}
private:
// initial root of unity for plaintext space
static std::map<ModulusM, NativeInteger> m_initRoot;
// modulus and root of unity to be used for Arbitrary CRT
static std::map<ModulusM, NativeInteger> m_bigModulus;
static std::map<ModulusM, NativeInteger> m_bigRoot;
// stores the list of primitive roots used in packing.
static std::map<usint, usint> m_automorphismGenerator;
static std::map<usint, std::vector<usint>> m_toCRTPerm;
static std::map<usint, std::vector<usint>> m_fromCRTPerm;
static void SetParams_2n(usint m, const NativeInteger &modulusNI);
static void SetParams_2n(usint m, EncodingParams params);
/**
* @brief Packs the slot values into aggregate plaintext space.
*
* @param ring is the element containing slot values.
* @param modulus is the plaintext modulus used for packing.
*/
template <typename P>
void Pack(P *ring, const PlaintextModulus &modulus) const;
/**
* @brief Unpacks the data from aggregated plaintext to slot values.
*
* @param ring is the input polynomial ring in aggregate plaintext.
* @param modulus is the plaintext modulus used in packing operation.
*/
template <typename P>
void Unpack(P *ring, const PlaintextModulus &modulus) const;
};
} // namespace lbcrypto
#endif
\core\include\encoding\coefpackedencoding.h
Represents and defines packing integers of plaintext objects into polynomial coefficients in Palisade.
#ifndef SRC_CORE_LIB_ENCODING_COEFPACKEDENCODING_H_
#define SRC_CORE_LIB_ENCODING_COEFPACKEDENCODING_H_
#include <initializer_list>
#include <memory>
#include <vector>
#include "encoding/plaintext.h"
namespace lbcrypto {
class CoefPackedEncoding : public PlaintextImpl {
vector<int64_t> value;
public:
// these two constructors are used inside of Decrypt
CoefPackedEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
CoefPackedEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
CoefPackedEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {}
CoefPackedEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep,
vector<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
CoefPackedEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep,
vector<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
CoefPackedEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep,
vector<int64_t> coeffs)
: PlaintextImpl(vp, ep), value(coeffs) {}
virtual ~CoefPackedEncoding() {}
/**
* GetCoeffsValue
* @return the un-encoded scalar
*/
const vector<int64_t>& GetCoefPackedValue() const { return value; }
/**
* SetIntVectorValue
* @param val integer vector to initialize the plaintext
*/
void SetIntVectorValue(const vector<int64_t>& val) { value = val; }
/**
* Encode the plaintext into the Poly
* @return true on success
*/
bool Encode();
/**
* Decode the Poly into the string
* @return true on success
*/
bool Decode();
/**
* GetEncodingType
* @return this is a CoefPacked encoding
*/
PlaintextEncodings GetEncodingType() const { return CoefPacked; }
/**
* Get length of the plaintext
*
* @return number of elements in this plaintext
*/
size_t GetLength() const { return value.size(); }
/**
* SetLength of the plaintext to the given size
* @param siz
*/
void SetLength(size_t siz) { value.resize(siz); }
/**
* Method to compare two plaintext to test for equivalence
* Testing that the plaintexts are of the same type done in operator==
*
* @param other - the other plaintext to compare to.
* @return whether the two plaintext are equivalent.
*/
bool CompareTo(const PlaintextImpl& other) const {
const auto& oth = static_cast<const CoefPackedEncoding&>(other);
return oth.value == this->value;
}
/**
* PrintValue - used by operator<< for this object
* @param out
*/
void PrintValue(std::ostream& out) const {
// for sanity's sake, trailing zeros get elided into "..."
out << "(";
size_t i = value.size();
while (--i > 0)
if (value[i] != 0) break;
for (size_t j = 0; j <= i; j++) out << ' ' << value[j];
out << " ... )";
}
};
} /* namespace lbcrypto */
#endif /* SRC_CORE_LIB_ENCODING_COEFPACKEDENCODING_H_ */
\core\include\encoding\ckkspackedencoding.h
Type used for representing IntArray types. Provides conversion functions to encode and decode plaintext data as type vector <uint64_t>. This class uses bit packing techniques to enable efficient computing on vectors of integers. It is NOT supported for DCRTPoly.
RescalingTechnique
#ifndef LBCRYPTO_UTILS_CKKSPACKEDEXTENCODING_H
#define LBCRYPTO_UTILS_CKKSPACKEDEXTENCODING_H
#include <functional>
#include <initializer_list>
#include <memory>
#include <numeric>
#include <utility>
#include <vector>
#include "encoding/encodingparams.h"
#include "encoding/plaintext.h"
#include "utils/inttypes.h"
namespace lbcrypto {
enum RescalingTechnique { APPROXRESCALE, EXACTRESCALE, APPROXAUTO };
CKKSPackedEncoding类
// STL pair used as a key for some tables in CKKSPackedEncoding
using ModulusM = std::pair<NativeInteger, uint64_t>;
/**
* @class CKKSPackedEncoding
* @brief Type used for representing IntArray types.
* Provides conversion functions to encode and decode plaintext data as type
* vector<uint64_t>. This class uses bit packing techniques to enable efficient
* computing on vectors of integers. It is NOT supported for DCRTPoly
*/
class CKKSPackedEncoding : public PlaintextImpl {
public:
// these two constructors are used inside of Decrypt
CKKSPackedEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {
depth = 1;
m_logError = 0.0;
}
CKKSPackedEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {
depth = 1;
m_logError = 0.0;
}
CKKSPackedEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep)
: PlaintextImpl(vp, ep) {
depth = 1;
m_logError = 0.0;
}
CKKSPackedEncoding(shared_ptr<Poly::Params> vp, EncodingParams ep,
const std::vector<std::complex<double>> &coeffs,
size_t depth, uint32_t level, double scFact)
: PlaintextImpl(vp, ep), value(coeffs) {
this->depth = depth;
this->level = level;
this->scalingFactor = scFact;
m_logError = 0.0;
}
CKKSPackedEncoding(shared_ptr<NativePoly::Params> vp, EncodingParams ep,
const std::vector<std::complex<double>> &coeffs,
size_t depth, uint32_t level, double scFact)
: PlaintextImpl(vp, ep), value(coeffs) {
this->depth = depth;
this->level = level;
this->scalingFactor = scFact;
m_logError = 0.0;
}
/*
* @param depth depth of plaintext to create.
* @param level level of plaintext to create.
* @param scFact scaling factor of a plaintext of this level at depth 1.
*
*/
CKKSPackedEncoding(shared_ptr<DCRTPoly::Params> vp, EncodingParams ep,
const std::vector<std::complex<double>> &coeffs,
size_t depth, uint32_t level, double scFact)
: PlaintextImpl(vp, ep), value(coeffs) {
this->depth = depth;
this->level = level;
this->scalingFactor = scFact;
m_logError = 0.0;
}
/**
* @brief Constructs a container with a copy of each of the elements in rhs,
* in the same order.
* @param rhs - The input object to copy.
*/
explicit CKKSPackedEncoding(const std::vector<std::complex<double>> &rhs)
: PlaintextImpl(shared_ptr<Poly::Params>(0), nullptr), value(rhs) {
depth = 1;
m_logError = 0.0;
}
/**
* @brief Default empty constructor with empty uninitialized data elements.
*/
CKKSPackedEncoding()
: PlaintextImpl(shared_ptr<Poly::Params>(0), nullptr), value() {
depth = 1;
m_logError = 0.0;
}
CKKSPackedEncoding(const CKKSPackedEncoding &rhs)
: PlaintextImpl(rhs), value(rhs.value), m_logError(rhs.m_logError) {}
CKKSPackedEncoding(const CKKSPackedEncoding &&rhs)
: PlaintextImpl(rhs),
value(std::move(rhs.value)),
m_logError(rhs.m_logError) {}
bool Encode();
bool Decode() {
PALISADE_THROW(
not_available_error,
"CKKSPackedEncoding::Decode() is not implemented. "
"Use CKKSPackedEncoding::Decode(depth,scalingFactor,rstech) instead.");
}
bool Decode(size_t depth, double scalingFactor, RescalingTechnique rsTech);
const std::vector<std::complex<double>> &GetCKKSPackedValue() const {
return value;
}
const std::vector<double> GetRealPackedValue() const {
std::vector<double> realValue(value.size());
std::transform(value.begin(), value.end(), realValue.begin(),
[](std::complex<double> da) { return da.real(); });
return realValue;
}
/**
* Static utility method to multiply two numbers in CRT representation.
* CRT representation is stored in a vector of native integers, and each
* position corresponds to the remainder of the number against one of
* the moduli in mods.
*
* @param a is the first number in CRT representation.
* @param b is the second number in CRT representation.
* @return the product of the two numbers in CRT representation.
*/
static std::vector<DCRTPoly::Integer> CRTMult(
const std::vector<DCRTPoly::Integer> &a,
const std::vector<DCRTPoly::Integer> &b,
const std::vector<DCRTPoly::Integer> &mods);
/**
* GetEncodingType
* @return this is a Packed encoding
*/
PlaintextEncodings GetEncodingType() const { return CKKSPacked; }
/**
* Get method to return the length of plaintext
*
* @return the length of the plaintext in terms of the number of bits.
*/
size_t GetLength() const { return value.size(); }
/**
* Get method to return log2 of estimated standard deviation of approximation
* error
*/
double GetLogError() const { return m_logError; }
/**
* Get method to return log2 of estimated precision
*/
double GetLogPrecision() const {
return encodingParams->GetPlaintextModulus() - m_logError;
}
/**
* SetLength of the plaintext to the given size
* @param siz
*/
void SetLength(size_t siz) { value.resize(siz); }
/**
* Method to compare two plaintext to test for equivalence. This method does
* not test that the plaintext are of the same type.
*
* @param other - the other plaintext to compare to.
* @return whether the two plaintext are equivalent.
*/
bool CompareTo(const PlaintextImpl &other) const {
const auto &rv = static_cast<const CKKSPackedEncoding &>(other);
return this->value == rv.value;
}
/**
* @brief Destructor method.
*/
static void Destroy();
void PrintValue(std::ostream &out) const {
// for sanity's sake, trailing zeros get elided into "..."
// out.precision(15);
out << "(";
size_t i = value.size();
while (--i > 0)
if (value[i] != std::complex<double>(0, 0)) break;
for (size_t j = 0; j <= i; j++) {
out << value[j].real() << ", ";
}
out << " ... ); ";
out << "Estimated precision: "
<< encodingParams->GetPlaintextModulus() - m_logError << " bits"
<< std::endl;
}
private:
std::vector<std::complex<double>> value;
double m_logError;
protected:
/**
* Set modulus and recalculates the vector values to fit the modulus
*
* @param &vec input vector
* @param &bigValue big bound of the vector values.
* @param &modulus modulus to be set for vector.
*/
void FitToNativeVector(const std::vector<int64_t> &vec, int64_t bigBound,
NativeVector *nativeVec) const;
#if NATIVEINT == 128
/**
* Set modulus and recalculates the vector values to fit the modulus
*
* @param &vec input vector
* @param &bigValue big bound of the vector values.
* @param &modulus modulus to be set for vector.
*/
void FitToNativeVector(const std::vector<__int128> &vec, __int128 bigBound,
NativeVector *nativeVec) const;
constexpr __int128 Max128BitValue() const {
// 2^127-2^73-1 - max value that could be rounded to int128_t
return ((unsigned __int128)1 << 127) - ((unsigned __int128)1 << 73) -
(unsigned __int128)1;
}
inline bool is128BitOverflow(double d) const {
const double EPSILON = 0.000001;
return EPSILON < (std::abs(d) - Max128BitValue());
}
#else // NATIVEINT == 64
constexpr int64_t Max64BitValue() const {
// 2^63-2^9-1 - max value that could be rounded to int64_t
return 9223372036854775295;
}
inline bool is64BitOverflow(double d) const {
const double EPSILON = 0.000001;
return EPSILON < (std::abs(d) - Max64BitValue());
}
#endif
};
} // namespace lbcrypto
#endif