Skip to content

Commit

Permalink
Implement CBLSLazySignature for lazy serialization/deserialization
Browse files Browse the repository at this point in the history
In some cases it takes too much time to perform full deserialization of
BLS signatures in the message handler thread. Better to just read the
buffer and do the actual deserialization when the signature is needed for
the first time (which is can be in another thread).
  • Loading branch information
codablock committed Feb 15, 2019
1 parent 6e8f50a commit 02b6888
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/bls/bls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,34 @@ bool CBLSSignature::Recover(const std::vector<CBLSSignature>& sigs, const std::v
return true;
}

CBLSLazySignature::CBLSLazySignature(CBLSSignature& _sig) :
bufValid(false),
sigInitialized(true),
sig(_sig)
{

}

void CBLSLazySignature::SetSig(const CBLSSignature& _sig)
{
bufValid = false;
sigInitialized = true;
sig = _sig;
}

const CBLSSignature& CBLSLazySignature::GetSig() const
{
if (!bufValid && !sigInitialized) {
static CBLSSignature invalidSig;
return invalidSig;
}
if (!sigInitialized) {
sig.SetBuf(buf, sizeof(buf));
sigInitialized = true;
}
return sig;
}

#ifndef BUILD_BITCOIN_INTERNAL

static std::once_flag init_flag;
Expand Down
39 changes: 39 additions & 0 deletions src/bls/bls.h
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,45 @@ class CBLSSignature : public CBLSWrapper<bls::InsecureSignature, BLS_CURVE_SIG_S
bool InternalGetBuf(void* buf) const;
};

class CBLSLazySignature
{
private:
mutable char buf[BLS_CURVE_SIG_SIZE];
mutable bool bufValid{false};

mutable CBLSSignature sig;
mutable bool sigInitialized{false};

public:
template<typename Stream>
inline void Serialize(Stream& s) const
{
if (!sigInitialized && !bufValid) {
throw std::ios_base::failure("sig and buf not initialized");
}
if (!bufValid) {
sig.GetBuf(buf, sizeof(buf));
bufValid = true;
}
s.write(buf, sizeof(buf));
}

template<typename Stream>
inline void Unserialize(Stream& s)
{
s.read(buf, sizeof(buf));
bufValid = true;
sigInitialized = false;
}

public:
CBLSLazySignature() = default;
CBLSLazySignature(CBLSSignature& _sig);

void SetSig(const CBLSSignature& _sig);
const CBLSSignature& GetSig() const;
};

typedef std::vector<CBLSId> BLSIdVector;
typedef std::vector<CBLSPublicKey> BLSVerificationVector;
typedef std::vector<CBLSPublicKey> BLSPublicKeyVector;
Expand Down

0 comments on commit 02b6888

Please sign in to comment.