packedencoding.cpp 14.8 KB
Newer Older
Gerard Ryan's avatar
Gerard Ryan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/*
 * @file packedencoding.cpp Represents and defines plaintext encodings in Palisade with bit packing capabilities.
 * @author  TPOC: palisade@njit.edu
 *
 * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT)
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this
 * list of conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "packedencoding.h"

namespace lbcrypto {

std::map<ModulusM, NativeInteger> PackedEncoding::m_initRoot;
std::map<ModulusM, NativeInteger> PackedEncoding::m_bigModulus;
std::map<ModulusM, NativeInteger> PackedEncoding::m_bigRoot;

std::map<usint, usint> PackedEncoding::m_automorphismGenerator;
std::map<usint, std::vector<usint>> PackedEncoding::m_toCRTPerm;
std::map<usint, std::vector<usint>> PackedEncoding::m_fromCRTPerm;

bool PackedEncoding::Encode() {
	if( this->isEncoded ) return true;
	auto mod = this->encodingParams->GetPlaintextModulus();

Gerard Ryan's avatar
Gerard Ryan committed
43 44 45 46 47 48 49 50 51 52 53
	if (( this->typeFlag == IsNativePoly ) || (this->typeFlag == IsDCRTPoly )) {

		NativeVector temp;
		if ( this->typeFlag == IsNativePoly )
			temp = NativeVector(this->GetElementRingDimension(), this->GetElementModulus().ConvertToInt());
		else {
			NativeInteger q0 = this->encodedVectorDCRT.GetParams()->GetParams()[0]->GetModulus().ConvertToInt();
			temp = NativeVector(this->GetElementRingDimension(), q0);
			if( q0 < mod )
				throw std::logic_error("the plaintext modulus size is larger than the size of CRT moduli; either decrease the plaintext modulus or increase the CRT moduli.");
		}
Gerard Ryan's avatar
Gerard Ryan committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

		size_t i;
		for( i=0; i < value.size(); i++ ) {
			uint32_t entry = value[i];

			if( entry >= mod )
				throw std::logic_error("Cannot encode integer " + std::to_string(entry) +
						" at position " + std::to_string(i) +
						" that is > plaintext modulus " + std::to_string(mod) );

			temp[i] = NativeInteger(entry);
		}

		for(; i < this->GetElementRingDimension(); i++ )
			temp[i] = NativeInteger(0);
		this->isEncoded = true;

Gerard Ryan's avatar
Gerard Ryan committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
		if ( this->typeFlag == IsNativePoly ) {
			this->GetElement<NativePoly>().SetValues(temp, Format::EVALUATION); //the input plaintext data is in the evaluation format
			this->Pack(&this->GetElement<NativePoly>(), this->encodingParams->GetPlaintextModulus());//ilVector coefficients are packed and resulting ilVector is in COEFFICIENT form.
		}
		else
		{
			NativePoly firstElement = this->GetElement<DCRTPoly>().GetElementAtIndex(0);
			firstElement.SetValues(temp, Format::EVALUATION); //the input plaintext data is in the evaluation format
			this->Pack(&firstElement, this->encodingParams->GetPlaintextModulus());//ilVector coefficients are packed and resulting ilVector is in COEFFICIENT form.
			this->encodedVectorDCRT.SetElementAtIndex(0,firstElement);

			const shared_ptr<ILDCRTParams<BigInteger>> params = this->encodedVectorDCRT.GetParams();
			const std::vector<std::shared_ptr<ILNativeParams>> &nativeParams = params->GetParams();

			for (size_t i = 1; i < nativeParams.size(); i++ ) {
				NativePoly temp(firstElement);
Gerard Ryan's avatar
Gerard Ryan committed
87 88
				temp.SwitchModulus(nativeParams[i]->GetModulus(),nativeParams[i]->GetRootOfUnity(),
						nativeParams[i]->GetBigModulus(),nativeParams[i]->GetBigRootOfUnity());
Gerard Ryan's avatar
Gerard Ryan committed
89 90 91 92
				this->encodedVectorDCRT.SetElementAtIndex(i,temp);
			}

		}
Gerard Ryan's avatar
Gerard Ryan committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

	}
	else {
		BigVector temp(this->GetElementRingDimension(), BigInteger(this->GetElementModulus()));

		size_t i;
		for( i=0; i < value.size(); i++ ) {
			uint32_t entry = value[i];

			if( entry >= mod )
				throw std::logic_error("Cannot encode integer " + std::to_string(entry) +
						" at position " + std::to_string(i) +
						" that is > plaintext modulus " + std::to_string(mod) );

			temp[i] = BigInteger(entry);
		}

		for(; i < this->GetElementRingDimension(); i++ )
			temp[i] = BigInteger(0);
		this->isEncoded = true;

Gerard Ryan's avatar
Gerard Ryan committed
114
		this->GetElement<Poly>().SetValues(temp, Format::EVALUATION); //the input plaintext data is in the evaluation format
Gerard Ryan's avatar
Gerard Ryan committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

		this->Pack(&this->GetElement<Poly>(), this->encodingParams->GetPlaintextModulus());//ilVector coefficients are packed and resulting ilVector is in COEFFICIENT form.
	}

	return true;
}

template<typename T>
static void fillVec(const T& poly, vector<uint64_t>& vec) {
	vec.clear();
	for (size_t i = 0; i<poly.GetLength(); i++) {
		vec.push_back(poly[i].ConvertToInt());
	}
}

bool PackedEncoding::Decode() {

	auto ptm = this->encodingParams->GetPlaintextModulus();

Gerard Ryan's avatar
Gerard Ryan committed
134 135 136 137 138 139 140 141 142 143 144
	if (( this->typeFlag == IsNativePoly ) || (this->typeFlag == IsDCRTPoly )) {
		if ( this->typeFlag == IsNativePoly ) {
			this->Unpack(&this->GetElement<NativePoly>(), ptm);
			fillVec(this->encodedNativeVector, this->value);
		}
		else
		{
			NativePoly firstElement = this->GetElement<DCRTPoly>().GetElementAtIndex(0);
			this->Unpack(&firstElement, ptm);
			fillVec(firstElement, this->value);
		}
Gerard Ryan's avatar
Gerard Ryan committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
	}
	else {
		this->Unpack(&this->GetElement<Poly>(), ptm);
		fillVec(this->encodedVector, this->value);
	}

	return true;
}

void PackedEncoding::Destroy()
{
	m_initRoot.clear();
	m_bigModulus.clear();
	m_bigRoot.clear();

	m_automorphismGenerator.clear();
	m_toCRTPerm.clear();
	m_fromCRTPerm.clear();
}

void PackedEncoding::SetParams(usint m, EncodingParams params)
{
	NativeInteger modulusNI(params->GetPlaintextModulus()); //native int modulus
	std::string exception_message;
	bool hadEx = false;

	//initialize the CRT coefficients if not initialized
#pragma omp critical
	try {
		if (!(m & (m - 1))) { // Check if m is a power of 2
			SetParams_2n(m, params);
		}
		else {
			const ModulusM modulusM = {modulusNI,m};
			// Arbitrary: Bluestein based CRT Arb. So we need the 2mth root of unity
			if (params->GetPlaintextRootOfUnity() == 0) {
				NativeInteger initRoot = RootOfUnity<NativeInteger>(2 * m, modulusNI);
				m_initRoot[modulusM] = initRoot;
				params->SetPlaintextRootOfUnity(m_initRoot[modulusM].ConvertToInt());
			}
			else
				m_initRoot[modulusM] = params->GetPlaintextRootOfUnity();

			// Find a compatible big-modulus and root of unity for CRTArb
			if (params->GetPlaintextBigModulus() == 0) {
				usint nttDim = pow(2, ceil(log2(2 * m - 1)));
				if ((modulusNI.ConvertToInt() - 1) % nttDim == 0) {
					m_bigModulus[modulusM] = modulusNI;
				}
				else {
					usint bigModulusSize = ceil(log2(2 * m - 1)) + 2 * modulusNI.GetMSB() + 1;
					m_bigModulus[modulusM] = FirstPrime<NativeInteger>(bigModulusSize, nttDim);
				}
				m_bigRoot[modulusM] = RootOfUnity<NativeInteger>(nttDim, m_bigModulus[modulusM]);
				params->SetPlaintextBigModulus(m_bigModulus[modulusM]);
				params->SetPlaintextBigRootOfUnity(m_bigRoot[modulusM]);
			}
			else
			{
				m_bigModulus[modulusM] = params->GetPlaintextBigModulus();
				m_bigRoot[modulusM] = params->GetPlaintextBigRootOfUnity();
			}

			// Find a generator for the automorphism group
			if (params->GetPlaintextGenerator() == 0) {
				NativeInteger M(m); // Hackish typecast
				NativeInteger automorphismGenerator = FindGeneratorCyclic<NativeInteger>(M);
				m_automorphismGenerator[m] = automorphismGenerator.ConvertToInt();
				params->SetPlaintextGenerator(m_automorphismGenerator[m]);
			}
			else
				m_automorphismGenerator[m] = params->GetPlaintextGenerator();

			// Create the permutations that interchange the automorphism and crt ordering
			usint phim = GetTotient(m);
			auto tList = GetTotientList(m);
			auto tIdx = std::vector<usint>(m, -1);
			for(usint i=0; i<phim; i++){
				tIdx[tList[i]] = i;
			}

			m_toCRTPerm[m] = std::vector<usint>(phim);
			m_fromCRTPerm[m] = std::vector<usint>(phim);

			usint curr_index = 1;
			for (usint i=0; i<phim; i++){
				m_toCRTPerm[m][tIdx[curr_index]] = i;
				m_fromCRTPerm[m][i] = tIdx[curr_index];

				curr_index = curr_index*m_automorphismGenerator[m] % m;
			}
		}
	}
	catch( std::exception& e ) {
		exception_message = e.what();
		hadEx = true;
	}

	if( hadEx )
		throw std::logic_error(exception_message);
}

template<typename P>
void PackedEncoding::Pack(P *ring, const PlaintextModulus &modulus) const {

	bool dbg_flag = false;

	usint m = ring->GetCyclotomicOrder();//cyclotomic order
	NativeInteger modulusNI(modulus);//native int modulus

	const ModulusM modulusM = {modulusNI,m};

	//Do the precomputation if not initialized
	if (this->m_initRoot[modulusM].GetMSB() == 0) {
Gerard Ryan's avatar
Gerard Ryan committed
259
		SetParams(m, EncodingParams(new EncodingParamsImpl(modulus)));
Gerard Ryan's avatar
Gerard Ryan committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
	}

	usint phim = ring->GetRingDimension();

	DEBUG("Pack for order " << m << " phim " << phim << " modulus " << modulusNI);

	//copy values from ring to the vector
	NativeVector slotValues(phim, modulusNI);
	for (usint i = 0; i < phim; i++) {
		slotValues[i] = (*ring)[i].ConvertToInt();
	}

	DEBUG(*ring);
	DEBUG(slotValues);

	// Transform Eval to Coeff
	if (!(m & (m-1))) { // Check if m is a power of 2

		if (m_toCRTPerm[m].size() > 0)
		{
			// Permute to CRT Order
			NativeVector permutedSlots(phim, modulusNI);

			for (usint i = 0; i < phim; i++) {
				permutedSlots[i] = slotValues[m_toCRTPerm[m][i]];
			}
Gerard Ryan's avatar
Gerard Ryan committed
286
			ChineseRemainderTransformFTT<NativeVector>::InverseTransform(permutedSlots, m_initRoot[modulusM], m, &slotValues);
Gerard Ryan's avatar
Gerard Ryan committed
287 288 289
		}
		else
		{
Gerard Ryan's avatar
Gerard Ryan committed
290
			ChineseRemainderTransformFTT<NativeVector>::InverseTransform(slotValues, m_initRoot[modulusM], m, &slotValues);
Gerard Ryan's avatar
Gerard Ryan committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
		}

	} else { // Arbitrary cyclotomic

		// Permute to CRT Order
		NativeVector permutedSlots(phim, modulusNI);
		for (usint i = 0; i < phim; i++) {
			permutedSlots[i] = slotValues[m_toCRTPerm[m][i]];
		}

		DEBUG("permutedSlots " << permutedSlots);
		DEBUG("m_initRoot[modulusM] " << m_initRoot[modulusM]);
		DEBUG("m_bigModulus[modulusM] " << m_bigModulus[modulusM]);
		DEBUG("m_bigRoot[modulusM] " << m_bigRoot[modulusM]);

Gerard Ryan's avatar
Gerard Ryan committed
306
		slotValues = ChineseRemainderTransformArb<NativeVector>::
Gerard Ryan's avatar
Gerard Ryan committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
				InverseTransform(permutedSlots, m_initRoot[modulusM], m_bigModulus[modulusM], m_bigRoot[modulusM], m);
	}

	DEBUG("slotvalues now " << slotValues);
	//copy values into the slotValuesRing
	typename P::Vector slotValuesRing(phim, ring->GetModulus());
	for (usint i = 0; i < phim; i++) {
		slotValuesRing[i] = typename P::Integer(slotValues[i].ConvertToInt());
	}

	ring->SetValues(slotValuesRing, Format::COEFFICIENT);
	DEBUG(*ring);
}

template<typename P>
void PackedEncoding::Unpack(P *ring, const PlaintextModulus &modulus) const {

	bool dbg_flag = false;

	usint m = ring->GetCyclotomicOrder(); // cyclotomic order
	NativeInteger modulusNI(modulus); //native int modulus

	const ModulusM modulusM = {modulusNI,m};

	//Do the precomputation if not initialized
	if (this->m_initRoot[modulusM].GetMSB() == 0) {
Gerard Ryan's avatar
Gerard Ryan committed
333
		SetParams(m, EncodingParams(new EncodingParamsImpl(modulus)));
Gerard Ryan's avatar
Gerard Ryan committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
	}

	usint phim = ring->GetRingDimension(); //ring dimension

	DEBUG("Unpack for order " << m << " phim " << phim << " modulus " << modulusNI);

	//copy aggregate plaintext values
	NativeVector packedVector(phim, modulusNI);
	for (usint i = 0; i < phim; i++) {
		packedVector[i] = NativeInteger((*ring)[i].ConvertToInt());
	}

	DEBUG(packedVector);

	// Transform Coeff to Eval
	NativeVector permutedSlots(phim, modulusNI);
	if (!(m & (m-1))) { // Check if m is a power of 2
Gerard Ryan's avatar
Gerard Ryan committed
351
		ChineseRemainderTransformFTT<NativeVector>::ForwardTransform(packedVector, m_initRoot[modulusM], m, &permutedSlots);
Gerard Ryan's avatar
Gerard Ryan committed
352
	} else { // Arbitrary cyclotomic
Gerard Ryan's avatar
Gerard Ryan committed
353
		permutedSlots = ChineseRemainderTransformArb<NativeVector>::
Gerard Ryan's avatar
Gerard Ryan committed
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
				ForwardTransform(packedVector, m_initRoot[modulusM], m_bigModulus[modulusM], m_bigRoot[modulusM], m);
	}

	if (m_fromCRTPerm[m].size() > 0) {
		// Permute to automorphism Order
		for (usint i = 0; i < phim; i++) {
			packedVector[i] = permutedSlots[m_fromCRTPerm[m][i]];
		}
	}
	else
		packedVector = permutedSlots;

	DEBUG(packedVector);

	//copy values into the slotValuesRing
	typename P::Vector packedVectorRing(phim, ring->GetModulus());
	for (usint i = 0; i < phim; i++) {
		packedVectorRing[i] = typename P::Integer(packedVector[i].ConvertToInt());
	}

	ring->SetValues(packedVectorRing, Format::COEFFICIENT);
}

void PackedEncoding::SetParams_2n(usint m, const NativeInteger &modulusNI) {

	const ModulusM modulusM = {modulusNI,m};

	// Power of two: m/2-point FTT. So we need the mth root of unity
	m_initRoot[modulusM] = RootOfUnity<NativeInteger>(m, modulusNI);

	// Create the permutations that interchange the automorphism and crt ordering
	// First we create the cyclic group generated by 5 and then adjoin the co-factor by multiplying by 3

	usint phim = (m >> 1);
	usint phim_by_2 = (m >> 2);

	m_toCRTPerm[m] = std::vector<usint>(phim);
	m_fromCRTPerm[m] = std::vector<usint>(phim);

	usint curr_index = 1;
	for (usint i = 0; i < phim_by_2; i++) {
		m_toCRTPerm[m][(curr_index - 1) / 2] = i;
		m_fromCRTPerm[m][i] = (curr_index - 1) / 2;

Gerard Ryan's avatar
Gerard Ryan committed
398
		usint cofactor_index = curr_index * (m-1) % m;
Gerard Ryan's avatar
Gerard Ryan committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
		m_toCRTPerm[m][(cofactor_index - 1) / 2] = i + phim_by_2;
		m_fromCRTPerm[m][i + phim_by_2] = (cofactor_index - 1) / 2;

		curr_index = curr_index * 5 % m;

	}

}

void PackedEncoding::SetParams_2n(usint m, EncodingParams params){

		NativeInteger modulusNI(params->GetPlaintextModulus()); //native int modulus

		const ModulusM modulusM = {modulusNI,m};

		// Power of two: m/2-point FTT. So we need the mth root of unity
		if (params->GetPlaintextRootOfUnity() == 0)
		{
			m_initRoot[modulusM] = RootOfUnity<NativeInteger>(m, modulusNI);
			params->SetPlaintextRootOfUnity(m_initRoot[modulusM]);
		}
		else
			m_initRoot[modulusM] = params->GetPlaintextRootOfUnity();

		// Create the permutations that interchange the automorphism and crt ordering
		// First we create the cyclic group generated by 5 and then adjoin the co-factor by multiplying by 3

		usint phim = (m >> 1);
		usint phim_by_2 = (m >> 2);

		m_toCRTPerm[m] = std::vector<usint>(phim);
		m_fromCRTPerm[m] = std::vector<usint>(phim);

		usint curr_index = 1;
		for (usint i = 0; i < phim_by_2; i++) {
			m_toCRTPerm[m][(curr_index - 1) / 2] = i;
			m_fromCRTPerm[m][i] = (curr_index - 1) / 2;

Gerard Ryan's avatar
Gerard Ryan committed
437
			usint cofactor_index = curr_index * (m-1) % m;
Gerard Ryan's avatar
Gerard Ryan committed
438 439 440 441 442 443 444 445 446 447
			m_toCRTPerm[m][(cofactor_index - 1) / 2] = i + phim_by_2;
			m_fromCRTPerm[m][i + phim_by_2] = (cofactor_index - 1) / 2;

			curr_index = curr_index * 5 % m;

		}

	}

}