scipr-lab / libsnark

C++ library for zkSNARKs
Other
1.83k stars 583 forks source link

Serialization to file and Deserialization from file not working as expected #89

Closed petermunnings closed 7 years ago

petermunnings commented 7 years ago

Hi,

The << and >> operators are defined in libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp (line 212) as follows:

    friend std::ostream& operator<< <ppT>(std::ostream &out, const r1cs_ppzksnark_verification_key<ppT> &vk);
    friend std::istream& operator>> <ppT>(std::istream &in, r1cs_ppzksnark_verification_key<ppT> &vk);

I can write a verifier key to a file as follows:

    std::ofstream verifierKey("verifierKey", std::ifstream::binary);
    verifierKey << keypair.vk;

reading it back however doesn't appear to work:

    std::ifstream infile ("verifierKey",std::ifstream::binary);

    cout << "vk after" << endl;

    // get size of file
    infile.seekg (0,infile.end);
    long size = infile.tellg();
    infile.seekg (0);

    // allocate memory for file content
    char* buffer = new char[size];

    // read content of infile
    infile.read (buffer,size);
    infile >> keypair.vk;

    cout << keypair.vk << endl;

    // release dynamically-allocated memory
    delete[] buffer;

    infile.close();

I suspect I am missing something - please could you point me in the correct direction

thanks

petermunnings commented 7 years ago

The problem seems to be with the way I was reading the file back in. Using a stringstream works fine:

    stringstream verifierKey;
    verifierKey << keypair.vk;

    ofstream fileOut;
    fileOut.open("verifierKey");

    fileOut << verifierKey.rdbuf();
    fileOut.close();

    cout << "verifierKey before" << endl;
    cout << keypair.vk << endl;

    ifstream fileIn("verifierKey");
    stringstream verifierKeyFromFile;
    if (fileIn) {
       verifierKeyFromFile << fileIn.rdbuf();
       fileIn.close();
    }

    verifierKeyFromFile >> keypair.vk;

    cout << "verifierKey after" << endl;
    cout << keypair.vk << endl;