Skip to content

Commit

Permalink
python-bindings: Add pickle support for G1Element
Browse files Browse the repository at this point in the history
This is needed for plots caching in `chia-blockchain`.
  • Loading branch information
xdustinface committed Aug 11, 2021
1 parent ecf77cc commit 4740720
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
10 changes: 10 additions & 0 deletions python-bindings/pythonbindings.cpp
Expand Up @@ -373,6 +373,16 @@ PYBIND11_MODULE(blspy, m)
// PythonGIL release_lock;
return G1Element::FromBytes(Bytes(data_ptr, G1Element::SIZE));
})
.def(py::pickle(
[](const G1Element &dp) { // __getstate__
return py::make_tuple(dp.Serialize());
},
[](py::tuple t) { // __setstate__
if (t.size() != 1)
throw std::runtime_error("Invalid state!");
auto vecBytes = t[0].cast<std::vector<uint8_t>>();
return G1Element::FromByteVector(vecBytes);
}))
.def("generator", &G1Element::Generator)
.def("from_message", py::overload_cast<const std::vector<uint8_t>&, const uint8_t*, int>(&G1Element::FromMessage))
.def("pair", &G1Element::Pair)
Expand Down
19 changes: 19 additions & 0 deletions python-bindings/test.py
@@ -1,5 +1,6 @@
# flake8: noqa: E501
import binascii
import pickle
from copy import deepcopy

from blspy import (
Expand Down Expand Up @@ -335,11 +336,29 @@ def test_aggregate_verify_zero_items():
assert AugSchemeMPL.aggregate_verify([], [], G2Element())


def test_pickle_support():
seed = bytes([
0, 50, 6, 244, 24, 199, 1, 25, 52, 88, 192, 19, 18, 12, 89, 6,
220, 18, 102, 58, 209, 82, 12, 62, 89, 110, 182, 9, 44, 20, 254, 22
])
key: PrivateKey = AugSchemeMPL.key_gen(seed)
g1: G1Element = key.get_g1()
g1_data = pickle.dumps(g1)
g1_expected_data = bytes.fromhex("80049581000000000000008c05626c737079948c094731456c656d656e749493942981945d94284b"
"864b244b324b904bbb4bcb4bfd4b9a4be74b5b4bde4bce4b794b814b964b534b504b204b8e4bb54b"
"e94b9b4b044bd54bcd4b244be94b554bad4ba94b614bf84bc04ba14b624bde4be74b404bbe4b7b4b"
"dc4b6c4b3c4b064b134bba4b2e4bb1658594622e")
assert g1_data == g1_expected_data
g1_restored = pickle.loads(g1_data)
assert g1 == g1_restored


test_schemes()
test_vectors_invalid()
test_vectors_valid()
test_readme()
test_aggregate_verify_zero_items()
test_pickle_support()

print("\nAll tests passed.")

Expand Down

0 comments on commit 4740720

Please sign in to comment.