Skip to content

Commit

Permalink
Relic quiet mode, and use more specific exception objects
Browse files Browse the repository at this point in the history
  • Loading branch information
mariano54 committed Jun 27, 2019
1 parent ef18752 commit 08ef32a
Show file tree
Hide file tree
Showing 15 changed files with 99 additions and 61 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ set(EP_SUPER "off" CACHE STRING "")
# Disable relic tests and benchmarks
set(TESTS 0 CACHE INTEGER "")
set(BENCH 0 CACHE INTEGER "")
set(QUIET 1 CACHE INTEGER "")

set(PP_EXT "LAZYR" CACHE STRING "")
set(PP_METHD "LAZYR;OATEP" CACHE STRING "")
Expand Down
31 changes: 24 additions & 7 deletions python-bindings/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,14 +336,31 @@ def test_vectors4():
assert(agg_sig.serialize() == bytes.fromhex("c37077684e735e62e3f1fd17772a236b4115d4b581387733d3b97cab08b90918c7e91c23380c93e54be345544026f93505d41e6000392b82ab3c8af1b2e3954b0ef3f62c52fc89f99e646ff546881120396c449856428e672178e5e0e14ec894"))
assert(agg_sig.verify(message_hashes, pks))

def no_throw_bad_sig():
private_key = ExtendedPrivateKey.from_seed(b"foo").get_private_key()

test1()
test2()
test_threshold()
test_vectors()
test_vectors2()
test_vectors3()
test_vectors4()
message_hash = bytes([9] * 32)

sig = private_key.sign_prepend_prehashed(message_hash).serialize()
sig = sig[:-1] + bytes([0])

public_key = private_key.get_public_key()

try:
bad_signature = PrependSignature.from_bytes(sig)
except ValueError:
return
assert(False)


# test1()
# test2()
# test_threshold()
# test_vectors()
# test_vectors2()
# test_vectors3()
# test_vectors4()
no_throw_bad_sig()

print("\nAll tests passed.")

