diff --git a/privacy/zsl/Makefile b/privacy/zsl/Makefile index 7d97f54..91f686a 100644 --- a/privacy/zsl/Makefile +++ b/privacy/zsl/Makefile @@ -8,10 +8,11 @@ all: #cd $(SUBDIR) && make g++ $(CXXFLAGS) -c utils/util.cpp -o utils/util.o g++ $(CXXFLAGS) -c utils/sha256.cpp -o utils/sha256.o + g++ $(CXXFLAGS) -c note.cpp -o note.o g++ $(CXXFLAGS) -c merkle_tree.cpp -o merkle_tree.o g++ $(CXXFLAGS) -c main.cpp -o main.o - g++ utils/util.o utils/sha256.o merkle_tree.o main.o -o zsltest $(CXXFLAGS) $(LDLIBS) + g++ utils/util.o utils/sha256.o note.o merkle_tree.o main.o -o zsltest $(CXXFLAGS) $(LDLIBS) clean: - rm -f utils/*.o *.o + rm -f utils/*.o *.o ./a.out ./zsltest #rm -f zsltest ./zsl/snark/libsnark.a diff --git a/privacy/zsl/api.hpp b/privacy/zsl/api.hpp index 48b3206..e1359d4 100644 --- a/privacy/zsl/api.hpp +++ b/privacy/zsl/api.hpp @@ -10,15 +10,17 @@ void zsl_prove_shielding( const std::string& pk, uint64_t value, std::string& output_proof - ) { - unsigned char rho_a[rho.size()/2]; - hex_str_to_array(rho, rho_a); - unsigned char pk_a[pk.size()/2]; - hex_str_to_array(pk, pk_a); - unsigned char proof[584]; + ) +{ + unsigned char rho_ptr[rho.size()/2]; + unsigned char pk_ptr[pk.size()/2]; + unsigned char proof_ptr[584]; + hex_str_to_array(rho, rho_ptr); + hex_str_to_array(pk, pk_ptr); - zsl_prove_shielding(rho_a, pk_a, value, proof); - output_proof = array_to_hex_str(proof, 584); + zsl_prove_shielding(rho_ptr, pk_ptr, value, proof_ptr); + + output_proof = array_to_hex_str(proof_ptr, 584); } bool zsl_verify_shielding( @@ -26,16 +28,18 @@ bool zsl_verify_shielding( const std::string& send_nf, const std::string& cm, uint64_t value - ) { + ) +{ - unsigned char proof_a[proof.size()/2]; - hex_str_to_array(proof, proof_a); - unsigned char send_nf_a[send_nf.size()/2]; - hex_str_to_array(send_nf, send_nf_a); - unsigned char cm_a[cm.size()/2]; - hex_str_to_array(cm, cm_a); - - return zsl_verify_shielding(proof_a, send_nf_a, cm_a, value); + unsigned char proof_ptr[proof.size()/2]; + unsigned char send_nf_ptr[send_nf.size()/2]; + unsigned char cm_ptr[cm.size()/2]; + + hex_str_to_array(proof, proof_ptr); + hex_str_to_array(send_nf, send_nf_ptr); + hex_str_to_array(cm, cm_ptr); + + return zsl_verify_shielding(proof_ptr, send_nf_ptr, cm_ptr, value); } void zsl_prove_unshielding( @@ -45,10 +49,12 @@ void zsl_prove_unshielding( uint64_t tree_position, std::vector& auth_path, std::string& output_proof - ) { + ) +{ unsigned char rho_a[rho.size()/2]; - hex_str_to_array(rho, rho_a); unsigned char sk_a[sk.size()/2]; + + hex_str_to_array(rho, rho_a); hex_str_to_array(sk, sk_a); unsigned char auth_path_a[29][32]; @@ -62,6 +68,7 @@ void zsl_prove_unshielding( unsigned char proof[584]; zsl_prove_unshielding(rho_a, sk_a, value, tree_position, auth_path_a, proof); + output_proof = array_to_hex_str(proof, 584); } @@ -70,16 +77,18 @@ bool zsl_verify_unshielding( const std::string& spend_nf, const std::string& root, uint64_t value - ) { + ) +{ - unsigned char proof_a[proof.size()/2]; - hex_str_to_array(proof, proof_a); - unsigned char spend_nf_a[spend_nf.size()/2]; - hex_str_to_array(spend_nf, spend_nf_a); - unsigned char root_a[root.size()/2]; - hex_str_to_array(root, root_a); - - return zsl_verify_unshielding(proof_a, spend_nf_a, root_a, value); + unsigned char proof_ptr[proof.size()/2]; + unsigned char spend_nf_ptr[spend_nf.size()/2]; + unsigned char root_ptr[root.size()/2]; + + hex_str_to_array(proof, proof_ptr); + hex_str_to_array(spend_nf, spend_nf_ptr); + hex_str_to_array(root, root_ptr); + + return zsl_verify_unshielding(proof_ptr, spend_nf_ptr, root_ptr, value); } void zsl_prove_transfer( @@ -128,8 +137,6 @@ void zsl_prove_transfer( for(int j = 0; j < 32; j++) { auth_path_ptr_1[i][j] = item[j]; } - print_char_array(auth_path_ptr_1[i], 32); - //std::cout << auth_path_1[i] << std::endl; } unsigned char auth_path_ptr_2[29][32]; @@ -139,11 +146,9 @@ void zsl_prove_transfer( for(int j = 0; j < 32; j++) { auth_path_ptr_2[i][j] = item[j]; } - print_char_array(auth_path_ptr_2[i], 32); - //std::cout << auth_path_2[i] << std::endl; } - std::cout << "input_rho_ptr_1:"; + /*std::cout << "input_rho_ptr_1:"; print_char_array(input_rho_ptr_1, 32); std::cout << "input_pk_ptr_1:"; print_char_array(input_pk_ptr_1, 32); @@ -164,11 +169,12 @@ void zsl_prove_transfer( std::cout << "output_value_1:" << output_value_1 << std::endl; std::cout << "output_value_2:" << output_value_2 << std::endl; std::cout << "input_tree_position_1:" << input_tree_position_1 << std::endl; - std::cout << "input_tree_position_2:" << input_tree_position_2 << std::endl; - zsl_prove_transfer( - proof, input_rho_ptr_1, input_pk_ptr_1, input_value_1, input_tree_position_1, auth_path_ptr_1, - input_rho_ptr_2, input_pk_ptr_2, input_value_2, input_tree_position_2, auth_path_ptr_2 - ,output_rho_ptr_1, output_pk_ptr_1, output_value_1, + std::cout << "input_tree_position_2:" << input_tree_position_2 << std::endl;*/ + + zsl_prove_transfer(proof, + input_rho_ptr_1, input_pk_ptr_1, input_value_1, input_tree_position_1, auth_path_ptr_1, + input_rho_ptr_2, input_pk_ptr_2, input_value_2, input_tree_position_2, auth_path_ptr_2, + output_rho_ptr_1, output_pk_ptr_1, output_value_1, output_rho_ptr_2, output_pk_ptr_2, output_value_2); output_proof = array_to_hex_str(proof, 584); @@ -203,15 +209,6 @@ bool zsl_verify_transfer( hex_str_to_array(cm_ptr_1, cm_1); hex_str_to_array(cm_ptr_2, cm_2); - return zsl_verify_transfer( - proof, - anchor, - spend_nf_1, - spend_nf_2, - send_nf_1, - send_nf_2, - cm_1, - cm_2 - ); + return zsl_verify_transfer(proof, anchor, spend_nf_1, spend_nf_2, send_nf_1, send_nf_2, cm_1, cm_2); } diff --git a/privacy/zsl/main.cpp b/privacy/zsl/main.cpp index c3276f4..0d8d817 100644 --- a/privacy/zsl/main.cpp +++ b/privacy/zsl/main.cpp @@ -1,108 +1,121 @@ #include #include +#include +#include + #include "note.hpp" #include "api.hpp" #include "utils/util.h" #include "merkle_tree.hpp" #include "utils/sha256.h" -std::string sk= "f0f0f0f00f0f0ffffffffff000000f0f0f0f0f00f0000f0f00f00f0f0f0f00ff"; -std::string pk= "e8e55f617b4b693083f883f70926dd5673fa434cefa3660828759947e2276348"; -std::string rho= "dedeffdddedeffdddedeffdddedeffdddedeffdddedeffdddedeffdddedeffdd"; - -bool shielding() +bool test_shielding() { - uint64_t value = 2378237 ; - std::cout << "rho:" << rho<< std::endl; - std::cout << "pk:" << pk<< std::endl; - std::cout << "sk:" << sk<< std::endl; - + std::string pk; + std::string sk; + std::string rho = get_randomness(); + get_keypair(sk, pk); + Note note(pk, 2378237, rho); + + std::cout << "rho:" << rho << std::endl; + std::cout << "pk:" << pk << std::endl; + std::cout << "sk:" << sk << std::endl; + std::cout << "value:" << 2378237 << std::endl; + std::string proof; - zsl_prove_shielding(rho, pk, value, proof); + zsl_prove_shielding(note.rho, note.pk, note.value, proof); //std::cout << "shielding proof:" << proof << std::endl;; - std::string send_nf = Note::computeSendNullifier(rho); - std::cout << "send_nf:" << send_nf << std::endl; - - std::string cm = Note::computeCommitment(rho, pk, value); - std::cout << "cm:" << cm << std::endl; - - bool ret = zsl_verify_shielding(proof, send_nf, cm, value); + bool ret = zsl_verify_shielding(proof, note.send_nf(), note.cm(), note.value); return ret; } -bool unshielding() +bool test_unshielding() { + std::string pk; + std::string sk; + std::string rho = get_randomness(); + + get_keypair(sk, pk); + Note note(pk, 2378237, rho); + + std::cout << "" << std::endl; + std::cout << "rho:" << rho << std::endl; + std::cout << "pk:" << pk << std::endl; + std::cout << "sk:" << sk << std::endl; + std::cout << "value:" << 2378237 << std::endl; + MerkleTree mt(29); uint64_t index = 0; - uint64_t value = 2378237 ; + + mt.add_commitment(note.cm()); - std::string cm = Note::computeCommitment(rho, pk, value); - mt.add_commitment(cm); std::vector uncles; - mt.get_witness(cm, index, uncles); - - std::cout << "index:" << index << std::endl; + mt.get_witness(note.cm(), index, uncles); - std::string spend_nf = Note::computeSpendNullifier(rho, sk); - std::cout << "spend_nf:" << spend_nf << std::endl; - - value = 2378237; std::string proof_u; - zsl_prove_unshielding(rho, sk, value, index, uncles, proof_u); + zsl_prove_unshielding(note.rho, sk, note.value, index, uncles, proof_u); //std::cout << "unshielding proof:" << proof_u << std::endl; - bool ret = zsl_verify_unshielding(proof_u, spend_nf, mt.root(), value); + bool ret = zsl_verify_unshielding(proof_u, note.spend_nf(sk), mt.root(), note.value); return ret; - } -bool shield_transfer() +bool test_shield_transfer() { MerkleTree mt(29); - std::string input_rho1 = rho; - //get_randomness(input_rho1, 32); - Note input_note1(pk, 100, input_rho1); std::string pk1; std::string sk1; + std::string pk2; + std::string sk2; + std::string input_rho1 = get_randomness(); + std::string input_rho2 = get_randomness(); + get_keypair(sk1, pk1); + get_keypair(sk2, pk2); - std::string input_rho2; - get_randomness(input_rho2, 32); - Note input_note2(pk1, 100, input_rho2); + Note input_note1(pk1, 100, input_rho1); + Note input_note2(pk2, 100, input_rho2); std::string input_cm1 = input_note1.cm(); - mt.add_commitment(input_cm1); std::string input_cm2 = input_note2.cm(); + + mt.add_commitment(input_cm1); mt.add_commitment(input_cm2); + std::cout << "" << std::endl; + std::cout << "Add input note 1:" << std::endl; + input_note1.debug_string(); + std::cout << "" << std::endl; + std::cout << "Add input note 2:" << std::endl; + input_note1.debug_string(); uint64_t index1 = 0; - std::vector auth_path1; - mt.get_witness(input_cm1, index1, auth_path1); - uint64_t index2 = 0; + std::vector auth_path1; std::vector auth_path2; + + mt.get_witness(input_cm1, index1, auth_path1); mt.get_witness(input_cm2, index2, auth_path2); - std::string output_pk; - std::string output_sk; - get_keypair(output_sk, output_pk); - std::string output_pk1; std::string output_sk1; + std::string output_pk2; + std::string output_sk2; + std::string output_rho1; + std::string output_rho2; + get_keypair(output_sk1, output_pk1); + get_keypair(output_sk2, output_pk2); - std::string output_rho1; get_randomness(output_rho1, 32); - std::string output_rho2; get_randomness(output_rho2, 32); - Note output_note1(output_pk, 150, output_rho1); - Note output_note2(output_pk1, 50, output_rho2); + Note output_note1(output_pk1, 150, output_rho1); + Note output_note2(output_pk2, 50, output_rho2); std::string anchor = mt.root(); @@ -115,36 +128,61 @@ bool shield_transfer() std::cout << "output_note1:" << std::endl; output_note2.debug_string();*/ - std::string proof_t; - zsl_prove_transfer(proof_t, input_note1.rho, sk, input_note1.value, index1, auth_path1, input_note2.rho, sk1, input_note2.value, index2, auth_path2, output_note1.rho, output_note1.pk, output_note1.value, output_note2.rho, output_note2.pk, output_note2.value); + std::time_t start = std::time(0); + zsl_prove_transfer(proof_t, input_note1.rho, sk1, input_note1.value, index1, auth_path1, input_note2.rho, sk2, input_note2.value, index2, auth_path2, output_note1.rho, output_note1.pk, output_note1.value, output_note2.rho, output_note2.pk, output_note2.value); + std::time_t end = std::time(0); + std::cout << "Prove transfer take " << end - start << std::endl; - bool ret = zsl_verify_transfer(proof_t, anchor, input_note1.spend_nf(sk), input_note2.spend_nf(sk1), output_note1.send_nf(), output_note2.send_nf(), output_note1.cm(), output_note2.cm()); - if (ret) { - std::cout << "spend the new output note test" << std::endl; - std::string new_input_cm1 = output_note1.cm(); - mt.add_commitment(new_input_cm1); - std::string new_input_cm2 = output_note2.cm(); - mt.add_commitment(new_input_cm2); - - auth_path1.clear(); - auth_path2.clear(); - mt.get_witness(new_input_cm1, index1, auth_path1); - mt.get_witness(new_input_cm2, index2, auth_path2); - - get_randomness(output_rho1, 32); - get_randomness(output_rho2, 32); - - Note new_output_note1(pk, 190, output_rho1); - Note new_output_note2(output_pk, 10, output_rho2); - - std::string anchor = mt.root(); - - std::string new_proof; - zsl_prove_transfer(new_proof, output_note1.rho, output_sk, output_note1.value, index1, auth_path1, output_note2.rho, output_sk1, output_note2.value, index2, auth_path2, new_output_note1.rho, new_output_note1.pk, new_output_note1.value, new_output_note2.rho, new_output_note2.pk, new_output_note2.value); - - bool ret = zsl_verify_transfer(new_proof, anchor, output_note1.spend_nf(output_sk), output_note2.spend_nf(output_sk1), new_output_note1.send_nf(), new_output_note2.send_nf(), new_output_note1.cm(), new_output_note2.cm()); + bool ret = zsl_verify_transfer(proof_t, anchor, input_note1.spend_nf(sk1), input_note2.spend_nf(sk2), output_note1.send_nf(), output_note2.send_nf(), output_note1.cm(), output_note2.cm()); + std::cout << "Verify transfer take " << std::time(0) - end << std::endl; + if (!ret) { + return false; } + std::cout << "" << std::endl; + std::cout << "Shield transfer for input note to output note done" << std::endl; + std::string new_input_cm1 = output_note1.cm(); + std::string new_input_cm2 = output_note2.cm(); + + mt.add_commitment(new_input_cm1); + mt.add_commitment(new_input_cm2); + + std::cout << "Add Onput note 1:" << std::endl; + output_note1.debug_string(); + std::cout << "" << std::endl; + std::cout << "Add Onput note 2:" << std::endl; + output_note2.debug_string(); + + auth_path1.clear(); + auth_path2.clear(); + mt.get_witness(new_input_cm1, index1, auth_path1); + mt.get_witness(new_input_cm2, index2, auth_path2); + + output_rho1 = get_randomness(); + output_rho2 = get_randomness(); + + Note new_output_note1(pk1, 190, output_rho1); + Note new_output_note2(output_pk1, 10, output_rho2); + + anchor = mt.root(); + + std::cout << "" << std::endl; + std::cout << "Spend the output note and generate new output note" << std::endl; + std::cout << "New output note 1:" << std::endl; + new_output_note1.debug_string(); + std::cout << "" << std::endl; + std::cout << "New output note 2:" << std::endl; + new_output_note2.debug_string(); + + std::string new_proof; + std::time_t start1 = std::time(0); + zsl_prove_transfer(new_proof, output_note1.rho, output_sk1, output_note1.value, index1, auth_path1, output_note2.rho, output_sk2, output_note2.value, index2, auth_path2, new_output_note1.rho, new_output_note1.pk, new_output_note1.value, new_output_note2.rho, new_output_note2.pk, new_output_note2.value); + std::time_t end1 = std::time(0); + std::cout << "Prove transfer take " << end1 - start1 << std::endl; + + ret = zsl_verify_transfer(new_proof, anchor, output_note1.spend_nf(output_sk1), output_note2.spend_nf(output_sk2), new_output_note1.send_nf(), new_output_note2.send_nf(), new_output_note1.cm(), new_output_note2.cm()); + std::cout << "Verify transfer take " << std::time(0) - end1 << std::endl; + return ret; } @@ -154,29 +192,36 @@ int main(int argc, char *argv[]) // shielding zk-snark test //zsl_paramgen_shielding(); - bool ret = shielding(); + std::time_t start = std::time(0); + bool ret = test_shielding(); if(!ret) { - std::cout << "shield verify failed" << std::endl; + std::cout << "Shielding verify failed" << std::endl; } else { - std::cout << "shield verify done" << std::endl; + std::cout << "Shielding verify done" << std::endl; } + std::time_t time1 = std::time(0); + std::cout << "Take " << time1 - start << " seconds" << std::endl; // unsheilding zk-snark test //zsl_paramgen_unshielding(); - /*ret = unshielding(); + ret = test_unshielding(); if(!ret) { - std::cout << "unshield verify failed" << std::endl; + std::cout << "Unshielding verify failed" << std::endl; } else { - std::cout << "unshield verify done" << std::endl; - }*/ + std::cout << "Unshielding verify done" << std::endl; + } + std::time_t time2 = std::time(0); + std::cout << "Take " << time2 - time1 << " seconds" << std::endl; // sheilding transfer zk-snark test //zsl_paramgen_transfer(); - ret = shield_transfer(); + ret = test_shield_transfer(); if(!ret) { - std::cout << "shield tranfer verify failed" << std::endl; + std::cout << "Shield tranfer verify failed" << std::endl; } else { - std::cout << "shield tranfer verify done" << std::endl; + std::cout << "Shield tranfer verify done" << std::endl; } + std::time_t time3 = std::time(0); + std::cout << "Take " << time3 - time2 << " seconds" << std::endl; return 0; } diff --git a/privacy/zsl/merkle_tree.cpp b/privacy/zsl/merkle_tree.cpp index 326805e..dc6f74b 100644 --- a/privacy/zsl/merkle_tree.cpp +++ b/privacy/zsl/merkle_tree.cpp @@ -41,14 +41,15 @@ std::string MerkleTree::get_commitment_at_leaf_index(uint32_t index) { return ""; }*/ -void MerkleTree::add_commitment(std::string& cm) { +void MerkleTree::add_commitment(const std::string& cm) { if (num_commitments >= max_num_elements) return; //if (map_commitment_indices.find(cm) != map_commitment_indices.end()) return; if (commitment_exists(cm)) return; uint32_t map_index = ++ num_commitments; //map_commitment_indices[cm] = map_index; - map_commitments[map_index] = cm; + //map_commitments[map_index] = cm; + map_commitments.insert(std::make_pair(map_index, cm)); } bool MerkleTree::commitment_exists(const std::string& cm) { diff --git a/privacy/zsl/merkle_tree.hpp b/privacy/zsl/merkle_tree.hpp index f9ea763..eacc7d0 100644 --- a/privacy/zsl/merkle_tree.hpp +++ b/privacy/zsl/merkle_tree.hpp @@ -29,7 +29,7 @@ class MerkleTree std::string combine(const std::string& left, const std::string& right); //uint32_t get_leaf_index(std::string& cm); //std::string get_commitment_at_leaf_index(uint32_t index); - void add_commitment(std::string& cm); + void add_commitment(const std::string& cm); bool commitment_exists(const std::string& cm); void get_witness(const std::string& cm, uint64_t& index, std::vector& uncles); diff --git a/privacy/zsl/test.cpp b/privacy/zsl/test.cpp deleted file mode 100644 index c3276f4..0000000 --- a/privacy/zsl/test.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include -#include - -#include "note.hpp" -#include "api.hpp" -#include "utils/util.h" -#include "merkle_tree.hpp" -#include "utils/sha256.h" - -std::string sk= "f0f0f0f00f0f0ffffffffff000000f0f0f0f0f00f0000f0f00f00f0f0f0f00ff"; -std::string pk= "e8e55f617b4b693083f883f70926dd5673fa434cefa3660828759947e2276348"; -std::string rho= "dedeffdddedeffdddedeffdddedeffdddedeffdddedeffdddedeffdddedeffdd"; - - -bool shielding() -{ - uint64_t value = 2378237 ; - std::cout << "rho:" << rho<< std::endl; - std::cout << "pk:" << pk<< std::endl; - std::cout << "sk:" << sk<< std::endl; - - - std::string proof; - zsl_prove_shielding(rho, pk, value, proof); - //std::cout << "shielding proof:" << proof << std::endl;; - - std::string send_nf = Note::computeSendNullifier(rho); - std::cout << "send_nf:" << send_nf << std::endl; - - std::string cm = Note::computeCommitment(rho, pk, value); - std::cout << "cm:" << cm << std::endl; - - bool ret = zsl_verify_shielding(proof, send_nf, cm, value); - return ret; -} - -bool unshielding() -{ - MerkleTree mt(29); - uint64_t index = 0; - uint64_t value = 2378237 ; - - std::string cm = Note::computeCommitment(rho, pk, value); - mt.add_commitment(cm); - std::vector uncles; - mt.get_witness(cm, index, uncles); - - std::cout << "index:" << index << std::endl; - - std::string spend_nf = Note::computeSpendNullifier(rho, sk); - std::cout << "spend_nf:" << spend_nf << std::endl; - - value = 2378237; - std::string proof_u; - zsl_prove_unshielding(rho, sk, value, index, uncles, proof_u); - //std::cout << "unshielding proof:" << proof_u << std::endl; - - bool ret = zsl_verify_unshielding(proof_u, spend_nf, mt.root(), value); - return ret; - -} - -bool shield_transfer() -{ - MerkleTree mt(29); - std::string input_rho1 = rho; - //get_randomness(input_rho1, 32); - Note input_note1(pk, 100, input_rho1); - - std::string pk1; - std::string sk1; - get_keypair(sk1, pk1); - - std::string input_rho2; - get_randomness(input_rho2, 32); - Note input_note2(pk1, 100, input_rho2); - - std::string input_cm1 = input_note1.cm(); - mt.add_commitment(input_cm1); - std::string input_cm2 = input_note2.cm(); - mt.add_commitment(input_cm2); - - uint64_t index1 = 0; - std::vector auth_path1; - mt.get_witness(input_cm1, index1, auth_path1); - - uint64_t index2 = 0; - std::vector auth_path2; - mt.get_witness(input_cm2, index2, auth_path2); - - std::string output_pk; - std::string output_sk; - get_keypair(output_sk, output_pk); - - std::string output_pk1; - std::string output_sk1; - get_keypair(output_sk1, output_pk1); - - std::string output_rho1; - get_randomness(output_rho1, 32); - std::string output_rho2; - get_randomness(output_rho2, 32); - - Note output_note1(output_pk, 150, output_rho1); - Note output_note2(output_pk1, 50, output_rho2); - - std::string anchor = mt.root(); - - /*std::cout << "input_note1:" << std::endl; - input_note1.debug_string(); - std::cout << "input_note2:" << std::endl; - input_note2.debug_string(); - std::cout << "output_note1:" << std::endl; - output_note1.debug_string(); - std::cout << "output_note1:" << std::endl; - output_note2.debug_string();*/ - - - std::string proof_t; - zsl_prove_transfer(proof_t, input_note1.rho, sk, input_note1.value, index1, auth_path1, input_note2.rho, sk1, input_note2.value, index2, auth_path2, output_note1.rho, output_note1.pk, output_note1.value, output_note2.rho, output_note2.pk, output_note2.value); - - bool ret = zsl_verify_transfer(proof_t, anchor, input_note1.spend_nf(sk), input_note2.spend_nf(sk1), output_note1.send_nf(), output_note2.send_nf(), output_note1.cm(), output_note2.cm()); - if (ret) { - std::cout << "spend the new output note test" << std::endl; - std::string new_input_cm1 = output_note1.cm(); - mt.add_commitment(new_input_cm1); - std::string new_input_cm2 = output_note2.cm(); - mt.add_commitment(new_input_cm2); - - auth_path1.clear(); - auth_path2.clear(); - mt.get_witness(new_input_cm1, index1, auth_path1); - mt.get_witness(new_input_cm2, index2, auth_path2); - - get_randomness(output_rho1, 32); - get_randomness(output_rho2, 32); - - Note new_output_note1(pk, 190, output_rho1); - Note new_output_note2(output_pk, 10, output_rho2); - - std::string anchor = mt.root(); - - std::string new_proof; - zsl_prove_transfer(new_proof, output_note1.rho, output_sk, output_note1.value, index1, auth_path1, output_note2.rho, output_sk1, output_note2.value, index2, auth_path2, new_output_note1.rho, new_output_note1.pk, new_output_note1.value, new_output_note2.rho, new_output_note2.pk, new_output_note2.value); - - bool ret = zsl_verify_transfer(new_proof, anchor, output_note1.spend_nf(output_sk), output_note2.spend_nf(output_sk1), new_output_note1.send_nf(), new_output_note2.send_nf(), new_output_note1.cm(), new_output_note2.cm()); - } - return ret; -} - -int main(int argc, char *argv[]) -{ - zsl_initialize(); - - // shielding zk-snark test - //zsl_paramgen_shielding(); - bool ret = shielding(); - if(!ret) { - std::cout << "shield verify failed" << std::endl; - } else { - std::cout << "shield verify done" << std::endl; - } - - // unsheilding zk-snark test - //zsl_paramgen_unshielding(); - /*ret = unshielding(); - if(!ret) { - std::cout << "unshield verify failed" << std::endl; - } else { - std::cout << "unshield verify done" << std::endl; - }*/ - - // sheilding transfer zk-snark test - //zsl_paramgen_transfer(); - ret = shield_transfer(); - if(!ret) { - std::cout << "shield tranfer verify failed" << std::endl; - } else { - std::cout << "shield tranfer verify done" << std::endl; - } - return 0; -} diff --git a/privacy/zsl/test.cpp1 b/privacy/zsl/test.cpp1 deleted file mode 100644 index f55e9fa..0000000 --- a/privacy/zsl/test.cpp1 +++ /dev/null @@ -1,134 +0,0 @@ -#include -#include - -#include "note.hpp" -#include "utils/util.h" -#include "merkle_tree.hpp" -#include "zsl/snark/zsl.h" -#include "utils/sha256.h" - -unsigned char rho[32]; -unsigned char pk[32]; -unsigned char sk[32]; -unsigned char send_nf[32]; -unsigned char cm[32]; -unsigned char proof_s[584]; -uint64_t value = 0; - - -bool shielding() -{ - /*get_keypair(sk, pk); - - std::cout << "a_pk:"; - print_char_array(pk, 32); - std::cout << "a_sk:"; - print_char_array(sk, 32); - - get_randomness(rho, 32); - //std::cout << "rho:"; - //print_char_array(rho, 32); - */ - - std::string sk_str = "f0f0f0f00f0f0ffffffffff000000f0f0f0f0f00f0000f0f00f00f0f0f0f00ff"; - std::string pk_str = "e8e55f617b4b693083f883f70926dd5673fa434cefa3660828759947e2276348"; - std::string rho_str = "dedeffdddedeffdddedeffdddedeffdddedeffdddedeffdddedeffdddedeffdd"; - - hex_str_to_array(sk_str, sk); - hex_str_to_array(pk_str, pk); - hex_str_to_array(rho_str, rho); - - value = 2378237 ; - - // zsl_prove_shielding(void *rho, void *pk, uint64_t value, void *output_proof); - zsl_prove_shielding(rho, pk, value, proof_s); - //std::cout << "shielding proof:"; - //print_char_array(proof_str, 32); - - std::cout << "rho:"; - print_char_array(rho, 32); - std::cout << "pk:"; - print_char_array(pk, 32); - - computeSendNullifier(rho, send_nf); - std::cout << "send_nf:"; - print_char_array(send_nf, 32); - - computeCommitment(rho, pk, value, cm); - std::cout << "cm:"; - print_char_array(cm, 32); - - bool ret = zsl_verify_shielding(proof_s, send_nf, cm, value); - if(!ret) { - std::cout << "shield verify failed" << std::endl; - } else { - std::cout << "shield verify done" << std::endl; - } - return ret; -} - -int main(int argc, char *argv[]) -{ - zsl_initialize(); - bool ret = shielding(); - - std::string zero = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; - std::cout << "Two zero combine hash is:" << sha256(zero) << std::endl; - - std::string cm_str = array_to_hex_str(cm, 32); - MerkleTree mt(29); - mt.add_commitment(cm_str); - std::cout << "commitment is:" << cm_str << std::endl; - - /*std::cout << "empty roots is:" << std::endl; - for(int i = 0; i < mt.empty_roots.size(); i++) { - std::cout << mt.empty_roots[i] << std::endl; - }*/ - - /*std::cout << "commitments map:" << std::endl; - std::map::iterator it = mt.map_commitments.begin(); - for ( ; it != mt.map_commitments.end(); it++) { - std::cout << it->first << ":" << it->second << std::endl; - }*/ - - uint32_t index = 0; - std::vector uncles; - mt.get_witness(cm_str, index, uncles); - std::cout << index << std::endl; - - unsigned char auth_path[29][32]; - for(int i = 0; i < uncles.size(); i++) { - //std::string path_item = "8000000000000000000000000000000000000000000000000000000000000100"; - //for(int i = 0; i < 29; i++) { - unsigned char item[32]; - hex_str_to_array(uncles[i], item); - //hex_str_to_array(path_item, item); - for(int j = 0; j < 32; j++) { - auth_path[i][j] = item[j]; - } - std::cout << uncles[i] << std::endl; - } - - unsigned char spend_nf[32]; - computeSpendNullifier(rho, sk, spend_nf); - std::cout << "spend_nf:"; - print_char_array(spend_nf, 32); - - unsigned char root[32]; - //std::string rt_str = "8610652739ac0c6bb6b5353649bb822b26543f0ebe88f32a489a56843cd04f03"; - hex_str_to_array(mt.root(), root); - //hex_str_to_array(rt_str, root); - - unsigned char proof_u[584] = {0x00}; - //zsl_prove_unshielding(rho, sk, value, 0, auth_path, proof_u); - /*zsl_prove_unshielding(rho, sk, value, index, auth_path, proof_u); - - ret = zsl_verify_unshielding(proof_u, spend_nf, root, value); - if(!ret) { - std::cout << "unshield verify failed" << std::endl; - } else { - std::cout << "unshield verify done" << std::endl; - }*/ - - return 0; -} diff --git a/privacy/zsl/test1.cpp b/privacy/zsl/test1.cpp deleted file mode 100644 index 9790fc2..0000000 --- a/privacy/zsl/test1.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include - -#include "utils/util.h" - - -int main() -{ - std::string a = "0000000000000000000000000000000000000000000000000000000000000000"; - std::string b = "58e38183982c6f7981e9f3ce0a735fdd4ca2f0cd88db6ee608c2fe1e84142d0d"; - std::cout << sha256_compress(a, a) << std::endl; - std::cout << sha256_compress(b, a) << std::endl; - return 0; -} diff --git a/privacy/zsl/utils/bak/endian.h b/privacy/zsl/utils/bak/endian.h deleted file mode 100644 index 90a485e..0000000 --- a/privacy/zsl/utils/bak/endian.h +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) 2014 The Bitcoin developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef BITCOIN_COMPAT_ENDIAN_H -#define BITCOIN_COMPAT_ENDIAN_H - -#if defined(HAVE_CONFIG_H) -#include "config/bitcoin-config.h" -#endif - -#include - -#include "byteswap.h" - -#if defined(HAVE_ENDIAN_H) -#include -#elif defined(HAVE_SYS_ENDIAN_H) -#include -#endif - -#if defined(WORDS_BIGENDIAN) - -#if HAVE_DECL_HTOBE16 == 0 -inline uint16_t htobe16(uint16_t host_16bits) -{ - return host_16bits; -} -#endif // HAVE_DECL_HTOBE16 - -#if HAVE_DECL_HTOLE16 == 0 -inline uint16_t htole16(uint16_t host_16bits) -{ - return bswap_16(host_16bits); -} -#endif // HAVE_DECL_HTOLE16 - -#if HAVE_DECL_BE16TOH == 0 -inline uint16_t be16toh(uint16_t big_endian_16bits) -{ - return big_endian_16bits; -} -#endif // HAVE_DECL_BE16TOH - -#if HAVE_DECL_LE16TOH == 0 -inline uint16_t le16toh(uint16_t little_endian_16bits) -{ - return bswap_16(little_endian_16bits); -} -#endif // HAVE_DECL_LE16TOH - -#if HAVE_DECL_HTOBE32 == 0 -inline uint32_t htobe32(uint32_t host_32bits) -{ - return host_32bits; -} -#endif // HAVE_DECL_HTOBE32 - -#if HAVE_DECL_HTOLE32 == 0 -inline uint32_t htole32(uint32_t host_32bits) -{ - return bswap_32(host_32bits); -} -#endif // HAVE_DECL_HTOLE32 - -#if HAVE_DECL_BE32TOH == 0 -inline uint32_t be32toh(uint32_t big_endian_32bits) -{ - return big_endian_32bits; -} -#endif // HAVE_DECL_BE32TOH - -#if HAVE_DECL_LE32TOH == 0 -inline uint32_t le32toh(uint32_t little_endian_32bits) -{ - return bswap_32(little_endian_32bits); -} -#endif // HAVE_DECL_LE32TOH - -#if HAVE_DECL_HTOBE64 == 0 -inline uint64_t htobe64(uint64_t host_64bits) -{ - return host_64bits; -} -#endif // HAVE_DECL_HTOBE64 - -#if HAVE_DECL_HTOLE64 == 0 -inline uint64_t htole64(uint64_t host_64bits) -{ - return bswap_64(host_64bits); -} -#endif // HAVE_DECL_HTOLE64 - -#if HAVE_DECL_BE64TOH == 0 -inline uint64_t be64toh(uint64_t big_endian_64bits) -{ - return big_endian_64bits; -} -#endif // HAVE_DECL_BE64TOH - -#if HAVE_DECL_LE64TOH == 0 -inline uint64_t le64toh(uint64_t little_endian_64bits) -{ - return bswap_64(little_endian_64bits); -} -#endif // HAVE_DECL_LE64TOH - -#else // WORDS_BIGENDIAN - -//#if HAVE_DECL_HTOBE16 == 0 -#ifndef HAVE_DECL_HTOBE16 -inline uint16_t htobe16(uint16_t host_16bits) -{ - return bswap_16(host_16bits); -} -#endif // HAVE_DECL_HTOBE16 - -#if HAVE_DECL_HTOLE16 == 0 -inline uint16_t htole16(uint16_t host_16bits) -{ - return host_16bits; -} -#endif // HAVE_DECL_HTOLE16 - -#if HAVE_DECL_BE16TOH == 0 -inline uint16_t be16toh(uint16_t big_endian_16bits) -{ - return bswap_16(big_endian_16bits); -} -#endif // HAVE_DECL_BE16TOH - -#if HAVE_DECL_LE16TOH == 0 -inline uint16_t le16toh(uint16_t little_endian_16bits) -{ - return little_endian_16bits; -} -#endif // HAVE_DECL_LE16TOH - -#if HAVE_DECL_HTOBE32 == 0 -inline uint32_t htobe32(uint32_t host_32bits) -{ - return bswap_32(host_32bits); -} -#endif // HAVE_DECL_HTOBE32 - -#if HAVE_DECL_HTOLE32 == 0 -inline uint32_t htole32(uint32_t host_32bits) -{ - return host_32bits; -} -#endif // HAVE_DECL_HTOLE32 - -#if HAVE_DECL_BE32TOH == 0 -inline uint32_t be32toh(uint32_t big_endian_32bits) -{ - return bswap_32(big_endian_32bits); -} -#endif // HAVE_DECL_BE32TOH - -#if HAVE_DECL_LE32TOH == 0 -inline uint32_t le32toh(uint32_t little_endian_32bits) -{ - return little_endian_32bits; -} -#endif // HAVE_DECL_LE32TOH - -#if HAVE_DECL_HTOBE64 == 0 -inline uint64_t htobe64(uint64_t host_64bits) -{ - return bswap_64(host_64bits); -} -#endif // HAVE_DECL_HTOBE64 - -#if HAVE_DECL_HTOLE64 == 0 -inline uint64_t htole64(uint64_t host_64bits) -{ - return host_64bits; -} -#endif // HAVE_DECL_HTOLE64 - -#if HAVE_DECL_BE64TOH == 0 -inline uint64_t be64toh(uint64_t big_endian_64bits) -{ - return bswap_64(big_endian_64bits); -} -#endif // HAVE_DECL_BE64TOH - -#if HAVE_DECL_LE64TOH == 0 -inline uint64_t le64toh(uint64_t little_endian_64bits) -{ - return little_endian_64bits; -} -#endif // HAVE_DECL_LE64TOH - -#endif // WORDS_BIGENDIAN - -#endif // BITCOIN_COMPAT_ENDIAN_H diff --git a/privacy/zsl/utils/bak/sha256.cpp b/privacy/zsl/utils/bak/sha256.cpp deleted file mode 100644 index c64d1ad..0000000 --- a/privacy/zsl/utils/bak/sha256.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/********************************************************************* -* Filename: sha256.c -* Author: Brad Conte (brad AT bradconte.com) -* Copyright: -* Disclaimer: This code is presented "as is" without any guarantees. -* Details: Implementation of the SHA-256 hashing algorithm. - SHA-256 is one of the three algorithms in the SHA2 - specification. The others, SHA-384 and SHA-512, are not - offered in this implementation. - Algorithm specification can be found here: - * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf - This implementation uses little endian byte order. -*********************************************************************/ - -/*************************** HEADER FILES ***************************/ -#include -#include -#include "sha256.h" - -/****************************** MACROS ******************************/ -#define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b)))) -#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b)))) - -#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z))) -#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) -#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22)) -#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25)) -#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3)) -#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10)) - -/**************************** VARIABLES *****************************/ -static const WORD k[64] = { - 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, - 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, - 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, - 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, - 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, - 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, - 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, - 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 -}; - -/*********************** FUNCTION DEFINITIONS ***********************/ -void sha256_transform(SHA256_CTX_mod *ctx, const BYTE data[]) -{ - WORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64]; - - for (i = 0, j = 0; i < 16; ++i, j += 4) - m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]); - for ( ; i < 64; ++i) - m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; - - a = ctx->state[0]; - b = ctx->state[1]; - c = ctx->state[2]; - d = ctx->state[3]; - e = ctx->state[4]; - f = ctx->state[5]; - g = ctx->state[6]; - h = ctx->state[7]; - - for (i = 0; i < 64; ++i) { - t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; - t2 = EP0(a) + MAJ(a,b,c); - h = g; - g = f; - f = e; - e = d + t1; - d = c; - c = b; - b = a; - a = t1 + t2; - } - - ctx->state[0] += a; - ctx->state[1] += b; - ctx->state[2] += c; - ctx->state[3] += d; - ctx->state[4] += e; - ctx->state[5] += f; - ctx->state[6] += g; - ctx->state[7] += h; -} - -void sha256_init(SHA256_CTX_mod *ctx) -{ - ctx->datalen = 0; - ctx->bitlen = 0; - ctx->state[0] = 0x6a09e667; - ctx->state[1] = 0xbb67ae85; - ctx->state[2] = 0x3c6ef372; - ctx->state[3] = 0xa54ff53a; - ctx->state[4] = 0x510e527f; - ctx->state[5] = 0x9b05688c; - ctx->state[6] = 0x1f83d9ab; - ctx->state[7] = 0x5be0cd19; -} - -void sha256_update(SHA256_CTX_mod *ctx, const BYTE data[], size_t len) -{ - WORD i; - - for (i = 0; i < len; ++i) { - ctx->data[ctx->datalen] = data[i]; - ctx->datalen++; - if (ctx->datalen == 64) { - sha256_transform(ctx, ctx->data); - ctx->bitlen += 512; - ctx->datalen = 0; - } - } -} - -void sha256_final(SHA256_CTX_mod *ctx, BYTE hash[]) -{ - WORD i; - - i = ctx->datalen; - - for (i = 0; i < 4; ++i) { - hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff; - hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff; - hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff; - hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff; - hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff; - hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff; - hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff; - hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff; - } -} diff --git a/privacy/zsl/utils/bak/sha256.h b/privacy/zsl/utils/bak/sha256.h deleted file mode 100644 index 9f6afa1..0000000 --- a/privacy/zsl/utils/bak/sha256.h +++ /dev/null @@ -1,34 +0,0 @@ -/********************************************************************* -* Filename: sha256.h -* Author: Brad Conte (brad AT bradconte.com) -* Copyright: -* Disclaimer: This code is presented "as is" without any guarantees. -* Details: Defines the API for the corresponding SHA1 implementation. -*********************************************************************/ - -#ifndef SHA256H_H -#define SHA256H_H - -/*************************** HEADER FILES ***************************/ -#include - -/****************************** MACROS ******************************/ -#define SHA256_BLOCK_SIZE 32 // SHA256 outputs a 32 byte digest - -/**************************** DATA TYPES ****************************/ -typedef unsigned char BYTE; // 8-bit byte -typedef unsigned int WORD; // 32-bit word, change to "long" for 16-bit machines - -typedef struct { - BYTE data[64]; - WORD datalen; - unsigned long long bitlen; - WORD state[8]; -} SHA256_CTX_mod; - -/*********************** FUNCTION DECLARATIONS **********************/ -void sha256_init(SHA256_CTX_mod *ctx); -void sha256_update(SHA256_CTX_mod *ctx, const BYTE data[], size_t len); -void sha256_final(SHA256_CTX_mod *ctx, BYTE hash[]); - -#endif // SHA256H_H diff --git a/privacy/zsl/utils/bak/util.cpp b/privacy/zsl/utils/bak/util.cpp deleted file mode 100644 index 3a928a8..0000000 --- a/privacy/zsl/utils/bak/util.cpp +++ /dev/null @@ -1,307 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "util.h" - - -void printChar(const unsigned char c) { - for(int j = 8; j >= 0; j--) { - std::cout << ((c >> j) & 1); - } - std::cout << std::endl; -} - -void printVector(const std::vector& v) { - std::cout << v.size() << " MSB "; - for(size_t i = 0; i < v.size(); i++) { - std::cout << v.at(i); - } - std::cout << " LSB" << std::endl; -} - -void printVector(const std::string str, const std::vector& v) { - std::cout << str << " " << v.size() << " MSB "; - for(size_t i = 0; i < v.size(); i++) { - std::cout << v.at(i); - } - std::cout << " LSB" << std::endl; -} - -void printVectorAsHex(const std::vector& v) { - unsigned char bytes[int(v.size() / 8)]; - convertVectorToBytes(v, bytes); - - for(int i = 0; i < int(v.size() / 8); i++) { - std::cout << std::setw(2) << std::setfill('0') << std::hex << (int) bytes[i]; - } - std::cout << std::dec << std::endl; -} - -void printVectorAsHex(const std::string str, const std::vector& v) { - unsigned char bytes[int(v.size() / 8)]; - convertVectorToBytes(v, bytes); - - std::cout << str << " "; - for(int i = 0; i < int(v.size() / 8); i++) { - std::cout << std::setw(2) << std::setfill('0') << std::hex << (int) bytes[i]; - } - std::cout << std::dec << std::endl; -} - -void printBytesVector(const std::vector& v) { - std::vector boolVec(v.size() * 8); - convertBytesVectorToVector(v, boolVec); - printVector(boolVec); -} - -void printBytesVector(const std::string str, const std::vector& v) { - std::vector boolVec(v.size() * 8); - convertBytesVectorToVector(v, boolVec); - printVector(str, boolVec); -} - -void printBytesVectorAsHex(const std::vector& v) { - std::vector boolVec(v.size() * 8); - convertBytesVectorToVector(v, boolVec); - printVectorAsHex(boolVec); -} - -void printBytesVectorAsHex(const std::string str, const std::vector& v) { - std::vector boolVec(v.size() * 8); - convertBytesVectorToVector(v, boolVec); - printVectorAsHex(str, boolVec); -} - -void getRandBytes(unsigned char* bytes, int num) { - int ret = RAND_bytes(bytes, num); - if(ret != 1) - std::cout << "rand_bytes error!" << ERR_get_error() << std::endl; -} - -void convertBytesToVector(const unsigned char* bytes, std::vector& v) { - int numBytes = v.size() / 8; - unsigned char c; - for(int i = 0; i < numBytes; i++) { - c = bytes[i]; - - for(int j = 0; j < 8; j++) { - v.at((i*8)+j) = ((c >> (7-j)) & 1); - } - } -} - -void convertVectorToBytes(const std::vector& v, unsigned char* bytes) { - int numBytes = v.size() / 8; - unsigned char c = '\0'; - - for(int i = 0; i < numBytes; i++) { - c = '\0'; - for(int j = 0; j < 8; j++) { - if(j == 7) - c = ((c | v.at((i*8)+j))); - else - c = ((c | v.at((i*8)+j)) << 1); - } - bytes[i] = c; - } -} - -void convertBytesToBytesVector(const unsigned char* bytes, std::vector& v) { - for(size_t i = 0; i < v.size(); i++) { - v.at(i) = bytes[i]; - } -} - -void convertBytesVectorToBytes(const std::vector& v, unsigned char* bytes) { - for(size_t i = 0; i < v.size(); i++) { - bytes[i] = v.at(i); - } -} - -void convertBytesVectorToVector(const std::vector& bytes, std::vector& v) { - v.resize(bytes.size() * 8); - unsigned char bytesArr[bytes.size()]; - convertBytesVectorToBytes(bytes, bytesArr); - convertBytesToVector(bytesArr, v); -} - -void convertVectorToBytesVector(const std::vector& v, std::vector& bytes) { - unsigned char bytesArr[int(ceil(v.size() / 8.))]; - convertVectorToBytes(v, bytesArr); - convertBytesToBytesVector(bytesArr, bytes); -} - -void convertIntToBytesVector(const uint64_t val_int, std::vector& bytes) { - for(size_t i = 0; i < bytes.size(); i++) { - bytes[bytes.size()-1-i] = (val_int >> (i * 8)); - } -} - -uint64_t convertBytesVectorToInt(const std::vector& bytes) { - uint64_t val_int = 0; - - for(size_t i = 0; i < bytes.size(); i++) { - val_int = val_int + (bytes[i] << ((bytes.size()-1-i) * 8)); - } - - return val_int; -} - -void concatenateVectors(const std::vector& A, const std::vector& B, std::vector& result) { - result.reserve(A.size() + B.size()); - result.insert(result.end(), A.begin(), A.end()); - result.insert(result.end(), B.begin(), B.end()); -} - -void concatenateVectors(const std::vector& A, const std::vector& B, std::vector& result) { - result.reserve(A.size() + B.size()); - result.insert(result.end(), A.begin(), A.end()); - result.insert(result.end(), B.begin(), B.end()); -} - -void concatenateVectors(const std::vector& A, const std::vector& B, const std::vector& C, std::vector& result) { - result.reserve(A.size() + B.size() + C.size()); - result.insert(result.end(), A.begin(), A.end()); - result.insert(result.end(), B.begin(), B.end()); - result.insert(result.end(), C.begin(), C.end()); -} - -void concatenateVectors(const std::vector& A, const std::vector& B, const std::vector& C, std::vector& result) { - result.reserve(A.size() + B.size() + C.size()); - result.insert(result.end(), A.begin(), A.end()); - result.insert(result.end(), B.begin(), B.end()); - result.insert(result.end(), C.begin(), C.end()); -} - -void sha256(unsigned char* input, unsigned char* hash, int len) { - SHA256_CTX_mod ctx256; - - sha256_init(&ctx256); - sha256_update(&ctx256, input, len); - sha256_final(&ctx256, hash); -} - -void sha256(SHA256_CTX_mod* ctx256, unsigned char* input, unsigned char* hash, int len) { - sha256_init(ctx256); - sha256_update(ctx256, input, len); - sha256_final(ctx256, hash); -} - -void hashVector(SHA256_CTX_mod* ctx256, const std::vector input, std::vector& output) { - int size = int(input.size() / 8); - unsigned char bytes[size]; - convertVectorToBytes(input, bytes); - - unsigned char hash[SHA256_BLOCK_SIZE]; - sha256(ctx256, bytes, hash, (int)size); - - convertBytesToVector(hash, output); -} - -void hashVector(SHA256_CTX_mod* ctx256, const std::vector input, std::vector& output) { - int size = int(input.size()); - unsigned char bytes[size]; - convertBytesVectorToBytes(input, bytes); - - unsigned char hash[SHA256_BLOCK_SIZE]; - sha256(ctx256, bytes, hash, (int)size); - - convertBytesToBytesVector(hash, output); -} - -void hashVector(const std::vector input, std::vector& output) { - SHA256_CTX_mod ctx256; - - int size = int(input.size() / 8); - unsigned char bytes[size]; - convertVectorToBytes(input, bytes); - - unsigned char hash[SHA256_BLOCK_SIZE]; - sha256(&ctx256, bytes, hash, (int)size); - - convertBytesToVector(hash, output); -} - -void hashVector(const std::vector input, std::vector& output) { - SHA256_CTX_mod ctx256; - - int size = int(input.size()); - unsigned char bytes[size]; - convertBytesVectorToBytes(input, bytes); - - unsigned char hash[SHA256_BLOCK_SIZE]; - sha256(&ctx256, bytes, hash, (int)size); - - convertBytesToBytesVector(hash, output); -} - -void hashVectors(SHA256_CTX_mod* ctx256, const std::vector left, const std::vector right, std::vector& output) { - std::vector concat; - concatenateVectors(left, right, concat); - - int size = int(concat.size() / 8); - unsigned char bytes[size]; - convertVectorToBytes(concat, bytes); - - unsigned char hash[SHA256_BLOCK_SIZE]; - sha256(ctx256, bytes, hash, (int)size); - - convertBytesToVector(hash, output); -} - -void hashVectors(SHA256_CTX_mod* ctx256, const std::vector left, const std::vector right, std::vector& output) { - std::vector concat; - concatenateVectors(left, right, concat); - - int size = int(concat.size()); - unsigned char bytes[size]; - convertBytesVectorToBytes(concat, bytes); - - unsigned char hash[SHA256_BLOCK_SIZE]; - sha256(ctx256, bytes, hash, (int)size); - - convertBytesToBytesVector(hash, output); -} - -void hashVectors(const std::vector left, const std::vector right, std::vector& output) { - std::cout << std::endl; - - std::vector concat; - concatenateVectors(left, right, concat); - - int size = int(concat.size() / 8); - unsigned char bytes[size]; - convertVectorToBytes(concat, bytes); - - unsigned char hash[SHA256_BLOCK_SIZE]; - sha256(bytes, hash, (int)size); - - convertBytesToVector(hash, output); -} - -void hashVectors(const std::vector left, const std::vector right, std::vector& output) { - std::vector concat; - concatenateVectors(left, right, concat); - - int size = int(concat.size()); - unsigned char bytes[size]; - convertBytesVectorToBytes(concat, bytes); - - unsigned char hash[SHA256_BLOCK_SIZE]; - sha256(bytes, hash, (int)size); - - convertBytesToBytesVector(hash, output); -} - -bool VectorIsZero(const std::vector test) { - return (test.end() == std::find(test.begin(), test.end(), true)); -} diff --git a/privacy/zsl/utils/bak/util.h b/privacy/zsl/utils/bak/util.h deleted file mode 100644 index 24405a9..0000000 --- a/privacy/zsl/utils/bak/util.h +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef UTIL_H_ -#define UTIL_H_ - -#include -#include - -#include "sha256.h" -#include "uint256.h" - -void printChar(const unsigned char c); - -void printVector(const std::vector& v); - -void printVector(const std::string str, const std::vector& v); - -void printVectorAsHex(const std::vector& v); - -void printVectorAsHex(const std::string str, const std::vector& v); - -void printBytesVector(const std::vector& v); - -void printBytesVector(const std::string str, const std::vector& v); - -void printBytesVectorAsHex(const std::vector& v); - -void printBytesVectorAsHex(const std::string str, const std::vector& v); - -void getRandBytes(unsigned char* bytes, int num); - -void convertBytesToVector(const unsigned char* bytes, std::vector& v); - -void convertVectorToBytes(const std::vector& v, unsigned char* bytes); - -void convertBytesToBytesVector(const unsigned char* bytes, std::vector& v); - -void convertBytesVectorToBytes(const std::vector& v, unsigned char* bytes); - -void convertBytesVectorToVector(const std::vector& bytes, std::vector& v); - -void convertVectorToBytesVector(const std::vector& v, std::vector& bytes); - -void convertIntToBytesVector(const uint64_t val_int, std::vector& bytes); - -uint64_t convertBytesVectorToInt(const std::vector& bytes); - -void concatenateVectors(const std::vector& A, const std::vector& B, std::vector& result); - -void concatenateVectors(const std::vector& A, const std::vector& B, std::vector& result); - -void concatenateVectors(const std::vector& A, const std::vector& B, const std::vector& C, std::vector& result); - -void concatenateVectors(const std::vector& A, const std::vector& B, const std::vector& C, std::vector& result); - -void sha256(unsigned char* input, unsigned char* hash, int len); - -void sha256(SHA256_CTX_mod* ctx256, unsigned char* input, unsigned char* hash, int len); - -void hashVector(SHA256_CTX_mod* ctx256, const std::vector input, std::vector& output); - -void hashVector(SHA256_CTX_mod* ctx256, const std::vector input, std::vector& output); - -void hashVector(const std::vector input, std::vector& output); - -void hashVector(const std::vector input, std::vector& output); - -void hashVectors(SHA256_CTX_mod* ctx256, const std::vector left, const std::vector right, std::vector& output); - -void hashVectors(SHA256_CTX_mod* ctx256, const std::vector left, const std::vector right, std::vector& output); - -void hashVectors(const std::vector left, const std::vector right, std::vector& output); - -void hashVectors(const std::vector left, const std::vector right, std::vector& output); - -bool VectorIsZero(const std::vector test); - -#endif /* UTIL_H_ */ - - diff --git a/privacy/zsl/utils/byteswap.h b/privacy/zsl/utils/byteswap.h deleted file mode 100644 index 899220b..0000000 --- a/privacy/zsl/utils/byteswap.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2014 The Bitcoin developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef BITCOIN_COMPAT_BYTESWAP_H -#define BITCOIN_COMPAT_BYTESWAP_H - -#if defined(HAVE_CONFIG_H) -#include "config/bitcoin-config.h" -#endif - -#include - -#if defined(HAVE_BYTESWAP_H) -#include -#endif - -#if HAVE_DECL_BSWAP_16 == 0 -inline uint16_t bswap_16(uint16_t x) -{ - return (x >> 8) | ((x & 0x00ff) << 8); -} -#endif // HAVE_DECL_BSWAP16 - -#if HAVE_DECL_BSWAP_32 == 0 -inline uint32_t bswap_32(uint32_t x) -{ - return (((x & 0xff000000U) >> 24) | ((x & 0x00ff0000U) >> 8) | - ((x & 0x0000ff00U) << 8) | ((x & 0x000000ffU) << 24)); -} -#endif // HAVE_DECL_BSWAP32 - -#if HAVE_DECL_BSWAP_64 == 0 -inline uint64_t bswap_64(uint64_t x) -{ - return (((x & 0xff00000000000000ull) >> 56) - | ((x & 0x00ff000000000000ull) >> 40) - | ((x & 0x0000ff0000000000ull) >> 24) - | ((x & 0x000000ff00000000ull) >> 8) - | ((x & 0x00000000ff000000ull) << 8) - | ((x & 0x0000000000ff0000ull) << 24) - | ((x & 0x000000000000ff00ull) << 40) - | ((x & 0x00000000000000ffull) << 56)); -} -#endif // HAVE_DECL_BSWAP64 - -#endif // BITCOIN_COMPAT_BYTESWAP_H diff --git a/privacy/zsl/utils/tinyformat.h b/privacy/zsl/utils/tinyformat.h deleted file mode 100644 index 57f7672..0000000 --- a/privacy/zsl/utils/tinyformat.h +++ /dev/null @@ -1,1049 +0,0 @@ -// tinyformat.h -// Copyright (C) 2011, Chris Foster [chris42f (at) gmail (d0t) com] -// -// Boost Software License - Version 1.0 -// -// Permission is hereby granted, free of charge, to any person or organization -// obtaining a copy of the software and accompanying documentation covered by -// this license (the "Software") to use, reproduce, display, distribute, -// execute, and transmit the Software, and to prepare derivative works of the -// Software, and to permit third-parties to whom the Software is furnished to -// do so, all subject to the following: -// -// The copyright notices in the Software and this entire statement, including -// the above license grant, this restriction and the following disclaimer, -// must be included in all copies of the Software, in whole or in part, and -// all derivative works of the Software, unless such copies or derivative -// works are solely in the form of machine-executable object code generated by -// a source language processor. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - -//------------------------------------------------------------------------------ -// Tinyformat: A minimal type safe printf replacement -// -// tinyformat.h is a type safe printf replacement library in a single C++ -// header file. Design goals include: -// -// * Type safety and extensibility for user defined types. -// * C99 printf() compatibility, to the extent possible using std::ostream -// * Simplicity and minimalism. A single header file to include and distribute -// with your projects. -// * Augment rather than replace the standard stream formatting mechanism -// * C++98 support, with optional C++11 niceties -// -// -// Main interface example usage -// ---------------------------- -// -// To print a date to std::cout: -// -// std::string weekday = "Wednesday"; -// const char* month = "July"; -// size_t day = 27; -// long hour = 14; -// int min = 44; -// -// tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min); -// -// The strange types here emphasize the type safety of the interface; it is -// possible to print a std::string using the "%s" conversion, and a -// size_t using the "%d" conversion. A similar result could be achieved -// using either of the tfm::format() functions. One prints on a user provided -// stream: -// -// tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n", -// weekday, month, day, hour, min); -// -// The other returns a std::string: -// -// std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n", -// weekday, month, day, hour, min); -// std::cout << date; -// -// These are the three primary interface functions. There is also a -// convenience function printfln() which appends a newline to the usual result -// of printf() for super simple logging. -// -// -// User defined format functions -// ----------------------------- -// -// Simulating variadic templates in C++98 is pretty painful since it requires -// writing out the same function for each desired number of arguments. To make -// this bearable tinyformat comes with a set of macros which are used -// internally to generate the API, but which may also be used in user code. -// -// The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and -// TINYFORMAT_PASSARGS(n) will generate a list of n argument types, -// type/name pairs and argument names respectively when called with an integer -// n between 1 and 16. We can use these to define a macro which generates the -// desired user defined function with n arguments. To generate all 16 user -// defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM. For an -// example, see the implementation of printf() at the end of the source file. -// -// Sometimes it's useful to be able to pass a list of format arguments through -// to a non-template function. The FormatList class is provided as a way to do -// this by storing the argument list in a type-opaque way. Continuing the -// example from above, we construct a FormatList using makeFormatList(): -// -// FormatListRef formatList = tfm::makeFormatList(weekday, month, day, hour, min); -// -// The format list can now be passed into any non-template function and used -// via a call to the vformat() function: -// -// tfm::vformat(std::cout, "%s, %s %d, %.2d:%.2d\n", formatList); -// -// -// Additional API information -// -------------------------- -// -// Error handling: Define TINYFORMAT_ERROR to customize the error handling for -// format strings which are unsupported or have the wrong number of format -// specifiers (calls assert() by default). -// -// User defined types: Uses operator<< for user defined types by default. -// Overload formatValue() for more control. - - -#ifndef TINYFORMAT_H_INCLUDED -#define TINYFORMAT_H_INCLUDED - -namespace tinyformat {} -//------------------------------------------------------------------------------ -// Config section. Customize to your liking! - -// Namespace alias to encourage brevity -namespace tfm = tinyformat; - -// Error handling; calls assert() by default. -#define TINYFORMAT_ERROR(reasonString) throw std::runtime_error(reasonString) - -// Define for C++11 variadic templates which make the code shorter & more -// general. If you don't define this, C++11 support is autodetected below. -// #define TINYFORMAT_USE_VARIADIC_TEMPLATES - - -//------------------------------------------------------------------------------ -// Implementation details. -#include -#include -#include -#include -#include - -#ifndef TINYFORMAT_ERROR -# define TINYFORMAT_ERROR(reason) assert(0 && reason) -#endif - -#if !defined(TINYFORMAT_USE_VARIADIC_TEMPLATES) && !defined(TINYFORMAT_NO_VARIADIC_TEMPLATES) -# ifdef __GXX_EXPERIMENTAL_CXX0X__ -# define TINYFORMAT_USE_VARIADIC_TEMPLATES -# endif -#endif - -#if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201 -// std::showpos is broken on old libstdc++ as provided with OSX. See -// http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html -# define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND -#endif - -#ifdef __APPLE__ -// Workaround macOS linker warning: Xcode uses different default symbol -// visibilities for static libs vs executables (see issue #25) -# define TINYFORMAT_HIDDEN __attribute__((visibility("hidden"))) -#else -# define TINYFORMAT_HIDDEN -#endif - -namespace tinyformat { - -//------------------------------------------------------------------------------ -namespace detail { - -// Test whether type T1 is convertible to type T2 -template -struct is_convertible -{ - private: - // two types of different size - struct fail { char dummy[2]; }; - struct succeed { char dummy; }; - // Try to convert a T1 to a T2 by plugging into tryConvert - static fail tryConvert(...); - static succeed tryConvert(const T2&); - static const T1& makeT1(); - public: -# ifdef _MSC_VER - // Disable spurious loss of precision warnings in tryConvert(makeT1()) -# pragma warning(push) -# pragma warning(disable:4244) -# pragma warning(disable:4267) -# endif - // Standard trick: the (...) version of tryConvert will be chosen from - // the overload set only if the version taking a T2 doesn't match. - // Then we compare the sizes of the return types to check which - // function matched. Very neat, in a disgusting kind of way :) - static const bool value = - sizeof(tryConvert(makeT1())) == sizeof(succeed); -# ifdef _MSC_VER -# pragma warning(pop) -# endif -}; - - -// Detect when a type is not a wchar_t string -template struct is_wchar { typedef int tinyformat_wchar_is_not_supported; }; -template<> struct is_wchar {}; -template<> struct is_wchar {}; -template struct is_wchar {}; -template struct is_wchar {}; - - -// Format the value by casting to type fmtT. This default implementation -// should never be called. -template::value> -struct formatValueAsType -{ - static void invoke(std::ostream& /*out*/, const T& /*value*/) { assert(0); } -}; -// Specialized version for types that can actually be converted to fmtT, as -// indicated by the "convertible" template parameter. -template -struct formatValueAsType -{ - static void invoke(std::ostream& out, const T& value) - { out << static_cast(value); } -}; - -#ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND -template::value> -struct formatZeroIntegerWorkaround -{ - static bool invoke(std::ostream& /**/, const T& /**/) { return false; } -}; -template -struct formatZeroIntegerWorkaround -{ - static bool invoke(std::ostream& out, const T& value) - { - if (static_cast(value) == 0 && out.flags() & std::ios::showpos) - { - out << "+0"; - return true; - } - return false; - } -}; -#endif // TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND - -// Convert an arbitrary type to integer. The version with convertible=false -// throws an error. -template::value> -struct convertToInt -{ - static int invoke(const T& /*value*/) - { - TINYFORMAT_ERROR("tinyformat: Cannot convert from argument type to " - "integer for use as variable width or precision"); - return 0; - } -}; -// Specialization for convertToInt when conversion is possible -template -struct convertToInt -{ - static int invoke(const T& value) { return static_cast(value); } -}; - -// Format at most ntrunc characters to the given stream. -template -inline void formatTruncated(std::ostream& out, const T& value, int ntrunc) -{ - std::ostringstream tmp; - tmp << value; - std::string result = tmp.str(); - out.write(result.c_str(), (std::min)(ntrunc, static_cast(result.size()))); -} -#define TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(type) \ -inline void formatTruncated(std::ostream& out, type* value, int ntrunc) \ -{ \ - std::streamsize len = 0; \ - while(len < ntrunc && value[len] != 0) \ - ++len; \ - out.write(value, len); \ -} -// Overload for const char* and char*. Could overload for signed & unsigned -// char too, but these are technically unneeded for printf compatibility. -TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(const char) -TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(char) -#undef TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR - -} // namespace detail - - -//------------------------------------------------------------------------------ -// Variable formatting functions. May be overridden for user-defined types if -// desired. - - -/// Format a value into a stream, delegating to operator<< by default. -/// -/// Users may override this for their own types. When this function is called, -/// the stream flags will have been modified according to the format string. -/// The format specification is provided in the range [fmtBegin, fmtEnd). For -/// truncating conversions, ntrunc is set to the desired maximum number of -/// characters, for example "%.7s" calls formatValue with ntrunc = 7. -/// -/// By default, formatValue() uses the usual stream insertion operator -/// operator<< to format the type T, with special cases for the %c and %p -/// conversions. -template -inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, - const char* fmtEnd, int ntrunc, const T& value) -{ -#ifndef TINYFORMAT_ALLOW_WCHAR_STRINGS - // Since we don't support printing of wchar_t using "%ls", make it fail at - // compile time in preference to printing as a void* at runtime. - typedef typename detail::is_wchar::tinyformat_wchar_is_not_supported DummyType; - (void) DummyType(); // avoid unused type warning with gcc-4.8 -#endif - // The mess here is to support the %c and %p conversions: if these - // conversions are active we try to convert the type to a char or const - // void* respectively and format that instead of the value itself. For the - // %p conversion it's important to avoid dereferencing the pointer, which - // could otherwise lead to a crash when printing a dangling (const char*). - const bool canConvertToChar = detail::is_convertible::value; - const bool canConvertToVoidPtr = detail::is_convertible::value; - if(canConvertToChar && *(fmtEnd-1) == 'c') - detail::formatValueAsType::invoke(out, value); - else if(canConvertToVoidPtr && *(fmtEnd-1) == 'p') - detail::formatValueAsType::invoke(out, value); -#ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND - else if(detail::formatZeroIntegerWorkaround::invoke(out, value)) /**/; -#endif - else if(ntrunc >= 0) - { - // Take care not to overread C strings in truncating conversions like - // "%.4s" where at most 4 characters may be read. - detail::formatTruncated(out, value, ntrunc); - } - else - out << value; -} - - -// Overloaded version for char types to support printing as an integer -#define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType) \ -inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, \ - const char* fmtEnd, int /**/, charType value) \ -{ \ - switch(*(fmtEnd-1)) \ - { \ - case 'u': case 'd': case 'i': case 'o': case 'X': case 'x': \ - out << static_cast(value); break; \ - default: \ - out << value; break; \ - } \ -} -// per 3.9.1: char, signed char and unsigned char are all distinct types -TINYFORMAT_DEFINE_FORMATVALUE_CHAR(char) -TINYFORMAT_DEFINE_FORMATVALUE_CHAR(signed char) -TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char) -#undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR - - -//------------------------------------------------------------------------------ -// Tools for emulating variadic templates in C++98. The basic idea here is -// stolen from the boost preprocessor metaprogramming library and cut down to -// be just general enough for what we need. - -#define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_ ## n -#define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_ ## n -#define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_ ## n -#define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_ ## n - -// To keep it as transparent as possible, the macros below have been generated -// using python via the excellent cog.py code generation script. This avoids -// the need for a bunch of complex (but more general) preprocessor tricks as -// used in boost.preprocessor. -// -// To rerun the code generation in place, use `cog.py -r tinyformat.h` -// (see http://nedbatchelder.com/code/cog). Alternatively you can just create -// extra versions by hand. - -/*[[[cog -maxParams = 16 - -def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1): - for j in range(startInd,maxParams+1): - list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)]) - cog.outl(lineTemplate % {'j':j, 'list':list}) - -makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s', - 'class T%(i)d') - -cog.outl() -makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s', - 'const T%(i)d& v%(i)d') - -cog.outl() -makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d') - -cog.outl() -cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1') -makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s', - 'v%(i)d', startInd = 2) - -cog.outl() -cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n ' + - ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)])) -]]]*/ -#define TINYFORMAT_ARGTYPES_1 class T1 -#define TINYFORMAT_ARGTYPES_2 class T1, class T2 -#define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3 -#define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4 -#define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5 -#define TINYFORMAT_ARGTYPES_6 class T1, class T2, class T3, class T4, class T5, class T6 -#define TINYFORMAT_ARGTYPES_7 class T1, class T2, class T3, class T4, class T5, class T6, class T7 -#define TINYFORMAT_ARGTYPES_8 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8 -#define TINYFORMAT_ARGTYPES_9 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9 -#define TINYFORMAT_ARGTYPES_10 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10 -#define TINYFORMAT_ARGTYPES_11 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11 -#define TINYFORMAT_ARGTYPES_12 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12 -#define TINYFORMAT_ARGTYPES_13 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13 -#define TINYFORMAT_ARGTYPES_14 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14 -#define TINYFORMAT_ARGTYPES_15 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 -#define TINYFORMAT_ARGTYPES_16 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16 - -#define TINYFORMAT_VARARGS_1 const T1& v1 -#define TINYFORMAT_VARARGS_2 const T1& v1, const T2& v2 -#define TINYFORMAT_VARARGS_3 const T1& v1, const T2& v2, const T3& v3 -#define TINYFORMAT_VARARGS_4 const T1& v1, const T2& v2, const T3& v3, const T4& v4 -#define TINYFORMAT_VARARGS_5 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5 -#define TINYFORMAT_VARARGS_6 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6 -#define TINYFORMAT_VARARGS_7 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7 -#define TINYFORMAT_VARARGS_8 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8 -#define TINYFORMAT_VARARGS_9 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9 -#define TINYFORMAT_VARARGS_10 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10 -#define TINYFORMAT_VARARGS_11 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11 -#define TINYFORMAT_VARARGS_12 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12 -#define TINYFORMAT_VARARGS_13 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13 -#define TINYFORMAT_VARARGS_14 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14 -#define TINYFORMAT_VARARGS_15 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15 -#define TINYFORMAT_VARARGS_16 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15, const T16& v16 - -#define TINYFORMAT_PASSARGS_1 v1 -#define TINYFORMAT_PASSARGS_2 v1, v2 -#define TINYFORMAT_PASSARGS_3 v1, v2, v3 -#define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4 -#define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5 -#define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6 -#define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7 -#define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8 -#define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9 -#define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 -#define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 -#define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 -#define TINYFORMAT_PASSARGS_13 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13 -#define TINYFORMAT_PASSARGS_14 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14 -#define TINYFORMAT_PASSARGS_15 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 -#define TINYFORMAT_PASSARGS_16 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 - -#define TINYFORMAT_PASSARGS_TAIL_1 -#define TINYFORMAT_PASSARGS_TAIL_2 , v2 -#define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3 -#define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4 -#define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5 -#define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6 -#define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7 -#define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8 -#define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9 -#define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10 -#define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 -#define TINYFORMAT_PASSARGS_TAIL_12 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 -#define TINYFORMAT_PASSARGS_TAIL_13 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13 -#define TINYFORMAT_PASSARGS_TAIL_14 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14 -#define TINYFORMAT_PASSARGS_TAIL_15 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 -#define TINYFORMAT_PASSARGS_TAIL_16 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 - -#define TINYFORMAT_FOREACH_ARGNUM(m) \ - m(1) m(2) m(3) m(4) m(5) m(6) m(7) m(8) m(9) m(10) m(11) m(12) m(13) m(14) m(15) m(16) -//[[[end]]] - - - -namespace detail { - -// Type-opaque holder for an argument to format(), with associated actions on -// the type held as explicit function pointers. This allows FormatArg's for -// each argument to be allocated as a homogenous array inside FormatList -// whereas a naive implementation based on inheritance does not. -class FormatArg -{ - public: - FormatArg() {} - - template - FormatArg(const T& value) - : m_value(static_cast(&value)), - m_formatImpl(&formatImpl), - m_toIntImpl(&toIntImpl) - { } - - void format(std::ostream& out, const char* fmtBegin, - const char* fmtEnd, int ntrunc) const - { - m_formatImpl(out, fmtBegin, fmtEnd, ntrunc, m_value); - } - - int toInt() const - { - return m_toIntImpl(m_value); - } - - private: - template - TINYFORMAT_HIDDEN static void formatImpl(std::ostream& out, const char* fmtBegin, - const char* fmtEnd, int ntrunc, const void* value) - { - formatValue(out, fmtBegin, fmtEnd, ntrunc, *static_cast(value)); - } - - template - TINYFORMAT_HIDDEN static int toIntImpl(const void* value) - { - return convertToInt::invoke(*static_cast(value)); - } - - const void* m_value; - void (*m_formatImpl)(std::ostream& out, const char* fmtBegin, - const char* fmtEnd, int ntrunc, const void* value); - int (*m_toIntImpl)(const void* value); -}; - - -// Parse and return an integer from the string c, as atoi() -// On return, c is set to one past the end of the integer. -inline int parseIntAndAdvance(const char*& c) -{ - int i = 0; - for(;*c >= '0' && *c <= '9'; ++c) - i = 10*i + (*c - '0'); - return i; -} - -// Print literal part of format string and return next format spec -// position. -// -// Skips over any occurrences of '%%', printing a literal '%' to the -// output. The position of the first % character of the next -// nontrivial format spec is returned, or the end of string. -inline const char* printFormatStringLiteral(std::ostream& out, const char* fmt) -{ - const char* c = fmt; - for(;; ++c) - { - switch(*c) - { - case '\0': - out.write(fmt, c - fmt); - return c; - case '%': - out.write(fmt, c - fmt); - if(*(c+1) != '%') - return c; - // for "%%", tack trailing % onto next literal section. - fmt = ++c; - break; - default: - break; - } - } -} - - -// Parse a format string and set the stream state accordingly. -// -// The format mini-language recognized here is meant to be the one from C99, -// with the form "%[flags][width][.precision][length]type". -// -// Formatting options which can't be natively represented using the ostream -// state are returned in spacePadPositive (for space padded positive numbers) -// and ntrunc (for truncating conversions). argIndex is incremented if -// necessary to pull out variable width and precision. The function returns a -// pointer to the character after the end of the current format spec. -inline const char* streamStateFromFormat(std::ostream& out, bool& spacePadPositive, - int& ntrunc, const char* fmtStart, - const detail::FormatArg* formatters, - int& argIndex, int numFormatters) -{ - if(*fmtStart != '%') - { - TINYFORMAT_ERROR("tinyformat: Not enough conversion specifiers in format string"); - return fmtStart; - } - // Reset stream state to defaults. - out.width(0); - out.precision(6); - out.fill(' '); - // Reset most flags; ignore irrelevant unitbuf & skipws. - out.unsetf(std::ios::adjustfield | std::ios::basefield | - std::ios::floatfield | std::ios::showbase | std::ios::boolalpha | - std::ios::showpoint | std::ios::showpos | std::ios::uppercase); - bool precisionSet = false; - bool widthSet = false; - int widthExtra = 0; - const char* c = fmtStart + 1; - // 1) Parse flags - for(;; ++c) - { - switch(*c) - { - case '#': - out.setf(std::ios::showpoint | std::ios::showbase); - continue; - case '0': - // overridden by left alignment ('-' flag) - if(!(out.flags() & std::ios::left)) - { - // Use internal padding so that numeric values are - // formatted correctly, eg -00010 rather than 000-10 - out.fill('0'); - out.setf(std::ios::internal, std::ios::adjustfield); - } - continue; - case '-': - out.fill(' '); - out.setf(std::ios::left, std::ios::adjustfield); - continue; - case ' ': - // overridden by show positive sign, '+' flag. - if(!(out.flags() & std::ios::showpos)) - spacePadPositive = true; - continue; - case '+': - out.setf(std::ios::showpos); - spacePadPositive = false; - widthExtra = 1; - continue; - default: - break; - } - break; - } - // 2) Parse width - if(*c >= '0' && *c <= '9') - { - widthSet = true; - out.width(parseIntAndAdvance(c)); - } - if(*c == '*') - { - widthSet = true; - int width = 0; - if(argIndex < numFormatters) - width = formatters[argIndex++].toInt(); - else - TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable width"); - if(width < 0) - { - // negative widths correspond to '-' flag set - out.fill(' '); - out.setf(std::ios::left, std::ios::adjustfield); - width = -width; - } - out.width(width); - ++c; - } - // 3) Parse precision - if(*c == '.') - { - ++c; - int precision = 0; - if(*c == '*') - { - ++c; - if(argIndex < numFormatters) - precision = formatters[argIndex++].toInt(); - else - TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable precision"); - } - else - { - if(*c >= '0' && *c <= '9') - precision = parseIntAndAdvance(c); - else if(*c == '-') // negative precisions ignored, treated as zero. - parseIntAndAdvance(++c); - } - out.precision(precision); - precisionSet = true; - } - // 4) Ignore any C99 length modifier - while(*c == 'l' || *c == 'h' || *c == 'L' || - *c == 'j' || *c == 'z' || *c == 't') - ++c; - // 5) We're up to the conversion specifier character. - // Set stream flags based on conversion specifier (thanks to the - // boost::format class for forging the way here). - bool intConversion = false; - switch(*c) - { - case 'u': case 'd': case 'i': - out.setf(std::ios::dec, std::ios::basefield); - intConversion = true; - break; - case 'o': - out.setf(std::ios::oct, std::ios::basefield); - intConversion = true; - break; - case 'X': - out.setf(std::ios::uppercase); - case 'x': case 'p': - out.setf(std::ios::hex, std::ios::basefield); - intConversion = true; - break; - case 'E': - out.setf(std::ios::uppercase); - case 'e': - out.setf(std::ios::scientific, std::ios::floatfield); - out.setf(std::ios::dec, std::ios::basefield); - break; - case 'F': - out.setf(std::ios::uppercase); - case 'f': - out.setf(std::ios::fixed, std::ios::floatfield); - break; - case 'G': - out.setf(std::ios::uppercase); - case 'g': - out.setf(std::ios::dec, std::ios::basefield); - // As in boost::format, let stream decide float format. - out.flags(out.flags() & ~std::ios::floatfield); - break; - case 'a': case 'A': - TINYFORMAT_ERROR("tinyformat: the %a and %A conversion specs " - "are not supported"); - break; - case 'c': - // Handled as special case inside formatValue() - break; - case 's': - if(precisionSet) - ntrunc = static_cast(out.precision()); - // Make %s print booleans as "true" and "false" - out.setf(std::ios::boolalpha); - break; - case 'n': - // Not supported - will cause problems! - TINYFORMAT_ERROR("tinyformat: %n conversion spec not supported"); - break; - case '\0': - TINYFORMAT_ERROR("tinyformat: Conversion spec incorrectly " - "terminated by end of string"); - return c; - default: - break; - } - if(intConversion && precisionSet && !widthSet) - { - // "precision" for integers gives the minimum number of digits (to be - // padded with zeros on the left). This isn't really supported by the - // iostreams, but we can approximately simulate it with the width if - // the width isn't otherwise used. - out.width(out.precision() + widthExtra); - out.setf(std::ios::internal, std::ios::adjustfield); - out.fill('0'); - } - return c+1; -} - - -//------------------------------------------------------------------------------ -inline void formatImpl(std::ostream& out, const char* fmt, - const detail::FormatArg* formatters, - int numFormatters) -{ - // Saved stream state - std::streamsize origWidth = out.width(); - std::streamsize origPrecision = out.precision(); - std::ios::fmtflags origFlags = out.flags(); - char origFill = out.fill(); - - for (int argIndex = 0; argIndex < numFormatters; ++argIndex) - { - // Parse the format string - fmt = printFormatStringLiteral(out, fmt); - bool spacePadPositive = false; - int ntrunc = -1; - const char* fmtEnd = streamStateFromFormat(out, spacePadPositive, ntrunc, fmt, - formatters, argIndex, numFormatters); - if (argIndex >= numFormatters) - { - // Check args remain after reading any variable width/precision - TINYFORMAT_ERROR("tinyformat: Not enough format arguments"); - return; - } - const FormatArg& arg = formatters[argIndex]; - // Format the arg into the stream. - if(!spacePadPositive) - arg.format(out, fmt, fmtEnd, ntrunc); - else - { - // The following is a special case with no direct correspondence - // between stream formatting and the printf() behaviour. Simulate - // it crudely by formatting into a temporary string stream and - // munging the resulting string. - std::ostringstream tmpStream; - tmpStream.copyfmt(out); - tmpStream.setf(std::ios::showpos); - arg.format(tmpStream, fmt, fmtEnd, ntrunc); - std::string result = tmpStream.str(); // allocates... yuck. - for(size_t i = 0, iend = result.size(); i < iend; ++i) - if(result[i] == '+') result[i] = ' '; - out << result; - } - fmt = fmtEnd; - } - - // Print remaining part of format string. - fmt = printFormatStringLiteral(out, fmt); - if(*fmt != '\0') - TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string"); - - // Restore stream state - out.width(origWidth); - out.precision(origPrecision); - out.flags(origFlags); - out.fill(origFill); -} - -} // namespace detail - - -/// List of template arguments format(), held in a type-opaque way. -/// -/// A const reference to FormatList (typedef'd as FormatListRef) may be -/// conveniently used to pass arguments to non-template functions: All type -/// information has been stripped from the arguments, leaving just enough of a -/// common interface to perform formatting as required. -class FormatList -{ - public: - FormatList(detail::FormatArg* formatters, int N) - : m_formatters(formatters), m_N(N) { } - - friend void vformat(std::ostream& out, const char* fmt, - const FormatList& list); - - private: - const detail::FormatArg* m_formatters; - int m_N; -}; - -/// Reference to type-opaque format list for passing to vformat() -typedef const FormatList& FormatListRef; - - -namespace detail { - -// Format list subclass with fixed storage to avoid dynamic allocation -template -class FormatListN : public FormatList -{ - public: -#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES - template - FormatListN(const Args&... args) - : FormatList(&m_formatterStore[0], N), - m_formatterStore { FormatArg(args)... } - { static_assert(sizeof...(args) == N, "Number of args must be N"); } -#else // C++98 version - void init(int) {} -# define TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR(n) \ - \ - template \ - FormatListN(TINYFORMAT_VARARGS(n)) \ - : FormatList(&m_formatterStore[0], n) \ - { assert(n == N); init(0, TINYFORMAT_PASSARGS(n)); } \ - \ - template \ - void init(int i, TINYFORMAT_VARARGS(n)) \ - { \ - m_formatterStore[i] = FormatArg(v1); \ - init(i+1 TINYFORMAT_PASSARGS_TAIL(n)); \ - } - - TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR) -# undef TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR -#endif - - private: - FormatArg m_formatterStore[N]; -}; - -// Special 0-arg version - MSVC says zero-sized C array in struct is nonstandard -template<> class FormatListN<0> : public FormatList -{ - public: FormatListN() : FormatList(0, 0) {} -}; - -} // namespace detail - - -//------------------------------------------------------------------------------ -// Primary API functions - -#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES - -/// Make type-agnostic format list from list of template arguments. -/// -/// The exact return type of this function is an implementation detail and -/// shouldn't be relied upon. Instead it should be stored as a FormatListRef: -/// -/// FormatListRef formatList = makeFormatList( /*...*/ ); -template -detail::FormatListN makeFormatList(const Args&... args) -{ - return detail::FormatListN(args...); -} - -#else // C++98 version - -inline detail::FormatListN<0> makeFormatList() -{ - return detail::FormatListN<0>(); -} -#define TINYFORMAT_MAKE_MAKEFORMATLIST(n) \ -template \ -detail::FormatListN makeFormatList(TINYFORMAT_VARARGS(n)) \ -{ \ - return detail::FormatListN(TINYFORMAT_PASSARGS(n)); \ -} -TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_MAKEFORMATLIST) -#undef TINYFORMAT_MAKE_MAKEFORMATLIST - -#endif - -/// Format list of arguments to the stream according to the given format string. -/// -/// The name vformat() is chosen for the semantic similarity to vprintf(): the -/// list of format arguments is held in a single function argument. -inline void vformat(std::ostream& out, const char* fmt, FormatListRef list) -{ - detail::formatImpl(out, fmt, list.m_formatters, list.m_N); -} - - -#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES - -/// Format list of arguments to the stream according to given format string. -template -void format(std::ostream& out, const char* fmt, const Args&... args) -{ - vformat(out, fmt, makeFormatList(args...)); -} - -/// Format list of arguments according to the given format string and return -/// the result as a string. -template -std::string format(const char* fmt, const Args&... args) -{ - std::ostringstream oss; - format(oss, fmt, args...); - return oss.str(); -} - -/// Format list of arguments to std::cout, according to the given format string -template -void printf(const char* fmt, const Args&... args) -{ - format(std::cout, fmt, args...); -} - -template -void printfln(const char* fmt, const Args&... args) -{ - format(std::cout, fmt, args...); - std::cout << '\n'; -} - -#else // C++98 version - -inline void format(std::ostream& out, const char* fmt) -{ - vformat(out, fmt, makeFormatList()); -} - -inline std::string format(const char* fmt) -{ - std::ostringstream oss; - format(oss, fmt); - return oss.str(); -} - -inline void printf(const char* fmt) -{ - format(std::cout, fmt); -} - -inline void printfln(const char* fmt) -{ - format(std::cout, fmt); - std::cout << '\n'; -} - -#define TINYFORMAT_MAKE_FORMAT_FUNCS(n) \ - \ -template \ -void format(std::ostream& out, const char* fmt, TINYFORMAT_VARARGS(n)) \ -{ \ - vformat(out, fmt, makeFormatList(TINYFORMAT_PASSARGS(n))); \ -} \ - \ -template \ -std::string format(const char* fmt, TINYFORMAT_VARARGS(n)) \ -{ \ - std::ostringstream oss; \ - format(oss, fmt, TINYFORMAT_PASSARGS(n)); \ - return oss.str(); \ -} \ - \ -template \ -void printf(const char* fmt, TINYFORMAT_VARARGS(n)) \ -{ \ - format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \ -} \ - \ -template \ -void printfln(const char* fmt, TINYFORMAT_VARARGS(n)) \ -{ \ - format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \ - std::cout << '\n'; \ -} - -TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS) -#undef TINYFORMAT_MAKE_FORMAT_FUNCS - -#endif - -// Added for Bitcoin Core -template -std::string format(const std::string &fmt, const Args&... args) -{ - std::ostringstream oss; - format(oss, fmt.c_str(), args...); - return oss.str(); -} - -} // namespace tinyformat - -#define strprintf tfm::format - -#endif // TINYFORMAT_H_INCLUDED diff --git a/privacy/zsl/utils/uint256.cpp b/privacy/zsl/utils/uint256.cpp deleted file mode 100644 index 2514880..0000000 --- a/privacy/zsl/utils/uint256.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2014 The Bitcoin Core developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#include "uint256.h" - -#include "utilstrencodings.h" - -#include -#include - -template -base_blob::base_blob(const std::vector& vch) -{ - assert(vch.size() == sizeof(data)); - memcpy(data, &vch[0], sizeof(data)); -} - -template -std::string base_blob::GetHex() const -{ - char psz[sizeof(data) * 2 + 1]; - for (unsigned int i = 0; i < sizeof(data); i++) - sprintf(psz + i * 2, "%02x", data[sizeof(data) - i - 1]); - return std::string(psz, psz + sizeof(data) * 2); -} - -template -void base_blob::SetHex(const char* psz) -{ - memset(data, 0, sizeof(data)); - - // skip leading spaces - while (isspace(*psz)) - psz++; - - // skip 0x - if (psz[0] == '0' && tolower(psz[1]) == 'x') - psz += 2; - - // hex string to uint - const char* pbegin = psz; - while (::HexDigit(*psz) != -1) - psz++; - psz--; - unsigned char* p1 = (unsigned char*)data; - unsigned char* pend = p1 + WIDTH; - while (psz >= pbegin && p1 < pend) { - *p1 = ::HexDigit(*psz--); - if (psz >= pbegin) { - *p1 |= ((unsigned char)::HexDigit(*psz--) << 4); - p1++; - } - } -} - -template -void base_blob::SetHex(const std::string& str) -{ - SetHex(str.c_str()); -} - -template -std::string base_blob::ToString() const -{ - return (GetHex()); -} - -// Explicit instantiations for base_blob<160> -template base_blob<160>::base_blob(const std::vector&); -template std::string base_blob<160>::GetHex() const; -template std::string base_blob<160>::ToString() const; -template void base_blob<160>::SetHex(const char*); -template void base_blob<160>::SetHex(const std::string&); - -// Explicit instantiations for base_blob<256> -template base_blob<256>::base_blob(const std::vector&); -template std::string base_blob<256>::GetHex() const; -template std::string base_blob<256>::ToString() const; -template void base_blob<256>::SetHex(const char*); -template void base_blob<256>::SetHex(const std::string&); - -static void inline HashMix(uint32_t& a, uint32_t& b, uint32_t& c) -{ - // Taken from lookup3, by Bob Jenkins. - a -= c; - a ^= ((c << 4) | (c >> 28)); - c += b; - b -= a; - b ^= ((a << 6) | (a >> 26)); - a += c; - c -= b; - c ^= ((b << 8) | (b >> 24)); - b += a; - a -= c; - a ^= ((c << 16) | (c >> 16)); - c += b; - b -= a; - b ^= ((a << 19) | (a >> 13)); - a += c; - c -= b; - c ^= ((b << 4) | (b >> 28)); - b += a; -} - -static void inline HashFinal(uint32_t& a, uint32_t& b, uint32_t& c) -{ - // Taken from lookup3, by Bob Jenkins. - c ^= b; - c -= ((b << 14) | (b >> 18)); - a ^= c; - a -= ((c << 11) | (c >> 21)); - b ^= a; - b -= ((a << 25) | (a >> 7)); - c ^= b; - c -= ((b << 16) | (b >> 16)); - a ^= c; - a -= ((c << 4) | (c >> 28)); - b ^= a; - b -= ((a << 14) | (a >> 18)); - c ^= b; - c -= ((b << 24) | (b >> 8)); -} - -uint64_t uint256::GetHash(const uint256& salt) const -{ - uint32_t a, b, c; - const uint32_t *pn = (const uint32_t*)data; - const uint32_t *salt_pn = (const uint32_t*)salt.data; - a = b = c = 0xdeadbeef + WIDTH; - - a += pn[0] ^ salt_pn[0]; - b += pn[1] ^ salt_pn[1]; - c += pn[2] ^ salt_pn[2]; - HashMix(a, b, c); - a += pn[3] ^ salt_pn[3]; - b += pn[4] ^ salt_pn[4]; - c += pn[5] ^ salt_pn[5]; - HashMix(a, b, c); - a += pn[6] ^ salt_pn[6]; - b += pn[7] ^ salt_pn[7]; - HashFinal(a, b, c); - - return ((((uint64_t)b) << 32) | c); -} diff --git a/privacy/zsl/utils/uint256.h b/privacy/zsl/utils/uint256.h deleted file mode 100644 index f22a8ba..0000000 --- a/privacy/zsl/utils/uint256.h +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2014 The Bitcoin Core developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef BITCOIN_UINT256_H -#define BITCOIN_UINT256_H - -#include -#include -#include -#include -#include -#include - -/** Template base class for fixed-sized opaque blobs. */ -template -class base_blob -{ -protected: - enum { WIDTH=BITS/8 }; - alignas(uint32_t) uint8_t data[WIDTH]; -public: - base_blob() - { - memset(data, 0, sizeof(data)); - } - - explicit base_blob(const std::vector& vch); - - bool IsNull() const - { - for (int i = 0; i < WIDTH; i++) - if (data[i] != 0) - return false; - return true; - } - - void SetNull() - { - memset(data, 0, sizeof(data)); - } - - friend inline bool operator==(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) == 0; } - friend inline bool operator!=(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) != 0; } - friend inline bool operator<(const base_blob& a, const base_blob& b) { return memcmp(a.data, b.data, sizeof(a.data)) < 0; } - - std::string GetHex() const; - void SetHex(const char* psz); - void SetHex(const std::string& str); - std::string ToString() const; - - unsigned char* begin() - { - return &data[0]; - } - - unsigned char* end() - { - return &data[WIDTH]; - } - - const unsigned char* begin() const - { - return &data[0]; - } - - const unsigned char* end() const - { - return &data[WIDTH]; - } - - unsigned int size() const - { - return sizeof(data); - } - - template - void Serialize(Stream& s) const - { - s.write((char*)data, sizeof(data)); - } - - template - void Unserialize(Stream& s) - { - s.read((char*)data, sizeof(data)); - } -}; - -/** 88-bit opaque blob. - */ -class blob88 : public base_blob<88> { -public: - blob88() {} - blob88(const base_blob<88>& b) : base_blob<88>(b) {} - explicit blob88(const std::vector& vch) : base_blob<88>(vch) {} -}; - -/** 160-bit opaque blob. - * @note This type is called uint160 for historical reasons only. It is an opaque - * blob of 160 bits and has no integer operations. - */ -class uint160 : public base_blob<160> { -public: - uint160() {} - uint160(const base_blob<160>& b) : base_blob<160>(b) {} - explicit uint160(const std::vector& vch) : base_blob<160>(vch) {} -}; - -/** 256-bit opaque blob. - * @note This type is called uint256 for historical reasons only. It is an - * opaque blob of 256 bits and has no integer operations. Use arith_uint256 if - * those are required. - */ -class uint256 : public base_blob<256> { -public: - uint256() {} - uint256(const base_blob<256>& b) : base_blob<256>(b) {} - explicit uint256(const std::vector& vch) : base_blob<256>(vch) {} - - /** A cheap hash function that just returns 64 bits from the result, it can be - * used when the contents are considered uniformly random. It is not appropriate - * when the value can easily be influenced from outside as e.g. a network adversary could - * provide values to trigger worst-case behavior. - * @note The result of this function is not stable between little and big endian. - */ - uint64_t GetCheapHash() const - { - uint64_t result; - memcpy((void*)&result, (void*)data, 8); - return result; - } - - /** A more secure, salted hash function. - * @note This hash is not stable between little and big endian. - */ - uint64_t GetHash(const uint256& salt) const; -}; - -/* uint256 from const char *. - * This is a separate function because the constructor uint256(const char*) can result - * in dangerously catching uint256(0). - */ -inline uint256 uint256S(const char *str) -{ - uint256 rv; - rv.SetHex(str); - return rv; -} -/* uint256 from std::string. - * This is a separate function because the constructor uint256(const std::string &str) can result - * in dangerously catching uint256(0) via std::string(const char*). - */ -inline uint256 uint256S(const std::string& str) -{ - uint256 rv; - rv.SetHex(str); - return rv; -} - -#endif // BITCOIN_UINT256_H diff --git a/privacy/zsl/utils/util.cpp b/privacy/zsl/utils/util.cpp index d89a4d0..3233e1f 100644 --- a/privacy/zsl/utils/util.cpp +++ b/privacy/zsl/utils/util.cpp @@ -79,7 +79,7 @@ std::string sha256_compress(const std::string& a, const std::string& b) { return array_to_hex_str(char_o, 32); } -static std::string BinToHexString(const char *value, int len) { +static std::string bin_to_hex_str(const char *value, int len) { std::string result; result.resize(len * 2); for (size_t i = 0; i < len; i++) { @@ -113,12 +113,19 @@ void get_randomness(std::string &output, int len) { if(urandom) { urandom.read(buf, len); if(urandom) { - output = BinToHexString(buf, len); + output = bin_to_hex_str(buf, len); } urandom.close(); } return; } + +std::string get_randomness() { + std::string rand_str; + get_randomness(rand_str, 32); + return rand_str; +} + void get_randomness(unsigned char *output, int len) { std::string hex_str; get_randomness(hex_str, len); diff --git a/privacy/zsl/utils/util.h b/privacy/zsl/utils/util.h index 9fac5f9..9fd6836 100644 --- a/privacy/zsl/utils/util.h +++ b/privacy/zsl/utils/util.h @@ -11,7 +11,7 @@ std::string to_string(T value) { return os.str(); }*/ -static std::string BinToHexString(const char *value, int len); +static std::string bin_to_hex_str(const char *value, int len); void print_char_array(unsigned char *array, int len); void sha256(unsigned char *str, int len, unsigned char *buf); @@ -26,7 +26,9 @@ template T get_randomness(); void get_randomness(std::string &output, int len); void get_randomness(unsigned char *output, int len); +std::string get_randomness(); void get_keypair(unsigned char *priv, unsigned char *pub); void get_keypair(std::string& priv, std::string& pub); + #endif diff --git a/privacy/zsl/utils/utilstrencodings.cpp b/privacy/zsl/utils/utilstrencodings.cpp deleted file mode 100644 index ece2ec7..0000000 --- a/privacy/zsl/utils/utilstrencodings.cpp +++ /dev/null @@ -1,506 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2014 The Bitcoin Core developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#include "utilstrencodings.h" - -#include "tinyformat.h" - -#include -#include -#include -#include -#include - -using namespace std; - -static const string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - -static const string SAFE_CHARS[] = -{ - CHARS_ALPHA_NUM + " .,;_/:?@()", // SAFE_CHARS_DEFAULT - CHARS_ALPHA_NUM + " .,;_?@" // SAFE_CHARS_UA_COMMENT -}; - -string SanitizeString(const string& str, int rule) -{ - string strResult; - for (std::string::size_type i = 0; i < str.size(); i++) - { - if (SAFE_CHARS[rule].find(str[i]) != std::string::npos) - strResult.push_back(str[i]); - } - return strResult; -} - -string SanitizeFilename(const string& str) -{ - /** - * safeChars chosen to restrict filename, keeping it simple to avoid cross-platform issues. - * http://stackoverflow.com/a/2306003 - */ - static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890"); - string strResult; - for (std::string::size_type i = 0; i < str.size(); i++) - { - if (safeChars.find(str[i]) != std::string::npos) - strResult.push_back(str[i]); - } - return strResult; -} - -std::string HexInt(uint32_t val) -{ - std::stringstream ss; - ss << std::setfill('0') << std::setw(sizeof(uint32_t) * 2) << std::hex << val; - return ss.str(); -} - -uint32_t ParseHexToUInt32(const std::string& str) { - std::istringstream converter(str); - uint32_t value; - converter >> std::hex >> value; - return value; -} - -const signed char p_util_hexdigit[256] = -{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1, - -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, }; - -signed char HexDigit(char c) -{ - return p_util_hexdigit[(unsigned char)c]; -} - -bool IsHex(const string& str) -{ - for(std::string::const_iterator it(str.begin()); it != str.end(); ++it) - { - if (HexDigit(*it) < 0) - return false; - } - return (str.size() > 0) && (str.size()%2 == 0); -} - -vector ParseHex(const char* psz) -{ - // convert hex dump to vector - vector vch; - while (true) - { - while (isspace(*psz)) - psz++; - signed char c = HexDigit(*psz++); - if (c == (signed char)-1) - break; - unsigned char n = (c << 4); - c = HexDigit(*psz++); - if (c == (signed char)-1) - break; - n |= c; - vch.push_back(n); - } - return vch; -} - -vector ParseHex(const string& str) -{ - return ParseHex(str.c_str()); -} - -string EncodeBase64(const unsigned char* pch, size_t len) -{ - static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - std::string str; - str.reserve(((len + 2) / 3) * 4); - ConvertBits<8, 6, true>([&](int v) { str += pbase64[v]; }, pch, pch + len); - while (str.size() % 4) str += '='; - return str; -} - -string EncodeBase64(const string& str) -{ - return EncodeBase64((const unsigned char*)str.c_str(), str.size()); -} - -vector DecodeBase64(const char* p, bool* pfInvalid) -{ - static const int decode64_table[256] = - { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, - -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 26, 27, 28, - 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - }; - - const char* e = p; - std::vector val; - val.reserve(strlen(p)); - while (*p != 0) { - int x = decode64_table[(unsigned char)*p]; - if (x == -1) break; - val.push_back(x); - ++p; - } - - std::vector ret; - ret.reserve((val.size() * 3) / 4); - bool valid = ConvertBits<6, 8, false>([&](unsigned char c) { ret.push_back(c); }, val.begin(), val.end()); - - const char* q = p; - while (valid && *p != 0) { - if (*p != '=') { - valid = false; - break; - } - ++p; - } - valid = valid && (p - e) % 4 == 0 && p - q < 4; - if (pfInvalid) *pfInvalid = !valid; - - return ret; -} - -string DecodeBase64(const string& str) -{ - vector vchRet = DecodeBase64(str.c_str()); - return (vchRet.size() == 0) ? string() : string((const char*)&vchRet[0], vchRet.size()); -} - -string EncodeBase32(const unsigned char* pch, size_t len) -{ - static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; - - std::string str; - str.reserve(((len + 4) / 5) * 8); - ConvertBits<8, 5, true>([&](int v) { str += pbase32[v]; }, pch, pch + len); - while (str.size() % 8) str += '='; - return str; -} - -string EncodeBase32(const string& str) -{ - return EncodeBase32((const unsigned char*)str.c_str(), str.size()); -} - -vector DecodeBase32(const char* p, bool* pfInvalid) -{ - static const int decode32_table[256] = - { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - }; - - const char* e = p; - std::vector val; - val.reserve(strlen(p)); - while (*p != 0) { - int x = decode32_table[(unsigned char)*p]; - if (x == -1) break; - val.push_back(x); - ++p; - } - - std::vector ret; - ret.reserve((val.size() * 5) / 8); - bool valid = ConvertBits<5, 8, false>([&](unsigned char c) { ret.push_back(c); }, val.begin(), val.end()); - - const char* q = p; - while (valid && *p != 0) { - if (*p != '=') { - valid = false; - break; - } - ++p; - } - valid = valid && (p - e) % 8 == 0 && p - q < 8; - if (pfInvalid) *pfInvalid = !valid; - - return ret; -} - -string DecodeBase32(const string& str) -{ - vector vchRet = DecodeBase32(str.c_str()); - return (vchRet.size() == 0) ? string() : string((const char*)&vchRet[0], vchRet.size()); -} - -static bool ParsePrechecks(const std::string& str) -{ - if (str.empty()) // No empty string allowed - return false; - if (str.size() >= 1 && (isspace(str[0]) || isspace(str[str.size()-1]))) // No padding allowed - return false; - if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed - return false; - return true; -} - -bool ParseInt32(const std::string& str, int32_t *out) -{ - if (!ParsePrechecks(str)) - return false; - char *endp = NULL; - errno = 0; // strtol will not set errno if valid - long int n = strtol(str.c_str(), &endp, 10); - if(out) *out = (int32_t)n; - // Note that strtol returns a *long int*, so even if strtol doesn't report a over/underflow - // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit - // platforms the size of these types may be different. - return endp && *endp == 0 && !errno && - n >= std::numeric_limits::min() && - n <= std::numeric_limits::max(); -} - -bool ParseInt64(const std::string& str, int64_t *out) -{ - if (!ParsePrechecks(str)) - return false; - char *endp = NULL; - errno = 0; // strtoll will not set errno if valid - long long int n = strtoll(str.c_str(), &endp, 10); - if(out) *out = (int64_t)n; - // Note that strtoll returns a *long long int*, so even if strtol doesn't report a over/underflow - // we still have to check that the returned value is within the range of an *int64_t*. - return endp && *endp == 0 && !errno && - n >= std::numeric_limits::min() && - n <= std::numeric_limits::max(); -} - -bool ParseDouble(const std::string& str, double *out) -{ - if (!ParsePrechecks(str)) - return false; - if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed - return false; - std::istringstream text(str); - text.imbue(std::locale::classic()); - double result; - text >> result; - if(out) *out = result; - return text.eof() && !text.fail(); -} - -std::string FormatParagraph(const std::string& in, size_t width, size_t indent) -{ - std::stringstream out; - size_t col = 0; - size_t ptr = 0; - while(ptr < in.size()) - { - // Find beginning of next word - ptr = in.find_first_not_of(' ', ptr); - if (ptr == std::string::npos) - break; - // Find end of next word - size_t endword = in.find_first_of(' ', ptr); - if (endword == std::string::npos) - endword = in.size(); - // Add newline and indentation if this wraps over the allowed width - if (col > 0) - { - if ((col + endword - ptr) > width) - { - out << '\n'; - for(size_t i=0; i (UPPER_BOUND / 10LL)) - return false; /* overflow */ - mantissa *= 10; - } - mantissa += ch - '0'; - mantissa_tzeros = 0; - } - return true; -} - -bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out) -{ - int64_t mantissa = 0; - int64_t exponent = 0; - int mantissa_tzeros = 0; - bool mantissa_sign = false; - bool exponent_sign = false; - int ptr = 0; - int end = val.size(); - int point_ofs = 0; - - if (ptr < end && val[ptr] == '-') { - mantissa_sign = true; - ++ptr; - } - if (ptr < end) - { - if (val[ptr] == '0') { - /* pass single 0 */ - ++ptr; - } else if (val[ptr] >= '1' && val[ptr] <= '9') { - while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { - if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros)) - return false; /* overflow */ - ++ptr; - } - } else return false; /* missing expected digit */ - } else return false; /* empty string or loose '-' */ - if (ptr < end && val[ptr] == '.') - { - ++ptr; - if (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') - { - while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { - if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros)) - return false; /* overflow */ - ++ptr; - ++point_ofs; - } - } else return false; /* missing expected digit */ - } - if (ptr < end && (val[ptr] == 'e' || val[ptr] == 'E')) - { - ++ptr; - if (ptr < end && val[ptr] == '+') - ++ptr; - else if (ptr < end && val[ptr] == '-') { - exponent_sign = true; - ++ptr; - } - if (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { - while (ptr < end && val[ptr] >= '0' && val[ptr] <= '9') { - if (exponent > (UPPER_BOUND / 10LL)) - return false; /* overflow */ - exponent = exponent * 10 + val[ptr] - '0'; - ++ptr; - } - } else return false; /* missing expected digit */ - } - if (ptr != end) - return false; /* trailing garbage */ - - /* finalize exponent */ - if (exponent_sign) - exponent = -exponent; - exponent = exponent - point_ofs + mantissa_tzeros; - - /* finalize mantissa */ - if (mantissa_sign) - mantissa = -mantissa; - - /* convert to one 64-bit fixed-point value */ - exponent += decimals; - if (exponent < 0) - return false; /* cannot represent values smaller than 10^-decimals */ - if (exponent >= 18) - return false; /* cannot represent values larger than or equal to 10^(18-decimals) */ - - for (int i=0; i < exponent; ++i) { - if (mantissa > (UPPER_BOUND / 10LL) || mantissa < -(UPPER_BOUND / 10LL)) - return false; /* overflow */ - mantissa *= 10; - } - if (mantissa > UPPER_BOUND || mantissa < -UPPER_BOUND) - return false; /* overflow */ - - if (amount_out) - *amount_out = mantissa; - - return true; -} - diff --git a/privacy/zsl/utils/utilstrencodings.h b/privacy/zsl/utils/utilstrencodings.h deleted file mode 100644 index 37a07ea..0000000 --- a/privacy/zsl/utils/utilstrencodings.h +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2014 The Bitcoin Core developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -/** - * Utilities for converting data from/to strings. - */ -#ifndef BITCOIN_UTILSTRENCODINGS_H -#define BITCOIN_UTILSTRENCODINGS_H - -#include -#include -#include - -#define BEGIN(a) ((char*)&(a)) -#define END(a) ((char*)&((&(a))[1])) -#define UBEGIN(a) ((unsigned char*)&(a)) -#define UEND(a) ((unsigned char*)&((&(a))[1])) -#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) - -/** This is needed because the foreach macro can't get over the comma in pair */ -#define PAIRTYPE(t1, t2) std::pair - -/** Used by SanitizeString() */ -enum SafeChars -{ - SAFE_CHARS_DEFAULT, //!< The full set of allowed chars - SAFE_CHARS_UA_COMMENT //!< BIP-0014 subset -}; - -std::string SanitizeFilename(const std::string& str); -/** -* Remove unsafe chars. Safe chars chosen to allow simple messages/URLs/email -* addresses, but avoid anything even possibly remotely dangerous like & or > -* @param[in] str The string to sanitize -* @param[in] rule The set of safe chars to choose (default: least restrictive) -* @return A new string without unsafe chars -*/ -std::string SanitizeString(const std::string& str, int rule = SAFE_CHARS_DEFAULT); -std::string HexInt(uint32_t val); -uint32_t ParseHexToUInt32(const std::string& str); -std::vector ParseHex(const char* psz); -std::vector ParseHex(const std::string& str); -signed char HexDigit(char c); -bool IsHex(const std::string& str); -std::vector DecodeBase64(const char* p, bool* pfInvalid = NULL); -std::string DecodeBase64(const std::string& str); -std::string EncodeBase64(const unsigned char* pch, size_t len); -std::string EncodeBase64(const std::string& str); -std::vector DecodeBase32(const char* p, bool* pfInvalid = NULL); -std::string DecodeBase32(const std::string& str); -std::string EncodeBase32(const unsigned char* pch, size_t len); -std::string EncodeBase32(const std::string& str); - -std::string i64tostr(int64_t n); -std::string itostr(int n); -int64_t atoi64(const char* psz); -int64_t atoi64(const std::string& str); -int atoi(const std::string& str); - -/** - * Convert string to signed 32-bit integer with strict parse error feedback. - * @returns true if the entire string could be parsed as valid integer, - * false if not the entire string could be parsed or when overflow or underflow occurred. - */ -bool ParseInt32(const std::string& str, int32_t *out); - -/** - * Convert string to signed 64-bit integer with strict parse error feedback. - * @returns true if the entire string could be parsed as valid integer, - * false if not the entire string could be parsed or when overflow or underflow occurred. - */ -bool ParseInt64(const std::string& str, int64_t *out); - -/** - * Convert string to double with strict parse error feedback. - * @returns true if the entire string could be parsed as valid double, - * false if not the entire string could be parsed or when overflow or underflow occurred. - */ -bool ParseDouble(const std::string& str, double *out); - -template -std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) -{ - std::string rv; - static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - rv.reserve((itend-itbegin)*3); - for(T it = itbegin; it < itend; ++it) - { - unsigned char val = (unsigned char)(*it); - if(fSpaces && it != itbegin) - rv.push_back(' '); - rv.push_back(hexmap[val>>4]); - rv.push_back(hexmap[val&15]); - } - - return rv; -} - -template -inline std::string HexStr(const T& vch, bool fSpaces=false) -{ - return HexStr(vch.begin(), vch.end(), fSpaces); -} - -/** - * Format a paragraph of text to a fixed width, adding spaces for - * indentation to any added line. - */ -std::string FormatParagraph(const std::string& in, size_t width = 79, size_t indent = 0); - -/** - * Timing-attack-resistant comparison. - * Takes time proportional to length - * of first argument. - */ -template -bool TimingResistantEqual(const T& a, const T& b) -{ - if (b.size() == 0) return a.size() == 0; - size_t accumulator = a.size() ^ b.size(); - for (size_t i = 0; i < a.size(); i++) - accumulator |= a[i] ^ b[i%b.size()]; - return accumulator == 0; -} - -/** Parse number as fixed point according to JSON number syntax. - * See http://json.org/number.gif - * @returns true on success, false on error. - * @note The result must be in the range (-10^18,10^18), otherwise an overflow error will trigger. - */ -bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out); - -/** - * Convert from one power-of-2 number base to another. - * - * Examples using ConvertBits<8, 5, true>(): - * 000000 -> 0000000000 - * 202020 -> 0400100200 - * 757575 -> 0e151a170a - * abcdef -> 150f061e1e - * ffffff -> 1f1f1f1f1e - */ -template -bool ConvertBits(const O& outfn, I it, I end) { - size_t acc = 0; - size_t bits = 0; - constexpr size_t maxv = (1 << tobits) - 1; - constexpr size_t max_acc = (1 << (frombits + tobits - 1)) - 1; - while (it != end) { - acc = ((acc << frombits) | *it) & max_acc; - bits += frombits; - while (bits >= tobits) { - bits -= tobits; - outfn((acc >> bits) & maxv); - } - ++it; - } - if (pad) { - if (bits) outfn((acc << (tobits - bits)) & maxv); - } else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) { - return false; - } - return true; -} - -#endif // BITCOIN_UTILSTRENCODINGS_H