Expand Down
21 changes: 15 additions & 6 deletions python-impl/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,23 @@ def __pow__(self, other):
return Fq(self.Q, 1)
elif other == 1:
return self
elif other % 2 == 0:
return (self * self) ** (other // 2)
else:
return (self * self) ** (other // 2) * self

el = self
multiply = []
while other > 1:
if other % 2 == 1:
multiply.append(el)
el = el * el
other = other // 2

for m in multiply:
el *= m

return el

def qi_power(self, i):
return self

def __invert__(self):
"""
Extended euclidian algorithm for inversion.
Expand Down Expand Up @@ -163,7 +172,7 @@ def one(cls, Q):
@classmethod
def from_fq(cls, Q, fq):
return fq


class FieldExtBase(tuple):
"""
Expand Down
14 changes: 7 additions & 7 deletions python-impl/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from threshold import Threshold
from util import hash256

setrecursionlimit(10**6)
# setrecursionlimit(10**6)


def rand_scalar(ec=default_ec):
Expand Down Expand Up @@ -445,13 +445,13 @@ def test_threshold():
test_threshold_instance(T, 5)


test_threshold()
# test_threshold()
test_fields()
test_ec()
test_vectors()
test_vectors2()
test_vectors3()
test_vectors4()
# test_ec()
# test_vectors()
# test_vectors2()
# test_vectors3()
# test_vectors4()
test1()
test2()

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def build_extension(self, ext):

setup(
name='blspy',
version='0.1.8',
version='0.1.9',
author='Mariano Sorgente',
author_email='[email protected]',
description='BLS signatures in c++ (python bindings)',
Expand Down
5 changes: 2 additions & 3 deletions src/aggregationinfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ AggregationInfo AggregationInfo::FromVectors(
std::vector<bn_t*> const &exponents) {
if (pubKeys.size() != messageHashes.size() || messageHashes.size() !=
exponents.size()) {
throw std::string(("Invalid input, all std::vectors must have\
the same length"));
throw std::length_error("Invalid input, all std::vectors must have the same length");
}
AggregationInfo::AggregationTree tree;
for (size_t i = 0; i < pubKeys.size(); i++) {
Expand Down Expand Up @@ -133,7 +132,7 @@ AggregationInfo::AggregationInfo(const AggregationInfo& info) {
void AggregationInfo::RemoveEntries(std::vector<uint8_t*> const &messages,
std::vector<PublicKey> const &pubKeys) {
if (messages.size() != pubKeys.size()) {
throw std::string("Invalid entries");
throw std::length_error("Invalid entries");
}
// Erase the keys from the tree
for (size_t i = 0; i < messages.size(); i++) {
Expand Down
10 changes: 10 additions & 0 deletions src/bls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,14 @@ void BLS::CheckRelicErrors() {
throw std::string("Relic library error");
}
}

void BLS::CheckRelicErrorsInvalidArgument() {
if (!core_get()) {
throw std::string("Library not initialized properly. Call BLS::Init()");
}
if (core_get()->code != STS_OK) {
core_get()->code = STS_OK;
throw std::invalid_argument("Relic library error");
}
}
} // end namespace bls
2 changes: 2 additions & 0 deletions src/bls.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include <vector>
#include <map>
#include <string>
#include <stdexcept>

#include "relic_conf.h"

Expand Down Expand Up @@ -62,6 +63,7 @@ class BLS {
static PublicKey DHKeyExchange(const PrivateKey& privKey, const PublicKey& pubKey);

static void CheckRelicErrors();
static void CheckRelicErrorsInvalidArgument();
};
} // end namespace bls

Expand Down
2 changes: 1 addition & 1 deletion src/extendedprivatekey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ ExtendedPrivateKey ExtendedPrivateKey::FromBytes(const uint8_t* serialized) {

ExtendedPrivateKey ExtendedPrivateKey::PrivateChild(uint32_t i) const {
if (depth >= 255) {
throw std::string("Cannot go further than 255 levels");
throw std::logic_error("Cannot go further than 255 levels");
}
// Hardened keys have i >= 2^31. Non-hardened have i < 2^31
uint32_t cmp = (1 << 31);
Expand Down
4 changes: 2 additions & 2 deletions src/extendedpublickey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ ExtendedPublicKey ExtendedPublicKey::PublicChild(uint32_t i) const {
// Hardened children have i >= 2^31. Non-hardened have i < 2^31
uint32_t cmp = (1 << 31);
if (i >= cmp) {
throw std::string("Cannot derive hardened children from public key");
throw std::invalid_argument("Cannot derive hardened children from public key");
}
if (depth >= 255) {
throw std::string("Cannot go further than 255 levels");
throw std::logic_error("Cannot go further than 255 levels");
}
uint8_t ILeft[PrivateKey::PRIVATE_KEY_SIZE];
uint8_t IRight[ChainCode::CHAIN_CODE_SIZE];
Expand Down
10 changes: 5 additions & 5 deletions src/privatekey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ PrivateKey PrivateKey::FromBytes(const uint8_t* bytes, bool modOrder) {
bn_mod_basic(*k.keydata, *k.keydata, ord);
} else {
if (bn_cmp(*k.keydata, ord) > 0) {
throw std::string("Key data too large, must be smaller than group order");
throw std::invalid_argument("Key data too large, must be smaller than group order");
}
}
return k;
Expand Down Expand Up @@ -101,7 +101,7 @@ PublicKey PrivateKey::GetPublicKey() const {

PrivateKey PrivateKey::AggregateInsecure(std::vector<PrivateKey> const& privateKeys) {
if (privateKeys.empty()) {
throw std::string("Number of private keys must be at least 1");
throw std::length_error("Number of private keys must be at least 1");
}

bn_t order;
Expand All @@ -117,12 +117,12 @@ PrivateKey PrivateKey::AggregateInsecure(std::vector<PrivateKey> const& privateK
}

PrivateKey PrivateKey::Aggregate(std::vector<PrivateKey> const& privateKeys,
std::vector<PublicKey> const& pubKeys) {
std::vector<PublicKey> const& pubKeys) {
if (pubKeys.size() != privateKeys.size()) {
throw std::string("Number of public keys must equal number of private keys");
throw std::length_error("Number of public keys must equal number of private keys");
}
if (privateKeys.empty()) {
throw std::string("Number of keys must be at least 1");
throw std::length_error("Number of keys must be at least 1");
}

std::vector<uint8_t*> serPubKeys(pubKeys.size());
Expand Down
6 changes: 3 additions & 3 deletions src/publickey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ PublicKey PublicKey::FromBytes(const uint8_t * key) {
uncompressed[0] = 0x02; // Insert extra byte for Y=0
}
g1_read_bin(pk.q, uncompressed, PUBLIC_KEY_SIZE + 1);
BLS::CheckRelicErrors();
BLS::CheckRelicErrorsInvalidArgument();
return pk;
}

Expand All @@ -52,7 +52,7 @@ PublicKey::PublicKey(const PublicKey &pubKey) {

PublicKey PublicKey::AggregateInsecure(std::vector<PublicKey> const& pubKeys) {
if (pubKeys.empty()) {
throw std::string("Number of public keys must be at least 1");
throw std::length_error("Number of public keys must be at least 1");
}

PublicKey ret = pubKeys[0];
Expand All @@ -64,7 +64,7 @@ PublicKey PublicKey::AggregateInsecure(std::vector<PublicKey> const& pubKeys) {

PublicKey PublicKey::Aggregate(std::vector<PublicKey> const& pubKeys) {
if (pubKeys.size() < 1) {
throw std::string("Number of public keys must be at least 1");
throw std::length_error("Number of public keys must be at least 1");
}

std::vector<uint8_t*> serPubKeys(pubKeys.size());
Expand Down
34 changes: 17 additions & 17 deletions src/signature.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ InsecureSignature InsecureSignature::FromBytes(const uint8_t *data) {
uncompressed[0] = 0x02; // Insert extra byte for Y=0
}
g2_read_bin(sigObj.sig, uncompressed, SIGNATURE_SIZE + 1);
BLS::CheckRelicErrors();
BLS::CheckRelicErrorsInvalidArgument();
return sigObj;
}

Expand All @@ -54,7 +54,7 @@ InsecureSignature::InsecureSignature(const InsecureSignature &signature) {
bool InsecureSignature::Verify(const std::vector<const uint8_t*>& hashes,
const std::vector<PublicKey>& pubKeys) const {
if (hashes.size() != pubKeys.size() || hashes.empty()) {
throw std::string("hashes and pubKeys vectors must be of same size and non-empty");
throw std::invalid_argument("hashes and pubKeys vectors must be of same size and non-empty");
}

g1_t *pubKeysNative = new g1_t[hashes.size() + 1];
Expand Down Expand Up @@ -107,7 +107,7 @@ bool InsecureSignature::VerifyNative(

InsecureSignature InsecureSignature::Aggregate(const std::vector<InsecureSignature>& sigs) {
if (sigs.empty()) {
throw std::string("sigs must not be empty");
throw std::length_error("sigs must not be empty");
}
InsecureSignature result = sigs[0];
for (size_t i = 1; i < sigs.size(); i++) {
Expand Down Expand Up @@ -182,7 +182,7 @@ Signature Signature::FromBytes(const uint8_t* data) {

Signature Signature::FromBytes(const uint8_t *data, const AggregationInfo &info) {
if ((data[0] & 0x40) > 0) {
throw std::string("Invalid signature. Second bit is set, so it's a PrependSignature.");
throw std::invalid_argument("Invalid signature. Second bit is set, so it's a PrependSignature.");
}

Signature ret = FromBytes(data);
Expand Down Expand Up @@ -343,12 +343,12 @@ Signature Signature::Aggregate(
for (const Signature &sig : sigs) {
const AggregationInfo &info = *sig.GetAggregationInfo();
if (info.Empty()) {
throw std::string("Signature must include aggregation info.");
throw std::invalid_argument("Signature must include aggregation info.");
}
std::vector<PublicKey> infoPubKeys = info.GetPubKeys();
std::vector<uint8_t*> infoMessageHashes = info.GetMessageHashes();
if (infoPubKeys.size() < 1 || infoMessageHashes.size() < 1) {
throw std::string("AggregationInfo must have items");
throw std::length_error("AggregationInfo must have items");
}
pubKeys.push_back(infoPubKeys);
std::vector<uint8_t*> currMessageHashes;
Expand All @@ -362,11 +362,11 @@ Signature Signature::Aggregate(

if (sigs.size() != pubKeys.size()
|| pubKeys.size() != messageHashes.size()) {
throw std::string("Lengths of vectors must match.");
throw std::length_error("Lengths of vectors must match.");
}
for (size_t i = 0; i < messageHashes.size(); i++) {
if (pubKeys[i].size() != messageHashes[i].size()) {
throw std::string("Lengths of vectors must match.");
throw std::length_error("Lengths of vectors must match.");
}
}
Signature ret = AggregateSigsInternal(sigs, pubKeys, messageHashes);
Expand All @@ -384,7 +384,7 @@ Signature Signature::AggregateSigsSecure(
std::vector<uint8_t*> const &messageHashes) {
if (sigs.size() != pubKeys.size() || sigs.size() != messageHashes.size()
|| sigs.size() < 1) {
throw std::string("Must have atleast one signature, key, and message");
throw std::invalid_argument("Must have atleast one signature, key, and message");
}

// Sort the public keys and signature by message + public key
Expand Down Expand Up @@ -441,11 +441,11 @@ Signature Signature::AggregateSigsInternal(
std::vector<std::vector<uint8_t*> > const &messageHashes) {
if (sigs.size() != pubKeys.size()
|| pubKeys.size() != messageHashes.size()) {
throw std::string("Lengths of std::vectors must match.");
throw std::length_error("Lengths of std::vectors must match.");
}
for (size_t i = 0; i < messageHashes.size(); i++) {
if (pubKeys[i].size() != messageHashes[i].size()) {
throw std::string("Lengths of std::vectors must match.");
throw std::length_error("Lengths of std::vectors must match.");
}
}

Expand Down Expand Up @@ -593,7 +593,7 @@ Signature Signature::AggregateSigsInternal(

Signature Signature::AggregateSigsSimple(std::vector<Signature> const &sigs) {
if (sigs.size() < 1) {
throw std::string("Must have atleast one signatures and key");
throw std::length_error("Must have atleast one signatures and key");
}
if (sigs.size() == 1) {
return sigs[0];
Expand Down Expand Up @@ -626,7 +626,7 @@ Signature Signature::DivideBy(std::vector<Signature> const &divisorSigs) const {
std::vector<uint8_t*> messageHashes = divisorSig.GetAggregationInfo()
->GetMessageHashes();
if (pks.size() != messageHashes.size()) {
throw string("Invalid aggregation info.");
throw std::length_error("Invalid aggregation info.");
}
bn_t quotient;
for (size_t i = 0; i < pks.size(); i++) {
Expand All @@ -641,7 +641,7 @@ Signature Signature::DivideBy(std::vector<Signature> const &divisorSigs) const {
aggregationInfo.GetExponent(&dividend, messageHashes[i],
pks[i]);
} catch (std::out_of_range e) {
throw string("Signature is not a subset.");
throw std::logic_error("Signature is not a subset.");
}

bn_t inverted;
Expand All @@ -656,8 +656,8 @@ Signature Signature::DivideBy(std::vector<Signature> const &divisorSigs) const {
bn_mod(newQuotient, newQuotient, ord);

if (bn_cmp(quotient, newQuotient) != CMP_EQ) {
throw string("Cannot divide by aggregate signature,"
"msg/pk pairs are not unique");
throw std::logic_error("Cannot divide by aggregate signature,"
"msg/pk pairs are not unique");
}
}
messageHashesToRemove.push_back(messageHashes[i]);
Expand All @@ -678,7 +678,7 @@ Signature Signature::DivideBy(std::vector<Signature> const &divisorSigs) const {
PrependSignature PrependSignature::FromBytes(const uint8_t *data) {
PrependSignature result;
if ((data[0] & 0x40) == 0) {
throw std::string("Invalid prepend signature. Second bit must be set to two");
throw std::invalid_argument("Invalid prepend signature. Second bit must be set to two");
}
uint8_t new_data[PrependSignature::SIGNATURE_SIZE];
memcpy(new_data, data, SIGNATURE_SIZE);
Expand Down
Loading

0 comments on commit 08ef32a

Please sign in to comment.