id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,535,313
Enclave.cpp
crustio_crust-sworker/src/enclave/Enclave.cpp
#include "Enclave.h" using namespace std; std::map<uint32_t, uint8_t *> g_ecall_buffer_pool; sgx_thread_mutex_t g_ecall_buffer_pool_mutex = SGX_THREAD_MUTEX_INITIALIZER; std::map<ecall_store_type_t, ecall_store2_f> g_ecall_store2_func_m = { {ECALL_RESTORE_FROM_UPGRADE, ecall_restore_from_upgrade}, }; /** * @description: Ecall main loop */ void ecall_main_loop() { Workload *wl = Workload::get_instance(); crust_status_t crust_status = CRUST_SUCCESS; while (true) { if (ENC_UPGRADE_STATUS_SUCCESS == wl->get_upgrade_status()) { log_info("Stop enclave main loop for exit...\n"); return; } // Store metadata periodically log_debug("Start storing metadata\n"); if (CRUST_SUCCESS != (crust_status = id_store_metadata())) { log_err("Store enclave data failed! Error code:%lx\n", crust_status); } // ----- File validate ----- // log_debug("Start validating meaningful files\n"); validate_meaningful_file(); // ----- SRD validate ----- // log_debug("Start validating srd\n"); validate_srd(); // ----- SRD ----- // log_debug("Start srd tasks\n"); srd_change(); // Wait for (size_t i = 0; i < MAIN_LOOP_WAIT_TIME; i++) { if (ENC_UPGRADE_STATUS_SUCCESS == wl->get_upgrade_status()) { log_info("Stop enclave main loop for exit...\n"); return; } ocall_usleep(1000000); } } } /************************************SRD****************************************/ /** * @description: Seal one G srd files under directory, can be called from multiple threads * @param uuid (in) -> Disk path uuid * @return: Srd increase result */ crust_status_t ecall_srd_increase(const char *uuid) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } return srd_increase(uuid); } /** * @description: Decrease srd files under directory * @param change -> reduction * @return: Deleted srd space */ size_t ecall_srd_decrease(size_t change) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return 0; } size_t ret = srd_decrease(change); return ret; } /** * @description: Change srd number * @param change -> Will be changed srd number * @param real_change (out) -> Pointer to real changed srd task number * @return: Changing result status */ crust_status_t ecall_change_srd_task(long change, long *real_change) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } return change_srd_task(change, real_change); } /** * @description: Update srd_metadata * @param data (in) -> Pointer to deleted srd info * @param data_size -> Data size */ void ecall_srd_remove_space(const char *data, size_t data_size) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return; } srd_remove_space(data, data_size); } /************************************System****************************************/ /** * @description: Stop enclave */ void ecall_stop_all() { Workload::get_instance()->set_upgrade_status(ENC_UPGRADE_STATUS_SUCCESS); id_store_metadata(); } /** * @description: Restore enclave data from file * @return: Restore status */ crust_status_t ecall_restore_metadata() { return id_restore_metadata(); } /** * @description: Compare chain account with enclave's * @param account_id (in) -> Pointer to account id * @param len -> account id length * @return: Compare status */ crust_status_t ecall_cmp_chain_account_id(const char *account_id, size_t len) { return id_cmp_chain_account_id(account_id, len); } /** * @description: Get signed work report * @param block_hash (in) -> block hash * @param block_height -> block height * @return: Sign status */ crust_status_t ecall_gen_and_upload_work_report(const char *block_hash, size_t block_height) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } crust_status_t ret = gen_and_upload_work_report(block_hash, block_height, 0, false, true); return ret; } /** * @description: Generate ecc key pair and store it in enclave * @param account_id (in) -> Chain account id * @param len -> Chain account id length * @return: Generate status */ sgx_status_t ecall_gen_key_pair(const char *account_id, size_t len) { return id_gen_key_pair(account_id, len); } /** * @description: Get sgx report, our generated public key contained * in report data * @param report (out) -> Pointer to SGX report * @param target_info (in) -> Data used to generate report * @return: Get sgx report status */ sgx_status_t ecall_get_quote_report(sgx_report_t *report, sgx_target_info_t *target_info) { return id_get_quote_report(report, target_info); } /** * @description: Generate current code measurement * @return: Generate status */ sgx_status_t ecall_gen_sgx_measurement() { return id_gen_sgx_measurement(); } /** * @description: Verify IAS report * @param IASReport (in) -> Vector first address * @param len -> Count of Vector IASReport * @return: Verify status */ crust_status_t ecall_gen_upload_epid_identity(char **IASReport, size_t len) { return id_verify_upload_epid_identity(IASReport, len); } /** * @description: Get ECDSA identity * @param p_quote (in) -> Pointer to quote buffer * @param quote_size -> Quote buffer size * @return: Get result */ crust_status_t ecall_gen_upload_ecdsa_quote(uint8_t *p_quote, uint32_t quote_size) { return id_gen_upload_ecdsa_quote(p_quote, quote_size); } /** * @description: Generate and upload sworker identity to crust * @param report (in) -> Report returned by registry chain * @param size -> Size of report * @return: Result status */ crust_status_t ecall_gen_upload_ecdsa_identity(const char *report, uint32_t size) { return id_gen_upload_ecdsa_identity(report, size); } /************************************Files****************************************/ /** * @description: IPFS informs sWorker to prepare for seal * @param root (in) -> File root cid * @param root_b58 (in) -> File root b58 cid * @return: Inform result */ crust_status_t ecall_seal_file_start(const char *root, const char *root_b58) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } crust_status_t ret = storage_seal_file_start(root, root_b58); return ret; } /** * @description: Seal file according to given path and return new MerkleTree * @param root (in) -> Pointer to file root cid * @param data (in) -> Pointer to raw data or link * @param data_size -> Raw data size or link size * @param is_link -> Indicate data is raw data or a link * @param path (in, out) -> Index path used to get file block * @param path_size -> Index path size * @return: Seal status */ crust_status_t ecall_seal_file(const char *root, const uint8_t *data, size_t data_size, bool is_link, char *path, size_t path_size) { return storage_seal_file(root, data, data_size, is_link, path, path_size); } /** * @description: IPFS informs sWorker seal end * @param root (in) -> File root cid * @return: Inform result */ crust_status_t ecall_seal_file_end(const char *root) { return storage_seal_file_end(root); } /** * @description: Unseal file according to given path * @param path (in) -> Pointer to file block stored path * @param p_decrypted_data (in) -> Pointer to decrypted data buffer * @param decrypted_data_size -> Decrypted data buffer size * @param p_decrypted_data_size -> Pointer to decrypted data real size * @return: Unseal status */ crust_status_t ecall_unseal_file(const char *path, uint8_t *p_decrypted_data, size_t decrypted_data_size, size_t *p_decrypted_data_size) { crust_status_t ret = storage_unseal_file(path, p_decrypted_data, decrypted_data_size, p_decrypted_data_size); return ret; } /** * @description: Add to be deleted file hash to buffer * @param cid (in) -> File content id * @return: Delete status */ crust_status_t ecall_delete_file(const char *cid) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } crust_status_t ret = storage_delete_file(cid); return ret; } /** * @description: Validate meaningful files */ void ecall_validate_file() { validate_meaningful_file_real(); } /** * @description: Validate srd */ void ecall_validate_srd() { validate_srd_real(); } /************************************Upgrade****************************************/ /** * @description: Check if upgrade can be done right now * @param block_height -> Current block height * @return: Capability to upgrade */ crust_status_t ecall_enable_upgrade(size_t block_height) { crust_status_t crust_status = CRUST_SUCCESS; Workload *wl = Workload::get_instance(); if (CRUST_SUCCESS == (crust_status = wl->can_report_work(block_height))) { wl->set_upgrade_status(ENC_UPGRADE_STATUS_PROCESS); } return crust_status; } /** * @description: Disable is_upgrading */ void ecall_disable_upgrade() { Workload::get_instance()->set_upgrade_status(ENC_UPGRADE_STATUS_NONE); } /** * @description: Generate upgrade data * @param block_height -> Current block height * @return: Generate result */ crust_status_t ecall_gen_upgrade_data(size_t block_height) { return id_gen_upgrade_data(block_height); } /** * @description: Restore from upgrade data * @param data (in) -> Metadata from old version * @param data_size -> Metadata length * @return: Restore result */ crust_status_t ecall_restore_from_upgrade(const uint8_t *data, size_t data_size) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } return id_restore_from_upgrade(data, data_size); } /** * @description: Deal with file illegal transfer * @param data (in) -> Pointer to recover data * @param data_size -> Recover data size * @return: Recover status */ crust_status_t ecall_recover_illegal_file(const uint8_t *data, size_t data_size) { return Workload::get_instance()->recover_illegal_file(data, data_size); } /************************************Tools****************************************/ /** * @description: Get enclave id information */ void ecall_id_get_info() { id_get_info(); } /** * @description: Ecall save big data * @param t -> Store function type * @param data (in) -> Pointer to data * @param total_size -> Total data size * @param partial_size -> Current store data size * @param offset -> Offset in total data * @param buffer_key -> Session key for this time enclave data store * @return: Store result */ crust_status_t ecall_safe_store2(ecall_store_type_t t, const uint8_t *data, size_t total_size, size_t partial_size, size_t offset, uint32_t buffer_key) { SafeLock sl(g_ecall_buffer_pool_mutex); sl.lock(); crust_status_t crust_status = CRUST_SUCCESS; bool is_end = true; if (offset < total_size) { uint8_t *buffer = NULL; if (g_ecall_buffer_pool.find(buffer_key) != g_ecall_buffer_pool.end()) { buffer = g_ecall_buffer_pool[buffer_key]; } if (buffer == NULL) { buffer = (uint8_t *)malloc(total_size); if (buffer == NULL) { crust_status = CRUST_MALLOC_FAILED; goto cleanup; } memset(buffer, 0, total_size); g_ecall_buffer_pool[buffer_key] = buffer; } memcpy(buffer + offset, data, partial_size); if (offset + partial_size < total_size) { is_end = false; } } if (!is_end) { return CRUST_SUCCESS; } crust_status = (g_ecall_store2_func_m[t])(g_ecall_buffer_pool[buffer_key], total_size); cleanup: if (g_ecall_buffer_pool.find(buffer_key) != g_ecall_buffer_pool.end()) { free(g_ecall_buffer_pool[buffer_key]); g_ecall_buffer_pool.erase(buffer_key); } return crust_status; }
12,811
C++
.cpp
411
26.673966
136
0.632355
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,314
Srd.cpp
crustio_crust-sworker/src/enclave/srd/Srd.cpp
#include "Srd.h" long g_srd_task = 0; sgx_thread_mutex_t g_srd_task_mutex = SGX_THREAD_MUTEX_INITIALIZER; uint8_t *g_base_rand_buffer = NULL; sgx_thread_mutex_t g_base_rand_buffer_mutex = SGX_THREAD_MUTEX_INITIALIZER; /** * @description: call ocall_save_file to save file * @param g_path -> g folder path * @param index -> m file's index * @param hash -> m file's hash * @param data -> m file's data * @param data_size -> the length of m file's data * @return: Save status */ crust_status_t save_file(const char *g_path, size_t index, sgx_sha256_hash_t hash, const unsigned char *data, size_t data_size) { std::string file_path = get_leaf_path(g_path, index, hash); crust_status_t crust_status = CRUST_SUCCESS; ocall_save_file(&crust_status, file_path.c_str(), data, data_size, STORE_TYPE_SRD); return crust_status; } /** * @description: call ocall_save_file to save m_hashs.bin file * @param g_path -> g folder path * @param data -> data * @param data_size -> the length of data * @return: Save status */ crust_status_t save_m_hashs_file(const char *g_path, const unsigned char *data, size_t data_size) { std::string file_path = get_m_hashs_file_path(g_path); crust_status_t crust_status = CRUST_SUCCESS; ocall_save_file(&crust_status, file_path.c_str(), data, data_size, STORE_TYPE_SRD); return crust_status; } /** * @description: Do srd */ void srd_change() { Workload *wl = Workload::get_instance(); if (ENC_UPGRADE_STATUS_NONE != wl->get_upgrade_status()) { return; } // Check if validation has been applied or not if (!wl->report_has_validated_proof()) { return; } SafeLock sl_task(g_srd_task_mutex); sl_task.lock(); if (0 == g_srd_task) return; // Get real srd space long srd_change_num = 0; if (g_srd_task > SRD_MAX_INC_PER_TURN) { srd_change_num = SRD_MAX_INC_PER_TURN; g_srd_task -= SRD_MAX_INC_PER_TURN; } else if (g_srd_task > 0) { srd_change_num = g_srd_task; g_srd_task = 0; } else if (g_srd_task < 0) { srd_change_num = std::max(g_srd_task, (long)-SRD_MAX_DEC_PER_TURN); g_srd_task -= srd_change_num; } sl_task.unlock(); // Do srd crust_status_t crust_status = CRUST_SUCCESS; if (srd_change_num != 0) { ocall_srd_change(&crust_status, srd_change_num); if (CRUST_SRD_NUMBER_EXCEED == crust_status) { sl_task.lock(); g_srd_task = 0; sl_task.unlock(); } } // Store remaining task sl_task.lock(); std::string srd_task_str = std::to_string(g_srd_task); if (CRUST_SUCCESS != persist_set_unsafe(WL_SRD_REMAINING_TASK, reinterpret_cast<const uint8_t *>(srd_task_str.c_str()), srd_task_str.size())) { log_warn("Store srd remaining task failed!\n"); } // Set srd remaining task wl->set_srd_remaining_task(g_srd_task); std::string srd_info_str = wl->get_srd_info().dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); sl_task.unlock(); } /** * @description: seal one G srd files under directory, can be called from multiple threads * @param uuid -> Disk path uuid * @return: Srd increase result */ crust_status_t srd_increase(const char *uuid) { crust_status_t crust_status = CRUST_SUCCESS; Workload *wl = Workload::get_instance(); // Get uuid bytes uint8_t *p_uuid_u = hex_string_to_bytes(uuid, UUID_LENGTH * 2); if (p_uuid_u == NULL) { log_err("Get uuid bytes failed! Invalid uuid:%s\n", uuid); return CRUST_UNEXPECTED_ERROR; } Defer def_uuid([&p_uuid_u](void) { free(p_uuid_u); }); // Check if validation has been applied or not if (!wl->report_has_validated_proof()) { return CRUST_VALIDATE_HIGH_PRIORITY; } // Generate base random data do { if (g_base_rand_buffer == NULL) { SafeLock sl(g_base_rand_buffer_mutex); sl.lock(); if (g_base_rand_buffer != NULL) { break; } g_base_rand_buffer = (uint8_t *)enc_malloc(SRD_RAND_DATA_LENGTH); if (g_base_rand_buffer == NULL) { log_err("Malloc memory failed!\n"); return CRUST_MALLOC_FAILED; } memset(g_base_rand_buffer, 0, SRD_RAND_DATA_LENGTH); sgx_read_rand(g_base_rand_buffer, sizeof(g_base_rand_buffer)); } } while (0); // Generate current G hash index size_t tmp_val_len = 18; char tmp_val[tmp_val_len]; sgx_read_rand((unsigned char *)&tmp_val, tmp_val_len); std::string tmp_val_str = hexstring_safe(tmp_val, tmp_val_len); char *p_mid_dir = tmp_val; std::string mid_dir = tmp_val_str.substr(0, LAYER_LENGTH * 2); std::string tmp_dir = uuid + tmp_val_str; // ----- Generate srd file ----- // // Create directory ocall_create_dir(&crust_status, tmp_dir.c_str(), STORE_TYPE_SRD); if (CRUST_SUCCESS != crust_status) { log_err("Create tmp directory failed! Error code:%lx\n", crust_status); return crust_status; } // Delete tmp directory if failed Defer def_del_dir([&crust_status, &tmp_dir](void) { if (CRUST_SUCCESS != crust_status) { crust_status_t del_ret = CRUST_SUCCESS; ocall_delete_folder_or_file(&del_ret, tmp_dir.c_str(), STORE_TYPE_SRD); if (CRUST_SUCCESS != del_ret) { log_warn("Delete temp directory %s failed! Error code:%lx\n", tmp_dir.c_str(), del_ret); } } }); // Generate all M hashs and store file to disk uint8_t *m_hashs = (uint8_t *)enc_malloc(SRD_RAND_DATA_NUM * HASH_LENGTH); if (m_hashs == NULL) { log_err("Malloc memory failed!\n"); return crust_status = CRUST_MALLOC_FAILED; } Defer defer_hashs([&m_hashs](void) { free(m_hashs); }); for (size_t i = 0; i < SRD_RAND_DATA_NUM; i++) { sgx_sealed_data_t *p_sealed_data = NULL; size_t sealed_data_size = 0; crust_status = seal_data_mrenclave(g_base_rand_buffer, SRD_RAND_DATA_LENGTH, &p_sealed_data, &sealed_data_size); if (CRUST_SUCCESS != crust_status) { log_err("Seal random data failed! Error code:%lx\n", crust_status); return crust_status; } Defer defer_sealed_data([&p_sealed_data](void) { free(p_sealed_data); }); sgx_sha256_hash_t m_hash; sgx_sha256_msg((uint8_t *)p_sealed_data, SRD_RAND_DATA_LENGTH, &m_hash); memcpy(m_hashs + i * HASH_LENGTH, m_hash, HASH_LENGTH); std::string m_data_path = get_leaf_path(tmp_dir.c_str(), i, m_hash); ocall_save_file(&crust_status, m_data_path.c_str(), reinterpret_cast<const uint8_t *>(p_sealed_data), SRD_RAND_DATA_LENGTH, STORE_TYPE_SRD); if (CRUST_SUCCESS != crust_status) { log_err("Save srd file(%s) failed! Error code:%lx\n", tmp_dir.c_str(), crust_status); return crust_status; } } // Generate G hashs sgx_sha256_hash_t g_hash; sgx_sha256_msg(m_hashs, SRD_RAND_DATA_NUM * HASH_LENGTH, &g_hash); crust_status = save_m_hashs_file(tmp_dir.c_str(), m_hashs, SRD_RAND_DATA_NUM * HASH_LENGTH); if (CRUST_SUCCESS != crust_status) { log_err("Save srd(%s) metadata failed!\n", tmp_dir.c_str()); return crust_status; } // Change G path name std::string g_hash_hex = hexstring_safe(&g_hash, HASH_LENGTH); std::string g_hash_path = uuid + mid_dir + g_hash_hex; ocall_rename_dir(&crust_status, tmp_dir.c_str(), g_hash_path.c_str(), STORE_TYPE_SRD); if (CRUST_SUCCESS != crust_status) { log_err("Rename directory %s to %s failed!\n", tmp_dir.c_str(), g_hash_path.c_str()); return crust_status; } // ----- Update srd_hashs ----- // // Add new g_hash to srd_hashs // Because add this p_hash_u to the srd_hashs, so we cannot free p_hash_u uint8_t *srd_item = (uint8_t *)enc_malloc(SRD_LENGTH); if (srd_item == NULL) { log_err("Malloc for srd item failed!\n"); return crust_status = CRUST_MALLOC_FAILED; } memset(srd_item, 0, SRD_LENGTH); memcpy(srd_item, p_uuid_u, UUID_LENGTH); memcpy(srd_item + UUID_LENGTH, p_mid_dir, LAYER_LENGTH); memcpy(srd_item + UUID_LENGTH + LAYER_LENGTH, g_hash, HASH_LENGTH); sgx_thread_mutex_lock(&wl->srd_mutex); wl->srd_hashs.push_back(srd_item); log_info("Seal random data -> %s, %luG success\n", g_hash_hex.c_str(), wl->srd_hashs.size()); sgx_thread_mutex_unlock(&wl->srd_mutex); // ----- Update srd info ----- // wl->set_srd_info(uuid, 1); // Update srd info std::string srd_info_str = wl->get_srd_info().dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); return CRUST_SUCCESS; } /** * @description: Decrease srd files under directory * @param change -> Total to be deleted space volumn * @return: Decreased size */ size_t srd_decrease(size_t change) { crust_status_t crust_status = CRUST_SUCCESS; Workload *wl = Workload::get_instance(); // ----- Choose to be deleted hash ----- // SafeLock sl(wl->srd_mutex); sl.lock(); wl->deal_deleted_srd_nolock(); // Get real change change = std::min(change, wl->srd_hashs.size()); if (change <= 0) { return 0; } // Get change hashs // Note: Cannot push srd hash pointer to vector because it will be deleted later std::vector<std::string> del_srds; std::vector<size_t> del_indexes; for (size_t i = 1; i <= change; i++) { size_t index = wl->srd_hashs.size() - i; del_srds.push_back(hexstring_safe(wl->srd_hashs[index], SRD_LENGTH)); del_indexes.push_back(index); } std::reverse(del_indexes.begin(), del_indexes.end()); wl->delete_srd_meta(del_indexes); sl.unlock(); // Delete srd files for (auto srd : del_srds) { // Delete srd data ocall_delete_folder_or_file(&crust_status, srd.c_str(), STORE_TYPE_SRD); if (CRUST_SUCCESS != crust_status) { log_warn("Delete path:%s failed! Error code:%lx\n", srd.c_str(), crust_status); } } // Update srd info std::string srd_info_str = wl->get_srd_info().dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); return change; } /** * @description: Remove space outside main loop * @param data -> Pointer to deleted srd info * @param data_size -> Data size */ void srd_remove_space(const char *data, size_t data_size) { crust_status_t crust_status = CRUST_SUCCESS; Workload *wl = Workload::get_instance(); json::JSON del_json = json::JSON::Load_unsafe(reinterpret_cast<const uint8_t *>(data), data_size); long change = 0; if (del_json.JSONType() != json::JSON::Class::Object) return; for (auto item : del_json.ObjectRange()) { change += item.second.ToInt(); } // ----- Choose to be deleted hash ----- // SafeLock sl(wl->srd_mutex); sl.lock(); // Get change hashs // Note: Cannot push srd hash pointer to vector because it will be deleted later std::vector<std::string> del_srds; if (wl->srd_hashs.size() > 0) { for (size_t i = wl->srd_hashs.size() - 1; i >= 0 && change > 0; i--) { std::string uuid = hexstring_safe(wl->srd_hashs[i], UUID_LENGTH); if (del_json[uuid].ToInt() > 0) { del_srds.push_back(hexstring_safe(wl->srd_hashs[i], SRD_LENGTH)); wl->add_srd_to_deleted_buffer(i); del_json[uuid].AddNum(-1); change--; } } } sl.unlock(); // Delete srd files if (del_srds.size() > 0) { for (auto srd : del_srds) { ocall_delete_folder_or_file(&crust_status, srd.c_str(), STORE_TYPE_SRD); if (CRUST_SUCCESS != crust_status) { log_warn("Delete path:%s failed! Error code:%lx\n", srd.c_str(), crust_status); } } } // Update srd info std::string srd_info_str = wl->get_srd_info().dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); } /** * @description: Get srd change * @return: Srd change */ long get_srd_task() { sgx_thread_mutex_lock(&g_srd_task_mutex); long srd_change = g_srd_task; sgx_thread_mutex_unlock(&g_srd_task_mutex); return srd_change; } /** * @description: Set srd change * @param change -> Srd change * @param real_change -> Pointer to real changed srd number * @return: Changing return status */ crust_status_t change_srd_task(long change, long *real_change) { Workload *wl = Workload::get_instance(); crust_status_t crust_status = CRUST_SUCCESS; // Check if srd number exceeds upper limit if (change > 0) { Workload *wl = Workload::get_instance(); sgx_thread_mutex_lock(&wl->srd_mutex); long srd_num = (long)wl->srd_hashs.size(); sgx_thread_mutex_unlock(&wl->srd_mutex); srd_num += get_srd_task(); if (srd_num >= SRD_NUMBER_UPPER_LIMIT) { log_warn("No srd will be added!Srd size has reached the upper limit:%ldG!\n", SRD_NUMBER_UPPER_LIMIT); change = 0; crust_status = CRUST_SRD_NUMBER_EXCEED; } else if (srd_num + change > SRD_NUMBER_UPPER_LIMIT) { log_warn("To be added srd number:%ldG(srd upper limit:%ldG)\n", change, SRD_NUMBER_UPPER_LIMIT); change = SRD_NUMBER_UPPER_LIMIT - srd_num; crust_status = CRUST_SRD_NUMBER_EXCEED; } } sgx_thread_mutex_lock(&g_srd_task_mutex); g_srd_task += change; // Store remaining task std::string srd_task_str = std::to_string(g_srd_task); if (CRUST_SUCCESS != persist_set_unsafe(WL_SRD_REMAINING_TASK, reinterpret_cast<const uint8_t *>(srd_task_str.c_str()), srd_task_str.size())) { log_warn("Store srd remaining task failed!\n"); } // Set srd remaining task wl->set_srd_remaining_task(g_srd_task); sgx_thread_mutex_unlock(&g_srd_task_mutex); *real_change = change; // Update srd info std::string srd_info_str = wl->get_srd_info().dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); return crust_status; } /** * @description: Srd gets sealed data data * @param path -> Data path * @param p_data -> Pointer to pointer sealed srd data * @param data_size -> Poniter to sealed srd data size * @return: Get result */ crust_status_t srd_get_file(const char *path, uint8_t **p_data, size_t *data_size) { crust_status_t crust_status = CRUST_SUCCESS; ocall_get_file(&crust_status, path, p_data, data_size, STORE_TYPE_SRD); if (CRUST_SUCCESS != crust_status) { return crust_status; } uint8_t *p_sealed_data = (uint8_t *)enc_malloc(*data_size); if (p_sealed_data == NULL) { ocall_free_outer_buffer(&crust_status, p_data); return CRUST_MALLOC_FAILED; } memset(p_sealed_data, 0, *data_size); memcpy(p_sealed_data, *p_data, *data_size); ocall_free_outer_buffer(&crust_status, p_data); *p_data = p_sealed_data; return crust_status; }
15,602
C++
.cpp
427
30.386417
148
0.609679
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,315
Storage.cpp
crustio_crust-sworker/src/enclave/storage/Storage.cpp
#include "Storage.h" using namespace std; crust_status_t check_seal_file_dup(std::string cid); /** * @description: IPFS informs sWorker to seal file * @param root -> File root cid * @param root_b58 -> File root cid in base58 format * @return: Inform result */ crust_status_t storage_seal_file_start(const char *root, const char *root_b58) { Workload *wl = Workload::get_instance(); crust_status_t crust_status = CRUST_SUCCESS; std::string root_cid(root); std::string root_cid_b58(root_b58); if (ENC_UPGRADE_STATUS_NONE != wl->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } // Check if total file number exceeds upper limit size_t file_num = 0; SafeLock sl_file(wl->file_mutex); sl_file.lock(); file_num += wl->sealed_files.size(); if (file_num >= FILE_NUMBER_UPPER_LIMIT) { return CRUST_FILE_NUMBER_EXCEED; } // Check if file is duplicated if (CRUST_SUCCESS != (crust_status = check_seal_file_dup(root_cid.c_str()))) { return crust_status; } sl_file.unlock(); // Delete inserted pending file if reaching pending number limit bool exceed_limit = false; Defer def_del_pending([&wl, &root, &exceed_limit](void) { if (exceed_limit) { sgx_thread_mutex_lock(&wl->file_mutex); wl->del_file_nolock(root); sgx_thread_mutex_unlock(&wl->file_mutex); } }); // Check if pending file number exceeds upper limit SafeLock sl(wl->pending_files_um_mutex); sl.lock(); if (wl->pending_files_um.size() > FILE_PENDING_LIMIT) { exceed_limit = true; return CRUST_FILE_NUMBER_EXCEED; } wl->pending_files_um[root_cid][FILE_BLOCKS][root_cid_b58].AddNum(1); sl.unlock(); // Delete previous left data crust_status_t del_ret = CRUST_SUCCESS; ocall_delete_ipfs_file(&del_ret, root); // Add info in workload spec wl->set_file_spec(FILE_STATUS_PENDING, 1); // Store file information ocall_store_file_info(root, "{}", FILE_TYPE_PENDING); return CRUST_SUCCESS; } /** * @description: Seal IPFS block * @param root -> File root cid * @param data -> To be sealed data * @param data_size -> To be sealed data size * @param is_link -> Indicate data is raw data or a link * @param path -> Path in sWorker return to IPFS * @param path_size -> Index path size * @return: Seal result */ crust_status_t storage_seal_file(const char *root, const uint8_t *data, size_t data_size, bool is_link, char *path, size_t /*path_size*/) { Workload *wl = Workload::get_instance(); std::string rcid(root); uint8_t *p_plain_data = const_cast<uint8_t *>(data); size_t plain_data_sz = data_size; // If file transfer completed if (p_plain_data == NULL || plain_data_sz == 0) { SafeLock sl_files_info(wl->pending_files_um_mutex); sl_files_info.lock(); if (wl->pending_files_um.find(rcid) == wl->pending_files_um.end()) { return CRUST_STORAGE_NEW_FILE_NOTFOUND; } wl->pending_files_um[rcid][FILE_BLOCKS][EMPTY_BLOCK_CID].AddNum(-1); sl_files_info.unlock(); memcpy(path, EMPTY_BLOCK_FLAG, std::strlen(EMPTY_BLOCK_FLAG)); return CRUST_SUCCESS; } crust_status_t seal_ret = CRUST_UNEXPECTED_ERROR; Defer defer([&seal_ret, &wl, &rcid, &root](){ if (CRUST_SUCCESS != seal_ret) { sgx_thread_mutex_lock(&wl->pending_files_um_mutex); wl->pending_files_um.erase(rcid); sgx_thread_mutex_unlock(&wl->pending_files_um_mutex); // Delete file directory crust_status_t del_ret = CRUST_SUCCESS; ocall_delete_ipfs_file(&del_ret, root); // Delete PENDING status file entry SafeLock sl_file(wl->file_mutex); sl_file.lock(); size_t pos = 0; if (wl->is_file_dup_nolock(rcid, pos)) { if (FILE_STATUS_PENDING == wl->sealed_files[pos][FILE_STATUS].get_char(CURRENT_STATUS)) { wl->sealed_files.erase(wl->sealed_files.begin() + pos); // Delete file info ocall_delete_file_info(root, FILE_TYPE_PENDING); // Delete info in workload spec wl->set_file_spec(FILE_STATUS_PENDING, -1); } } sl_file.unlock(); } }); if (ENC_UPGRADE_STATUS_NONE != wl->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } // ----- Check file status ----- // SafeLock sl_files_info(wl->pending_files_um_mutex); sl_files_info.lock(); if (wl->pending_files_um.find(rcid) == wl->pending_files_um.end()) { return CRUST_STORAGE_NEW_FILE_NOTFOUND; } // ----- Parse file data ----- // if (is_link) { // Unlock files info before dealing with follow complicated computation sl_files_info.unlock(); // Get raw data uint8_t *p_sealed_data = NULL; size_t sealed_data_sz = 0; json::JSON links_json = json::JSON::Load(&seal_ret, p_plain_data, plain_data_sz); if (CRUST_SUCCESS != seal_ret) { return seal_ret; } if (!(links_json.JSONType() == json::JSON::Class::Object && links_json.hasKey(IPFS_META) && links_json[IPFS_META].JSONType() == json::JSON::Class::Array)) { return CRUST_UNEXPECTED_ERROR; } for (long i = 0; i < links_json.size(); i++) { std::string s_path = links_json[IPFS_META][i][IPFS_META_PATH].ToString(); if (CRUST_SUCCESS == (seal_ret = storage_get_file(s_path.c_str(), &p_sealed_data, &sealed_data_sz))) { break; } } if (CRUST_SUCCESS != seal_ret) { return seal_ret; } // Unseal sealed data uint8_t *p_decrypted_data = NULL; uint32_t decrypted_data_sz = 0; if (CRUST_SUCCESS != (seal_ret = unseal_data_mrsigner((sgx_sealed_data_t *)p_sealed_data, sealed_data_sz, &p_decrypted_data, &decrypted_data_sz))) { return seal_ret; } p_plain_data = p_decrypted_data; plain_data_sz = decrypted_data_sz; sl_files_info.lock(); } Defer def_plain_data([&p_plain_data, &is_link](void) { if (is_link) { free(p_plain_data); } }); sgx_sha256_hash_t cur_hash; sgx_sha256_msg(p_plain_data, plain_data_sz, &cur_hash); std::string cur_cid = hash_to_cid(reinterpret_cast<const uint8_t *>(&cur_hash)); //log_debug("Dealing with cid '%s'\n", cur_cid.c_str()); wl->pending_files_um[rcid][FILE_BLOCKS][cur_cid].AddNum(-1); sl_files_info.unlock(); // Push children to map std::vector<uint8_t *> children_hashs; seal_ret = get_hashs_from_block(p_plain_data, plain_data_sz, children_hashs); if (CRUST_SUCCESS != seal_ret) { return seal_ret; } sl_files_info.lock(); if (wl->pending_files_um.find(rcid) == wl->pending_files_um.end()) { return CRUST_STORAGE_NEW_FILE_NOTFOUND; } for (size_t i = 0; i < children_hashs.size(); i++) { std::string ccid = hash_to_cid(reinterpret_cast<const uint8_t *>(children_hashs[i])); wl->pending_files_um[rcid][FILE_BLOCKS][ccid].AddNum(1); free(children_hashs[i]); } sl_files_info.unlock(); // ----- Seal data ----- // sgx_sealed_data_t *p_sealed_data = NULL; size_t sealed_data_sz = 0; seal_ret = seal_data_mrsigner(p_plain_data, plain_data_sz, (sgx_sealed_data_t **)&p_sealed_data, &sealed_data_sz); if (CRUST_SUCCESS != seal_ret) { return seal_ret; } Defer def_sealed_data([&p_sealed_data](void) { free(p_sealed_data); }); sgx_sha256_hash_t sealed_hash; sgx_sha256_msg(reinterpret_cast<uint8_t *>(p_sealed_data), sealed_data_sz, &sealed_hash); std::string sealed_path = std::string(root) + "/" + hexstring_safe(&sealed_hash, HASH_LENGTH); // Save sealed block char *uuid = (char *)enc_malloc(UUID_LENGTH * 2); if (uuid == NULL) { return CRUST_MALLOC_FAILED; } Defer def_uuid([&uuid](void) { free(uuid); }); memset(uuid, 0, UUID_LENGTH * 2); ocall_save_ipfs_block(&seal_ret, sealed_path.c_str(), reinterpret_cast<uint8_t *>(p_sealed_data), sealed_data_sz, uuid, UUID_LENGTH * 2); if (CRUST_SUCCESS != seal_ret) { return seal_ret; } sealed_path = std::string(uuid, UUID_LENGTH * 2) + sealed_path; uint8_t *uuid_u = hex_string_to_bytes(uuid, UUID_LENGTH * 2); if (uuid_u == NULL) { return CRUST_UNEXPECTED_ERROR; } Defer def_uuid_u([&uuid_u](void) { free(uuid_u); }); // Return index path memcpy(path, sealed_path.c_str(), sealed_path.size()); // Record file info sl_files_info.lock(); if (wl->pending_files_um.find(rcid) == wl->pending_files_um.end()) { return CRUST_STORAGE_NEW_FILE_NOTFOUND; } wl->pending_files_um[rcid][FILE_META][FILE_HASH].AppendBuffer(uuid_u, UUID_LENGTH); wl->pending_files_um[rcid][FILE_META][FILE_HASH].AppendBuffer(sealed_hash, HASH_LENGTH); wl->pending_files_um[rcid][FILE_META][FILE_SIZE].AddNum(plain_data_sz); wl->pending_files_um[rcid][FILE_META][FILE_SEALED_SIZE].AddNum(sealed_data_sz); wl->pending_files_um[rcid][FILE_META][FILE_BLOCK_NUM].AddNum(1); sl_files_info.unlock(); seal_ret = CRUST_SUCCESS; return seal_ret; } /** * @description: Seal block end * @param root -> File root cid * @return: Seal end result */ crust_status_t storage_seal_file_end(const char *root) { crust_status_t crust_status = CRUST_UNEXPECTED_ERROR; std::string rcid(root); Workload *wl = Workload::get_instance(); // Check if file exists SafeLock sl(wl->pending_files_um_mutex); sl.lock(); if (wl->pending_files_um.find(rcid) == wl->pending_files_um.end()) { return CRUST_STORAGE_NEW_FILE_NOTFOUND; } json::JSON file_json = wl->pending_files_um[rcid]; sl.unlock(); Defer defer([&crust_status, &root, &wl](void) { if (CRUST_SUCCESS != crust_status) { // Delete file directory crust_status_t del_ret = CRUST_SUCCESS; ocall_delete_ipfs_file(&del_ret, root); } sgx_thread_mutex_lock(&wl->pending_files_um_mutex); wl->pending_files_um.erase(root); sgx_thread_mutex_unlock(&wl->pending_files_um_mutex); // Delete PENDING status file entry SafeLock sl(wl->file_mutex); sl.lock(); size_t pos = 0; if (wl->is_file_dup_nolock(root, pos)) { if (FILE_STATUS_PENDING == wl->sealed_files[pos][FILE_STATUS].get_char(CURRENT_STATUS)) { wl->sealed_files.erase(wl->sealed_files.begin() + pos); // Delete file info ocall_delete_file_info(root, FILE_TYPE_PENDING); // Delete info in workload spec wl->set_file_spec(FILE_STATUS_PENDING, -1); } } sl.unlock(); }); if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } // ----- Check if seal complete ----- // // Check if getting all blocks if (file_json[FILE_BLOCKS].JSONType() != json::JSON::Class::Object) { return CRUST_UNEXPECTED_ERROR; } for (auto m : file_json[FILE_BLOCKS].ObjectRange()) { if (m.second.ToInt() != 0) { return CRUST_STORAGE_INCOMPLETE_BLOCK; } } std::string cid_str = std::string(root); // ----- Add corresponding metadata ----- // // Get block height size_t chain_block_num = INT_MAX; size_t info_buf_sz = strlen(CHAIN_BLOCK_NUMBER) + 3 + HASH_LENGTH + strlen(CHAIN_BLOCK_HASH) + 3 + HASH_LENGTH * 2 + 2 + HASH_LENGTH * 2; uint8_t *block_info_buf = (uint8_t *)enc_malloc(info_buf_sz); if (block_info_buf == NULL) { return CRUST_MALLOC_FAILED; } Defer def_blk_info([&block_info_buf](void) { free(block_info_buf); }); memset(block_info_buf, 0, info_buf_sz); crust_status = safe_ocall_get2(ocall_chain_get_block_info, block_info_buf, &info_buf_sz); if (CRUST_SUCCESS == crust_status) { json::JSON binfo_json = json::JSON::Load_unsafe(block_info_buf, info_buf_sz); chain_block_num = binfo_json[CHAIN_BLOCK_NUMBER].ToInt(); } else { log_warn("Cannot get block information for sealed file.\n"); } // Get file entry info json::JSON file_entry_json = file_json[FILE_META]; sgx_sha256_hash_t sealed_root; sgx_sha256_msg(reinterpret_cast<const uint8_t *>(file_entry_json[FILE_HASH].ToBytes()), file_entry_json[FILE_HASH].size(), &sealed_root); // Store new tree structure crust_status = persist_set_unsafe(cid_str, reinterpret_cast<const uint8_t *>(file_entry_json[FILE_HASH].ToBytes()), file_entry_json[FILE_HASH].size()); if (CRUST_SUCCESS != crust_status) { return crust_status; } file_entry_json[FILE_CID] = cid_str; file_entry_json[FILE_HASH] = (uint8_t *)&sealed_root; file_entry_json[FILE_CHAIN_BLOCK_NUM] = chain_block_num; // Status indicates current new file's status, which must be one of unverified, valid, lost and deleted file_entry_json[FILE_STATUS].AppendChar(FILE_STATUS_VALID).AppendChar(FILE_STATUS_UNVERIFIED).AppendChar(FILE_STATUS_UNVERIFIED); // Print sealed file information log_info("Seal complete, file info; cid: %s -> size: %ld, status: valid\n", file_entry_json[FILE_CID].ToString().c_str(), file_entry_json[FILE_SIZE].ToInt()); // Add new file sgx_thread_mutex_lock(&wl->file_mutex); size_t pos = 0; if (wl->is_file_dup_nolock(root, pos)) { if (FILE_STATUS_DELETED == wl->sealed_files[pos][FILE_STATUS].get_char(CURRENT_STATUS)) { wl->recover_from_deleted_file_buffer(root); } wl->sealed_files[pos] = file_entry_json; } else { wl->add_file_nolock(file_entry_json, pos); } // Delete info in workload spec wl->set_file_spec(FILE_STATUS_PENDING, -1); sgx_thread_mutex_unlock(&wl->file_mutex); // Add info in workload spec wl->set_file_spec(FILE_STATUS_VALID, file_entry_json[FILE_SIZE].ToInt()); // Store file information std::string file_info; file_info.append("{ \"" FILE_SIZE "\" : ").append(std::to_string(file_entry_json[FILE_SIZE].ToInt())).append(" , ") .append("\"" FILE_SEALED_SIZE "\" : ").append(std::to_string(file_entry_json[FILE_SEALED_SIZE].ToInt())).append(" , ") .append("\"" FILE_CHAIN_BLOCK_NUM "\" : ").append(std::to_string(chain_block_num)).append(" }"); ocall_store_file_info(root, file_info.c_str(), FILE_TYPE_VALID); crust_status = CRUST_SUCCESS; return crust_status; } /** * @description: Unseal file according to given path * @param path -> Pointer to file block stored path * @param p_decrypted_data -> Pointer to decrypted data buffer * @param decrypted_data_size -> Decrypted data buffer size * @param p_decrypted_data_size -> Pointer to decrypted data real size * @return: Unseal status */ crust_status_t storage_unseal_file(const char *path, uint8_t *p_decrypted_data, size_t /*decrypted_data_size*/, size_t *p_decrypted_data_size) { crust_status_t crust_status = CRUST_SUCCESS; uint8_t *p_unsealed_data = NULL; uint32_t unsealed_data_sz = 0; // Get sealed file block data uint8_t *p_data = NULL; size_t data_size = 0; if (CRUST_SUCCESS != (crust_status = storage_get_file(path, &p_data, &data_size))) { return crust_status; } Defer defer_data([&p_data](void) { free(p_data); }); // Do unseal if (CRUST_SUCCESS != (crust_status = unseal_data_mrsigner((sgx_sealed_data_t *)p_data, data_size, &p_unsealed_data, &unsealed_data_sz))) { return crust_status; } Defer def_decrypted_data([&p_unsealed_data](void) { free(p_unsealed_data); }); // Check if data is private data if (memcmp(p_unsealed_data, SWORKER_PRIVATE_TAG, strlen(SWORKER_PRIVATE_TAG)) == 0) { return CRUST_MALWARE_DATA_BLOCK; } // Store unsealed data *p_decrypted_data_size = unsealed_data_sz; memcpy(p_decrypted_data, p_unsealed_data, *p_decrypted_data_size); return crust_status; } /** * @description: Delete meaningful file * @param cid -> File root cid * @return: Delete status */ crust_status_t storage_delete_file(const char *cid) { // ----- Delete file items in metadata ----- // json::JSON deleted_file; crust_status_t crust_status = CRUST_SUCCESS; // ----- Delete file items in sealed_files ----- // Workload *wl = Workload::get_instance(); SafeLock sf_lock(wl->file_mutex); sf_lock.lock(); size_t pos = 0; if (wl->is_file_dup_nolock(cid, pos)) { if (wl->sealed_files[pos][FILE_STATUS].get_char(CURRENT_STATUS) == FILE_STATUS_DELETED) { log_info("File(%s) has been deleted!\n", cid); return CRUST_SUCCESS; } deleted_file = wl->sealed_files[pos]; wl->add_to_deleted_file_buffer(cid); wl->sealed_files[pos][FILE_STATUS].set_char(CURRENT_STATUS, FILE_STATUS_DELETED); } sf_lock.unlock(); if (deleted_file.size() > 0) { // ----- Delete file related data ----- // std::string del_cid = deleted_file[FILE_CID].ToString(); crust_status_t del_ret = CRUST_SUCCESS; // Delete all about file ocall_ipfs_del_all(&del_ret, del_cid.c_str()); // Update workload spec info wl->set_file_spec(deleted_file[FILE_STATUS].get_char(CURRENT_STATUS), -deleted_file[FILE_SIZE].ToInt()); // Delete pending file if (FILE_STATUS_PENDING == deleted_file[FILE_STATUS].get_char(CURRENT_STATUS)) { storage_seal_file_end(cid); } log_info("Delete file:%s successfully!\n", cid); } else { log_warn("Delete file:%s not found!\n", cid); crust_status = CRUST_STORAGE_NEW_FILE_NOTFOUND; } return crust_status; } /** * @description: Check if to be sealed file is duplicated, must hold file_mutex before invoking this function * @param cid -> IPFS content id * @return: Can seal file or not */ crust_status_t check_seal_file_dup(std::string cid) { Workload *wl = Workload::get_instance(); crust_status_t crust_status = CRUST_SUCCESS; size_t pos = 0; if (wl->is_file_dup_nolock(cid, pos)) { crust_status = CRUST_STORAGE_FILE_DUP; char cur_s = wl->sealed_files[pos][FILE_STATUS].get_char(CURRENT_STATUS); char org_s = wl->sealed_files[pos][FILE_STATUS].get_char(ORIGIN_STATUS); if (FILE_STATUS_PENDING == cur_s) { crust_status = CRUST_STORAGE_FILE_SEALING; } else if (FILE_STATUS_DELETED == cur_s) { if (FILE_STATUS_DELETED == org_s || FILE_STATUS_UNVERIFIED == org_s) { crust_status = CRUST_SUCCESS; wl->del_file_nolock(pos); } else { // If the original status is valid, we cannot seal the same new file. // If do that, increasement report may be crashed due to unknown work report result crust_status = CRUST_STORAGE_FILE_DELETING; log_info("File(%s) is being deleted, please wait.\n", cid.c_str()); } } } if (CRUST_SUCCESS == crust_status) { json::JSON file_entry_json; file_entry_json[FILE_CID] = cid; // Set file status to 'FILE_STATUS_PENDING,FILE_STATUS_UNVERIFIED,FILE_STATUS_UNVERIFIED' file_entry_json[FILE_STATUS].AppendChar(FILE_STATUS_PENDING).AppendChar(FILE_STATUS_UNVERIFIED).AppendChar(FILE_STATUS_UNVERIFIED); wl->add_file_nolock(file_entry_json, pos); } return crust_status; } /** * @description: Get the hashs of links from ipfs block * @param block_data -> ipfs block data * @param bs -> ipfs block size * @param hashs -> Return hashs, which need to be released when used up * @return: Status */ crust_status_t get_hashs_from_block(const uint8_t *block_data, size_t bs, std::vector<uint8_t *> &hashs) { if (block_data == NULL || bs == 0) { return CRUST_SUCCESS; } int block_size = int(bs); int index = 0; bool is_err = false; Defer def_plain_data([&hashs, &is_err](void) { if (is_err) { for (size_t i = 0; i < hashs.size(); i++) { free(hashs[i]); } hashs.clear(); } }); while (index < block_size) { // Skip link header if (block_data[index] != 0x12) { break; } index++; // Get all link size int link_size = 0; for (uint8_t shift = 0;;shift += 7) { if(shift >= 64) { is_err = true; return CRUST_SUCCESS; } if(index >= block_size) { is_err = true; return CRUST_SUCCESS; } uint8_t b = block_data[index]; index++; link_size |= int(b&0x7F) << shift; if(b < 0x80) { break; } } if (link_size < 0 || index + link_size < 0 || index + link_size >= block_size) { is_err = true; break; } size_t index_header = index; // Skip link hash header if (block_data[index] != 0x0a) { break; } index++; // Get link hash size int hash_with_prefix_size = 0; for (uint8_t shift = 0;;shift += 7) { if (shift >= 64) { is_err = true; return CRUST_SUCCESS; } if(index >= block_size) { is_err = true; return CRUST_SUCCESS; } uint8_t b = block_data[index]; index++; hash_with_prefix_size |= int(b&0x7F) << shift; if(b < 0x80) { break; } } if (hash_with_prefix_size < 0 || index + hash_with_prefix_size < HASH_LENGTH + 2 || index + hash_with_prefix_size >= block_size) { is_err = true; break; } if (block_data[index + hash_with_prefix_size - HASH_LENGTH - 1] != 0x20 || block_data[index + hash_with_prefix_size - HASH_LENGTH - 2] != 0x12) { is_err = true; break; } uint8_t* hash = (uint8_t *)enc_malloc(HASH_LENGTH); if (hash == NULL) { is_err = true; return CRUST_MALLOC_FAILED; } memcpy(hash, block_data + index + hash_with_prefix_size - HASH_LENGTH, HASH_LENGTH); hashs.push_back(hash); index = index_header + link_size; } return CRUST_SUCCESS; } /** * @description: Storage get file data * @param path -> File path * @param p_data -> Pointer to pointer file data * @param data_size -> Pointer to data size * @return: Get result */ crust_status_t storage_get_file(const char *path, uint8_t **p_data, size_t *data_size) { crust_status_t crust_status = CRUST_SUCCESS; ocall_get_file(&crust_status, path, p_data, data_size, STORE_TYPE_FILE); if (CRUST_SUCCESS != crust_status) { return crust_status; } uint8_t *p_sealed_data = (uint8_t *)enc_malloc(*data_size); if (p_sealed_data == NULL) { ocall_free_outer_buffer(&crust_status, p_data); return CRUST_MALLOC_FAILED; } memset(p_sealed_data, 0, *data_size); memcpy(p_sealed_data, *p_data, *data_size); ocall_free_outer_buffer(&crust_status, p_data); *p_data = p_sealed_data; return crust_status; } /** * @description: Get ipfs block * @param cid -> Ipfs content id * @param p_data -> Ipfs data * @param data_size -> Pointer to ipfs data size * @return: Get status */ crust_status_t storage_ipfs_get_block(const char *cid, uint8_t **p_data, size_t *data_size) { crust_status_t crust_status = CRUST_SUCCESS; ocall_ipfs_get_block(&crust_status, cid, p_data, data_size); if (CRUST_SUCCESS != crust_status) { return crust_status; } uint8_t *p_enc_data = (uint8_t *)enc_malloc(*data_size); if (p_enc_data == NULL) { ocall_free_outer_buffer(&crust_status, p_data); return CRUST_MALLOC_FAILED; } memset(p_enc_data, 0, *data_size); memcpy(p_enc_data, *p_data, *data_size); ocall_free_outer_buffer(&crust_status, p_data); *p_data = p_enc_data; return crust_status; } /** * @description: Ipfs cat data by content id * @param cid -> Ipfs content id * @param p_data -> Ipfs data * @param data_size -> Pointer to ipfs data size * @return: Cat status */ crust_status_t storage_ipfs_cat(const char *cid, uint8_t **p_data, size_t *data_size) { crust_status_t crust_status = CRUST_SUCCESS; ocall_ipfs_cat(&crust_status, cid, p_data, data_size); if (CRUST_SUCCESS != crust_status) { return crust_status; } uint8_t *p_enc_data = (uint8_t *)enc_malloc(*data_size); if (p_enc_data == NULL) { ocall_free_outer_buffer(&crust_status, p_data); return CRUST_MALLOC_FAILED; } memset(p_enc_data, 0, *data_size); memcpy(p_enc_data, *p_data, *data_size); ocall_free_outer_buffer(&crust_status, p_data); *p_data = p_enc_data; return crust_status; }
26,331
C++
.cpp
724
28.792818
154
0.587906
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,316
Workload.cpp
crustio_crust-sworker/src/enclave/workload/Workload.cpp
#include "Workload.h" sgx_thread_mutex_t g_workload_mutex = SGX_THREAD_MUTEX_INITIALIZER; sgx_thread_mutex_t g_report_flag_mutex = SGX_THREAD_MUTEX_INITIALIZER; sgx_thread_mutex_t g_upgrade_status_mutex = SGX_THREAD_MUTEX_INITIALIZER; Workload *Workload::workload = NULL; /** * @description: Single instance class function to get instance * @return: Workload instance */ Workload *Workload::get_instance() { if (Workload::workload == NULL) { sgx_thread_mutex_lock(&g_workload_mutex); if (Workload::workload == NULL) { Workload::workload = new Workload(); } sgx_thread_mutex_unlock(&g_workload_mutex); } return Workload::workload; } /** * @description: Initialize workload */ Workload::Workload() { this->report_files = true; for (auto item : g_file_spec_status) { this->wl_file_spec[item.second]["num"] = 0; this->wl_file_spec[item.second]["size"] = 0; } } /** * @description: Destructor */ Workload::~Workload() { for (auto g_hash : this->srd_hashs) { if (g_hash != NULL) free(g_hash); } this->srd_hashs.clear(); } /** * @description: Clean up work report data */ void Workload::clean_srd() { for (auto g_hash : this->srd_hashs) { if (g_hash != NULL) free(g_hash); } this->srd_hashs.clear(); // Clean srd info json this->srd_info_json = json::Object(); std::string srd_info_str = this->srd_info_json.dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); } /** * @description: Generate workload info * @param status -> Pointer to result status * @return: Workload info in json format */ json::JSON Workload::gen_workload_info(crust_status_t *status) { *status = CRUST_SUCCESS; // Generate srd information sgx_sha256_hash_t srd_root; json::JSON ans; SafeLock sl_srd(this->srd_mutex); sl_srd.lock(); if (this->srd_hashs.size() == 0) { memset(&srd_root, 0, sizeof(sgx_sha256_hash_t)); ans[WL_SRD_ROOT_HASH] = reinterpret_cast<uint8_t *>(&srd_root); } else { size_t srds_data_sz = this->srd_hashs.size() * SRD_LENGTH; uint8_t *srds_data = (uint8_t *)enc_malloc(srds_data_sz); if (srds_data == NULL) { log_err("Generate srd info failed due to malloc failed!\n"); *status = CRUST_MALLOC_FAILED; return ans; } Defer Def_srds_data([&srds_data](void) { free(srds_data); }); memset(srds_data, 0, srds_data_sz); for (size_t i = 0; i < this->srd_hashs.size(); i++) { memcpy(srds_data + i * SRD_LENGTH, this->srd_hashs[i], SRD_LENGTH); } ans[WL_SRD_SPACE] = this->srd_hashs.size() * 1024 * 1024 * 1024; sgx_sha256_msg(srds_data, (uint32_t)srds_data_sz, &srd_root); ans[WL_SRD_ROOT_HASH] = reinterpret_cast<uint8_t *>(&srd_root); } sl_srd.unlock(); // Generate file information sgx_sha256_hash_t file_root; SafeLock sl_file(this->file_mutex); sl_file.lock(); if (this->sealed_files.size() == 0) { memset(&file_root, 0, sizeof(sgx_sha256_hash_t)); ans[WL_FILE_ROOT_HASH] = reinterpret_cast<uint8_t *>(&file_root); } else { std::vector<uint8_t> file_buffer; for (size_t i = 0; i < this->sealed_files.size(); i++) { // Do not calculate pending status file if (FILE_STATUS_PENDING == this->sealed_files[i][FILE_STATUS].get_char(CURRENT_STATUS)) { continue; } *status = vector_end_insert(file_buffer, this->sealed_files[i][FILE_HASH].ToBytes(), HASH_LENGTH); if (CRUST_SUCCESS != *status) { return ans; } } sgx_sha256_msg(file_buffer.data(), file_buffer.size(), &file_root); ans[WL_FILE_ROOT_HASH] = reinterpret_cast<uint8_t *>(&file_root); } sl_file.unlock(); return ans; } /** * @description: Serialize workload for sealing * @return: Serialized workload */ json::JSON Workload::serialize_srd() { sgx_thread_mutex_lock(&this->srd_mutex); std::vector<uint8_t *> srd_hashs; srd_hashs.insert(srd_hashs.end(), this->srd_hashs.begin(), this->srd_hashs.end()); sgx_thread_mutex_unlock(&this->srd_mutex); // Get srd buffer json::JSON srd_buffer = json::Array(); for (size_t i = 0; i < srd_hashs.size(); i++) { srd_buffer.append(hexstring_safe(srd_hashs[i], SRD_LENGTH)); } return srd_buffer; } /** * @description: Serialize workload for sealing * @param status -> Pointer to result status * @return: Serialized workload */ json::JSON Workload::get_upgrade_srd_info(crust_status_t *status) { SafeLock sl(this->srd_mutex); sl.lock(); *status = CRUST_SUCCESS; json::JSON srd_buffer; // Get srd root hash sgx_sha256_hash_t srd_root; if (this->srd_hashs.size() == 0) { memset(&srd_root, 0, sizeof(sgx_sha256_hash_t)); } else { size_t srds_data_sz = this->srd_hashs.size() * SRD_LENGTH; uint8_t *srds_data = (uint8_t *)enc_malloc(srds_data_sz); if (srds_data == NULL) { log_err("Generate srd info failed due to malloc failed!\n"); *status = CRUST_MALLOC_FAILED; return srd_buffer; } Defer Def_srds_data([&srds_data](void) { free(srds_data); }); memset(srds_data, 0, srds_data_sz); for (size_t i = 0; i < this->srd_hashs.size(); i++) { memcpy(srds_data + i * SRD_LENGTH, this->srd_hashs[i], SRD_LENGTH); } sgx_sha256_msg(srds_data, (uint32_t)srds_data_sz, &srd_root); } srd_buffer[WL_SRD_ROOT_HASH] = (uint8_t *)&srd_root; log_debug("Generate srd root hash successfully!\n"); // Get srd buffer srd_buffer[WL_SRD] = json::Array(); for (size_t i = 0; i < this->srd_hashs.size(); i++) { srd_buffer[WL_SRD].append(hexstring_safe(this->srd_hashs[i], SRD_LENGTH)); } return srd_buffer; } /** * @description: Serialize file for sealing * @return: Serialized result */ json::JSON Workload::serialize_file() { sgx_thread_mutex_lock(&this->file_mutex); std::vector<json::JSON> tmp_sealed_files; tmp_sealed_files.insert(tmp_sealed_files.end(), this->sealed_files.begin(), this->sealed_files.end()); sgx_thread_mutex_unlock(&this->file_mutex); // Get file buffer json::JSON file_buffer = json::Array(); for (size_t i = 0; i < tmp_sealed_files.size(); i++) { if (FILE_STATUS_PENDING == tmp_sealed_files[i][FILE_STATUS].get_char(CURRENT_STATUS)) { json::JSON file; file[FILE_CID] = tmp_sealed_files[i][FILE_CID].ToString(); file[FILE_STATUS] = tmp_sealed_files[i][FILE_STATUS].ToString(); tmp_sealed_files[i] = file; } file_buffer.append(tmp_sealed_files[i]); } return file_buffer; } /** * @description: Serialize file for sealing * @param status -> Pointer to result status * @return: Serialized result */ json::JSON Workload::get_upgrade_file_info(crust_status_t *status) { SafeLock sl(this->file_mutex); sl.lock(); *status = CRUST_SUCCESS; json::JSON file_buffer; // Generate file information sgx_sha256_hash_t file_root; if (this->sealed_files.size() == 0) { memset(&file_root, 0, sizeof(sgx_sha256_hash_t)); } else { std::vector<uint8_t> file_hashs; for (size_t i = 0; i < this->sealed_files.size(); i++) { if (FILE_STATUS_PENDING == this->sealed_files[i][FILE_STATUS].get_char(CURRENT_STATUS)) { continue; } if (CRUST_SUCCESS != (*status = vector_end_insert(file_hashs, this->sealed_files[i][FILE_HASH].ToBytes(), HASH_LENGTH))) { return file_buffer; } } sgx_sha256_msg(file_hashs.data(), file_hashs.size(), &file_root); } file_buffer[WL_FILE_ROOT_HASH] = (uint8_t *)&file_root; log_debug("Generate file root hash successfully!\n"); // Get file buffer file_buffer[WL_FILES] = json::Array(); for (size_t i = 0; i < this->sealed_files.size(); i++) { if (FILE_STATUS_PENDING == this->sealed_files[i][FILE_STATUS].get_char(CURRENT_STATUS)) { continue; } file_buffer[WL_FILES].append(this->sealed_files[i]); } return file_buffer; } /** * @description: Restore workload from serialized workload * @param g_hashs -> G hashs json data * @return: Restore status */ crust_status_t Workload::restore_srd(json::JSON &g_hashs) { if (g_hashs.JSONType() != json::JSON::Class::Array) return CRUST_BAD_SEAL_DATA; if (g_hashs.size() == 0) return CRUST_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; this->clean_srd(); // Restore srd_hashs for (auto it : g_hashs.ArrayRange()) { std::string hex_g_hash = it.ToString(); uint8_t *g_hash = hex_string_to_bytes(hex_g_hash.c_str(), hex_g_hash.size()); if (g_hash == NULL) { this->clean_srd(); return CRUST_UNEXPECTED_ERROR; } this->srd_hashs.push_back(g_hash); // Restore srd detail std::string uuid = hex_g_hash.substr(0, UUID_LENGTH * 2); this->srd_info_json[WL_SRD_DETAIL][uuid].AddNum(1); } // Restore srd info this->srd_info_json[WL_SRD_COMPLETE] = this->srd_hashs.size(); // Restore srd info std::string srd_info_str = this->get_srd_info().dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); return crust_status; } /** * @description: Clean file related data */ void Workload::clean_file() { // Clean sealed files this->sealed_files.clear(); // Clean workload spec info this->wl_file_spec = json::JSON(); // Clean file info safe_ocall_store2(OCALL_FILE_INFO_ALL, reinterpret_cast<const uint8_t *>("{}"), 2); } /** * @description: Restore file from json * @param file_json -> File json * @return: Restore file result */ crust_status_t Workload::restore_file(json::JSON &file_json) { if (file_json.JSONType() != json::JSON::Class::Array) return CRUST_BAD_SEAL_DATA; if (file_json.size() == 0) return CRUST_SUCCESS; this->sealed_files.clear(); for (int i = 0; i < file_json.size(); i++) { char s = file_json[i][FILE_STATUS].get_char(CURRENT_STATUS); if (FILE_STATUS_PENDING == s) { crust_status_t del_ret = CRUST_SUCCESS; std::string cid = file_json[i][FILE_CID].ToString(); // Delete file directory ocall_delete_ipfs_file(&del_ret, cid.c_str()); // Delete file tree structure persist_del(cid); } else { this->sealed_files.push_back(file_json[i]); // Restore workload spec info this->set_file_spec(s, file_json[i][FILE_SIZE].ToInt()); } } // Restore file information this->restore_file_info(); return CRUST_SUCCESS; } /** * @description: Set report file flag * @param flag -> Report flag */ void Workload::set_report_file_flag(bool flag) { sgx_thread_mutex_lock(&g_report_flag_mutex); this->report_files = flag; sgx_thread_mutex_unlock(&g_report_flag_mutex); } /** * @description: Get report flag * @return: Report flag */ bool Workload::get_report_file_flag() { SafeLock sl(g_report_flag_mutex); sl.lock(); return this->report_files; } /** * @description: Set srd remaining task * @param num -> Srd remaining task number */ void Workload::set_srd_remaining_task(long num) { sgx_thread_mutex_lock(&this->srd_info_mutex); this->srd_info_json[WL_SRD_REMAINING_TASK] = num; sgx_thread_mutex_unlock(&this->srd_info_mutex); } /** * @description: Set srd info * @param uuid -> Disk path uuid * @param change -> Change number */ void Workload::set_srd_info(const char *uuid, long change) { std::string uuid_str(uuid); sgx_thread_mutex_lock(&this->srd_info_mutex); this->srd_info_json[WL_SRD_COMPLETE].AddNum(change); if (this->srd_info_json[WL_SRD_COMPLETE].ToInt() <= 0) { this->srd_info_json[WL_SRD_COMPLETE] = 0; } this->srd_info_json[WL_SRD_DETAIL][uuid_str].AddNum(change); sgx_thread_mutex_unlock(&this->srd_info_mutex); } /** * @description: Get srd info * @return: Return srd info json */ json::JSON Workload::get_srd_info() { sgx_thread_mutex_lock(&this->srd_info_mutex); if (this->srd_info_json.size() <= 0) { this->srd_info_json = json::Object(); } json::JSON srd_info = this->srd_info_json; sgx_thread_mutex_unlock(&this->srd_info_mutex); return srd_info; } /** * @description: Set upgrade flag * @param pub_key -> Previous version's public key */ void Workload::set_upgrade(sgx_ec256_public_t pub_key) { this->upgrade = true; memcpy(&this->pre_pub_key, &pub_key, sizeof(sgx_ec256_public_t)); } /** * @description: Unset upgrade */ void Workload::unset_upgrade() { this->upgrade = false; } /** * @description: Restore previous public key * @param meta -> Reference to metadata * @return: Restore result */ crust_status_t Workload::restore_pre_pub_key(json::JSON &meta) { if (!meta.hasKey(ID_PRE_PUB_KEY)) { return CRUST_SUCCESS; } sgx_ec256_public_t pre_pub_key; std::string pre_pub_key_str = meta[ID_PRE_PUB_KEY].ToString(); uint8_t *pre_pub_key_u = hex_string_to_bytes(pre_pub_key_str.c_str(), pre_pub_key_str.size()); if (pre_pub_key_u == NULL) { return CRUST_UNEXPECTED_ERROR; } memcpy(&pre_pub_key, pre_pub_key_u, sizeof(sgx_ec256_public_t)); free(pre_pub_key_u); this->set_upgrade(pre_pub_key); return CRUST_SUCCESS; } /** * @description: Get upgrade flag * @return: Upgrade flag */ bool Workload::is_upgrade() { return this->upgrade; } /** * @description: Set is_upgrading flag * @param status -> Enclave upgrade status */ void Workload::set_upgrade_status(enc_upgrade_status_t status) { sgx_thread_mutex_lock(&g_upgrade_status_mutex); this->upgrade_status = status; switch (status) { case ENC_UPGRADE_STATUS_NONE: log_info("Set upgrade status:ENC_UPGRADE_STATUS_NONE\n"); break; case ENC_UPGRADE_STATUS_PROCESS: log_info("Set upgrade status:ENC_UPGRADE_STATUS_PROCESS\n"); break; case ENC_UPGRADE_STATUS_SUCCESS: log_info("Set upgrade status:ENC_UPGRADE_STATUS_SUCCESS\n"); break; default: log_info("Unknown upgrade status!\n"); } sgx_thread_mutex_unlock(&g_upgrade_status_mutex); } /** * @description: Get is_upgrading flag * @return: Enclave upgrade status */ enc_upgrade_status_t Workload::get_upgrade_status() { SafeLock sl(g_upgrade_status_mutex); sl.lock(); return this->upgrade_status; } /** * @description: Handle workreport result */ void Workload::handle_report_result() { bool handled = false; // Set file status by report result sgx_thread_mutex_lock(&this->file_mutex); for (auto cid : this->reported_files_idx) { size_t pos = 0; if (this->is_file_dup_nolock(cid, pos)) { auto status = &this->sealed_files[pos][FILE_STATUS]; status->set_char(ORIGIN_STATUS, status->get_char(WAITING_STATUS)); handled = true; } } this->reported_files_idx.clear(); sgx_thread_mutex_unlock(&this->file_mutex); // Store changed metadata if (handled) { id_store_metadata(); } } /** * @description: Check if can report workreport * @param block_height -> Block height * @return: Check status */ crust_status_t Workload::can_report_work(size_t block_height) { if (block_height == 0 || block_height < REPORT_SLOT + this->get_report_height() + REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT) { return CRUST_UPGRADE_BLOCK_EXPIRE; } if (!this->report_has_validated_proof()) { return CRUST_UPGRADE_NO_VALIDATE; } if (this->get_restart_flag()) { return CRUST_UPGRADE_RESTART; } return CRUST_SUCCESS; } /** * @description: Set workload spec information * @param file_status -> Workload spec * @param change -> Spec information change */ void Workload::set_file_spec(char file_status, long long change) { if (g_file_spec_status.find(file_status) != g_file_spec_status.end()) { sgx_thread_mutex_lock(&wl_file_spec_mutex); std::string ws_name = g_file_spec_status[file_status]; this->wl_file_spec[ws_name]["num"].AddNum(change > 0 ? 1 : -1); this->wl_file_spec[ws_name]["size"].AddNum(change); sgx_thread_mutex_unlock(&wl_file_spec_mutex); } } /** * @description: Get workload spec info reference * @return: Const reference to wl_file_spec */ const json::JSON &Workload::get_file_spec() { SafeLock sl(wl_file_spec_mutex); sl.lock(); return this->wl_file_spec; } /** * @description: Set chain account id * @param account_id -> Chain account id */ void Workload::set_account_id(std::string account_id) { this->account_id = account_id; } /** * @description: Get chain account id * @return: Chain account id */ std::string Workload::get_account_id() { return this->account_id; } /** * @description: Can get key pair or not * @return: Get result */ bool Workload::try_get_key_pair() { return this->is_set_key_pair; } /** * @description: Get public key * @return: Const reference to public key */ const sgx_ec256_public_t &Workload::get_pub_key() { return this->id_key_pair.pub_key; } /** * @description: Get private key * @return: Const reference to private key */ const sgx_ec256_private_t &Workload::get_pri_key() { return this->id_key_pair.pri_key; } /** * @description: Set identity key pair * @param id_key_pair -> Identity key pair */ void Workload::set_key_pair(ecc_key_pair id_key_pair) { memcpy(&this->id_key_pair.pub_key, &id_key_pair.pub_key, sizeof(sgx_ec256_public_t)); memcpy(&this->id_key_pair.pri_key, &id_key_pair.pri_key, sizeof(sgx_ec256_private_t)); this->is_set_key_pair = true; } /** * @description: Unset id key pair */ void Workload::unset_key_pair() { this->is_set_key_pair = false; } /** * @description: Get identity key pair * @return: Const reference to identity key pair */ const ecc_key_pair &Workload::get_key_pair() { return this->id_key_pair; } /** * @description: Set MR enclave * @param mr -> MR enclave */ void Workload::set_mr_enclave(sgx_measurement_t mr) { memcpy(&this->mr_enclave, &mr, sizeof(sgx_measurement_t)); } /** * @description: Get MR enclave * @return: Const reference to MR enclave */ const sgx_measurement_t &Workload::get_mr_enclave() { return this->mr_enclave; } /** * @description: Set report height * @param height -> Report height */ void Workload::set_report_height(size_t height) { sgx_thread_mutex_lock(&this->report_height_mutex); this->report_height = height; sgx_thread_mutex_unlock(&this->report_height_mutex); } /** * @description: Get report height * @return: Report height */ size_t Workload::get_report_height() { SafeLock sl(this->report_height_mutex); sl.lock(); return this->report_height; } /** * @description: Clean all workload information */ void Workload::clean_all() { // Clean srd this->clean_srd(); // Clean file this->clean_file(); // Clean id key pair this->unset_key_pair(); // Clean upgrade related this->unset_upgrade(); } /** * @description: Set restart flag */ void Workload::set_restart_flag() { this->restart_flag = 1; } /** * @description: Reduce flag */ void Workload::reduce_restart_flag() { this->restart_flag -= 1; if (this->restart_flag < 0) { this->restart_flag = 0; } } /** * @description: Get restart flag * @return: Restart flag */ bool Workload::get_restart_flag() { return this->restart_flag > 0; } /** * @description: add validated srd proof */ void Workload::report_add_validated_srd_proof() { sgx_thread_mutex_lock(&this->validated_srd_mutex); if (this->validated_srd_proof >= VALIDATE_PROOF_MAX_NUM) { this->validated_srd_proof = VALIDATE_PROOF_MAX_NUM; } else { this->validated_srd_proof++; } sgx_thread_mutex_unlock(&this->validated_srd_mutex); } /** * @description: add validated file proof */ void Workload::report_add_validated_file_proof() { sgx_thread_mutex_lock(&this->validated_file_mutex); if (this->validated_file_proof >= VALIDATE_PROOF_MAX_NUM) { this->validated_file_proof = VALIDATE_PROOF_MAX_NUM; } else { this->validated_file_proof++; } sgx_thread_mutex_unlock(&this->validated_file_mutex); } /** * @description: Reset validated proof */ void Workload::report_reset_validated_proof() { sgx_thread_mutex_lock(&this->validated_srd_mutex); this->validated_srd_proof = 0; sgx_thread_mutex_unlock(&this->validated_srd_mutex); sgx_thread_mutex_lock(&this->validated_file_mutex); this->validated_file_proof = 0; sgx_thread_mutex_unlock(&this->validated_file_mutex); } /** * @description: Has validated proof * @return: true or false */ bool Workload::report_has_validated_proof() { sgx_thread_mutex_lock(&this->validated_srd_mutex); bool res = (this->validated_srd_proof > 0); sgx_thread_mutex_unlock(&this->validated_srd_mutex); sgx_thread_mutex_lock(&this->validated_file_mutex); res = (res && this->validated_file_proof > 0); sgx_thread_mutex_unlock(&this->validated_file_mutex); return res; } /** * @description: Add deleted srd to buffer * @param index -> Srd index in indicated path * @return: Add result */ bool Workload::add_srd_to_deleted_buffer(uint32_t index) { sgx_thread_mutex_lock(&this->srd_del_idx_mutex); auto ret_val = this->srd_del_idx_s.insert(index); sgx_thread_mutex_unlock(&this->srd_del_idx_mutex); return ret_val.second; } /** * @description: Has given srd been added to buffer * @param index -> Srd index in indicated path * @return: Added to deleted buffer or not */ bool Workload::is_srd_in_deleted_buffer(uint32_t index) { SafeLock sl(this->srd_del_idx_mutex); sl.lock(); return (this->srd_del_idx_s.find(index) != this->srd_del_idx_s.end()); } /** * @description: Delete invalid srd from metadata */ void Workload::deal_deleted_srd() { _deal_deleted_srd(true); } /** * @description: Delete invalid srd from metadata */ void Workload::deal_deleted_srd_nolock() { _deal_deleted_srd(false); } /** * @description: Delete invalid srd from metadata * @param locked -> Lock srd_hashs or not */ void Workload::_deal_deleted_srd(bool locked) { // Delete related srd from metadata by mainloop thread if (locked) { sgx_thread_mutex_lock(&this->srd_mutex); } sgx_thread_mutex_lock(&this->srd_del_idx_mutex); std::set<uint32_t> tmp_del_idx_s; // Put to be deleted srd to a buffer map and clean the old one tmp_del_idx_s.insert(this->srd_del_idx_s.begin(), this->srd_del_idx_s.end()); this->srd_del_idx_s.clear(); sgx_thread_mutex_unlock(&this->srd_del_idx_mutex); // Delete hashs this->delete_srd_meta(tmp_del_idx_s); if (locked) { sgx_thread_mutex_unlock(&this->srd_mutex); } } /** * @description: Add file to deleted buffer * @param cid -> File content id * @return: Added result */ bool Workload::add_to_deleted_file_buffer(std::string cid) { sgx_thread_mutex_lock(&this->file_del_idx_mutex); auto ret = this->file_del_cid_s.insert(cid); sgx_thread_mutex_unlock(&this->file_del_idx_mutex); return ret.second; } /** * @description: Is deleted file in buffer * @param cid -> File content id * @return: Check result */ bool Workload::is_in_deleted_file_buffer(std::string cid) { SafeLock sl(this->file_del_idx_mutex); sl.lock(); return (this->file_del_cid_s.find(cid) != this->file_del_cid_s.end()); } /** * @description: Recover file from deleted buffer * @param cid -> File content id */ void Workload::recover_from_deleted_file_buffer(std::string cid) { sgx_thread_mutex_lock(&this->file_del_idx_mutex); this->file_del_cid_s.erase(cid); sgx_thread_mutex_unlock(&this->file_del_idx_mutex); } /** * @description: Deal with deleted file */ void Workload::deal_deleted_file() { // Clear file deleted buffer sgx_thread_mutex_lock(&this->file_del_idx_mutex); std::set<std::string> tmp_del_cid_s = this->file_del_cid_s; this->file_del_cid_s.clear(); sgx_thread_mutex_unlock(&this->file_del_idx_mutex); // Deleted invalid file item std::set<std::string> left_del_cid_s = tmp_del_cid_s; SafeLock sealed_files_sl(this->file_mutex); sealed_files_sl.lock(); for (auto cid : tmp_del_cid_s) { size_t pos = 0; if (this->is_file_dup_nolock(cid, pos)) { std::string status = this->sealed_files[pos][FILE_STATUS].ToString(); if ((status[CURRENT_STATUS] == FILE_STATUS_DELETED && status[ORIGIN_STATUS] == FILE_STATUS_DELETED) || (status[CURRENT_STATUS] == FILE_STATUS_DELETED && status[ORIGIN_STATUS] == FILE_STATUS_UNVERIFIED && status[WAITING_STATUS] == FILE_STATUS_UNVERIFIED) || (status[CURRENT_STATUS] == FILE_STATUS_DELETED && status[ORIGIN_STATUS] == FILE_STATUS_LOST)) { this->sealed_files.erase(this->sealed_files.begin() + pos); left_del_cid_s.erase(cid); } } } sealed_files_sl.unlock(); // Put left file to file deleted set sgx_thread_mutex_lock(&this->file_del_idx_mutex); this->file_del_cid_s.insert(left_del_cid_s.begin(), left_del_cid_s.end()); sgx_thread_mutex_unlock(&this->file_del_idx_mutex); } /** * @description: Is file duplicated, must hold file_mutex before invoked * @param cid -> File's content id * @return: File duplicated or not */ bool Workload::is_file_dup_nolock(std::string cid) { size_t pos = 0; return is_file_dup_nolock(cid, pos); } /** * @description: Is file duplicated, must hold file_mutex before invoked * @param cid -> File's content id * @param pos -> Duplicated file's position * @return: Duplicated or not */ bool Workload::is_file_dup_nolock(std::string cid, size_t &pos) { long spos = 0; long epos = this->sealed_files.size(); while (spos <= epos) { long mpos = (spos + epos) / 2; if (mpos >= (long)this->sealed_files.size()) { break; } int ret = cid.compare(this->sealed_files[mpos][FILE_CID].ToString()); if (ret > 0) { spos = mpos + 1; pos = std::min(spos, (long)this->sealed_files.size()); } else if (ret < 0) { pos = mpos; epos = mpos - 1; } else { pos = mpos; return true; } } return false; } /** * @description: Add sealed file, must hold file_mutex before invoked * @param file -> File content * @param pos -> Inserted position */ void Workload::add_file_nolock(json::JSON file, size_t pos) { if (pos <= this->sealed_files.size()) { this->sealed_files.insert(this->sealed_files.begin() + pos, file); } } /** * @description: Add sealed file, must hold file_mutex before invoked * @param file -> File content */ void Workload::add_file_nolock(json::JSON file) { size_t pos = 0; if (is_file_dup_nolock(file[FILE_CID].ToString(), pos)) { return; } this->sealed_files.insert(this->sealed_files.begin() + pos, file); } /** * @description: Delete sealed file, must hold file_mutex before invoked * @param cid -> File content id */ void Workload::del_file_nolock(std::string cid) { size_t pos = 0; if (this->is_file_dup_nolock(cid, pos)) { this->sealed_files.erase(this->sealed_files.begin() + pos); } } /** * @description: Delete sealed file, must hold file_mutex before invoked * @param pos -> Deleted file position */ void Workload::del_file_nolock(size_t pos) { if (pos < this->sealed_files.size()) { this->sealed_files.erase(this->sealed_files.begin() + pos); } } /** * @description: Deal with file illegal transfer * @param data -> Pointer to recover data * @param data_size -> Recover data size * @return: Recover status */ crust_status_t Workload::recover_illegal_file(const uint8_t *data, size_t data_size) { crust_status_t crust_status = CRUST_SUCCESS; json::JSON commit_file = json::JSON::Load(&crust_status, data, data_size); if (CRUST_SUCCESS != crust_status) { return crust_status; } Workload *wl = Workload::get_instance(); SafeLock sl(wl->file_mutex); sl.lock(); std::vector<std::string> file_tag = {WORKREPORT_FILES_ADDED, WORKREPORT_FILES_DELETED}; for (auto type : file_tag) { if (commit_file.hasKey(type)) { if (commit_file[type].JSONType() == json::JSON::Class::Array) { for (auto file : commit_file[type].ArrayRange()) { size_t pos = 0; std::string cid = file.ToString(); if (wl->is_file_dup_nolock(cid, pos)) { if (type.compare(WORKREPORT_FILES_ADDED) == 0) { wl->sealed_files[pos][FILE_STATUS].set_char(ORIGIN_STATUS, FILE_STATUS_VALID); } else { char cur_status = wl->sealed_files[pos][FILE_STATUS].get_char(CURRENT_STATUS); char com_status = (FILE_STATUS_DELETED == cur_status ? FILE_STATUS_DELETED : FILE_STATUS_LOST); wl->sealed_files[pos][FILE_STATUS].set_char(ORIGIN_STATUS, com_status); } log_info("Recover illegal file:'%s' type:'%s' done\n", cid.c_str(), type.c_str()); } else { log_warn("Recover illegal: cannot find file:'%s'\n", cid.c_str()); } } } else { log_err("Recover illegal: %s is not an array!\n", type.c_str()); } } else { log_debug("Recover illegal: no %s provided.\n", type.c_str()); } } sl.unlock(); return crust_status; } /** * @description: Restore file informatione * @return: Restore file information result */ crust_status_t Workload::restore_file_info() { // ----- Construct file information json string ----- // crust_status_t crust_status = CRUST_SUCCESS; json::JSON file_buffer; for (auto it = g_file_spec_status.begin(); it != g_file_spec_status.end(); it++) { std::string file_type = it->second; char s = it->first; for (auto file : this->sealed_files) { if (s != file[FILE_STATUS].get_char(CURRENT_STATUS)) continue; json::JSON info; info[file[FILE_CID].ToString()] = "{ \"" FILE_SIZE "\" : " + std::to_string(file[FILE_SIZE].ToInt()) + " , \"" FILE_SEALED_SIZE "\" : " + std::to_string(file[FILE_SEALED_SIZE].ToInt()) + " , \"" FILE_CHAIN_BLOCK_NUM "\" : " + std::to_string(file[FILE_CHAIN_BLOCK_NUM].ToInt()) + " }"; file_buffer[file_type].append(info); } } // Store file information to app std::vector<uint8_t> file_data = file_buffer.dump_vector(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } return safe_ocall_store2(OCALL_FILE_INFO_ALL, file_data.data(), file_data.size()); }
32,365
C++
.cpp
1,080
24.756481
173
0.620876
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,317
PathHelper.cpp
crustio_crust-sworker/src/enclave/utils/PathHelper.cpp
#include "PathHelper.h" /** * @description: get the path of m_hashs.bin * @param g_path -> the G path * @return: the m_hashs.bin path */ std::string get_m_hashs_file_path(const char *g_path) { std::string file_path(g_path); file_path = file_path + '/' + SRD_M_HASHS; return file_path; } /** * @description: get the path of the leaf file * @param g_path -> the G path * @param now_index -> the index of the leaf file * @param hash -> the index of the leaf file * @return: the leaf file's path */ std::string get_leaf_path(const char *g_path, const size_t now_index, const unsigned char *hash) { std::string leaf_path = std::string(g_path) + "/" + std::to_string(now_index + 1); return leaf_path + '-' + unsigned_char_array_to_hex_string(hash, 32); } /** * @description: get the G path by using hash * @param dir_path -> the directory path * @param hash -> the index of G folder * @return: the G path */ std::string get_g_path_with_hash(const char *dir_path, const unsigned char *hash) { std::string g_path = std::string(dir_path) + "/"; return g_path + unsigned_char_array_to_hex_string(hash, HASH_LENGTH); } /** * @description: get the G path * @param dir_path -> the directory path * @param now_index -> the index of G folder * @return: the G path */ std::string get_g_path(const char *dir_path, const size_t now_index) { return std::string(dir_path) + "/" + std::to_string(now_index + 1); }
1,451
C++
.cpp
45
30
96
0.666191
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,318
SafeLock.cpp
crustio_crust-sworker/src/enclave/utils/SafeLock.cpp
#include "SafeLock.h" SafeLock::~SafeLock() { if (this->lock_time > 0) { sgx_thread_mutex_unlock(&this->_mutex); } } void SafeLock::lock() { if (this->lock_time == 0) { sgx_thread_mutex_lock(&this->_mutex); this->lock_time++; } } void SafeLock::unlock() { if (this->lock_time > 0) { this->lock_time--; sgx_thread_mutex_unlock(&this->_mutex); } }
425
C++
.cpp
24
13.416667
47
0.552764
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,319
EUtils.cpp
crustio_crust-sworker/src/enclave/utils/EUtils.cpp
#include "EUtils.h" #include "Json.h" using namespace std; static char *_hex_buffer = NULL; static size_t _hex_buffer_size = 0; const char _hextable[] = "0123456789abcdef"; int eprint_base(char buf[], int flag); /** * @description: Print flat normal info * @param fmt -> Output format * @return: the length of printed string */ int eprint_info(const char *fmt, ...) { char buf[LOG_BUF_SIZE] = {'\0'}; va_list ap; va_start(ap, fmt); vsnprintf(buf, LOG_BUF_SIZE, fmt, ap); va_end(ap); return eprint_base(buf, 0); } /** * @description: Print flat debug info * @param fmt -> Output format * @return: the length of printed string */ int eprint_debug(const char *fmt, ...) { char buf[LOG_BUF_SIZE] = {'\0'}; va_list ap; va_start(ap, fmt); vsnprintf(buf, LOG_BUF_SIZE, fmt, ap); va_end(ap); return eprint_base(buf, 1); } /** * @description: Flat printf base function * @param buf -> Print content * @param flag -> 0 for info, 1 for debug * @return: Print content length */ int eprint_base(char buf[], int flag) { switch (flag) { case 0: ocall_print_info(buf); break; case 1: ocall_print_debug(buf); break; } return (int)strnlen(buf, LOG_BUF_SIZE - 1) + 1; } /** * @description: use ocall_log_info to print format string * @param fmt -> Output format * @return: the length of printed string */ int log_info(const char *fmt, ...) { char buf[LOG_BUF_SIZE] = {'\0'}; va_list ap; va_start(ap, fmt); vsnprintf(buf, LOG_BUF_SIZE, fmt, ap); va_end(ap); ocall_log_info(buf); return (int)strnlen(buf, LOG_BUF_SIZE - 1) + 1; } /** * @description: use ocall_log_warn to print format string * @param fmt -> Output format * @return: the length of printed string */ int log_warn(const char *fmt, ...) { char buf[LOG_BUF_SIZE] = {'\0'}; va_list ap; va_start(ap, fmt); vsnprintf(buf, LOG_BUF_SIZE, fmt, ap); va_end(ap); ocall_log_warn(buf); return (int)strnlen(buf, LOG_BUF_SIZE - 1) + 1; } /** * @description: use ocall_log_err to print format string * @param fmt -> Output format * @return: the length of printed string */ int log_err(const char *fmt, ...) { char buf[LOG_BUF_SIZE] = {'\0'}; va_list ap; va_start(ap, fmt); vsnprintf(buf, LOG_BUF_SIZE, fmt, ap); va_end(ap); ocall_log_err(buf); return (int)strnlen(buf, LOG_BUF_SIZE - 1) + 1; } /** * @description: use ocall_log_debug to print format string * @param fmt -> Output format * @return: the length of printed string */ int log_debug(const char *fmt, ...) { char buf[LOG_BUF_SIZE] = {'\0'}; va_list ap; va_start(ap, fmt); vsnprintf(buf, LOG_BUF_SIZE, fmt, ap); va_end(ap); ocall_log_debug(buf); return (int)strnlen(buf, LOG_BUF_SIZE - 1) + 1; } /** * @description: Change char to int * @param input -> Input character * @return: Corresponding int */ int char_to_int(char input) { if (input >= '0' && input <= '9') return input - '0'; if (input >= 'A' && input <= 'F') return input - 'A' + 10; if (input >= 'a' && input <= 'f') return input - 'a' + 10; return 0; } /** * @description: Transform string to hexstring * @param vsrc -> Source byte array * @param len -> Srouce byte array length * @return: Hexstringed data */ char *hexstring(const void *vsrc, size_t len) { size_t i, bsz; const uint8_t *src = (const uint8_t *)vsrc; char *bp; bsz = len * 2 + 1; /* Make room for NULL byte */ if (bsz >= _hex_buffer_size) { /* Allocate in 1K increments. Make room for the NULL byte. */ size_t newsz = 1024 * (bsz / 1024) + ((bsz % 1024) ? 1024 : 0); _hex_buffer_size = newsz; _hex_buffer = (char *)enc_realloc(_hex_buffer, newsz); if (_hex_buffer == NULL) { return NULL; } } for (i = 0, bp = _hex_buffer; i < len; ++i) { *bp = _hextable[src[i] >> 4]; ++bp; *bp = _hextable[src[i] & 0xf]; ++bp; } _hex_buffer[len * 2] = 0; return _hex_buffer; } /** * @description: Transform string to hexstring, thread safe * @param vsrc -> Source byte array * @param len -> Srouce byte array length * @return: Hexstringed data */ std::string hexstring_safe(const void *vsrc, size_t len) { size_t i; const uint8_t *src = (const uint8_t *)vsrc; char *hex_buffer = (char *)enc_malloc(len * 2); if (hex_buffer == NULL) { return ""; } memset(hex_buffer, 0, len * 2); char *bp; for (i = 0, bp = hex_buffer; i < len; ++i) { *bp = _hextable[src[i] >> 4]; ++bp; *bp = _hextable[src[i] & 0xf]; ++bp; } std::string ans(hex_buffer, len * 2); free(hex_buffer); return ans; } /** * @description: Byte vector to string * @param bytes -> Byte vector * @return: Hexstring of byte vector */ std::string byte_vec_to_string(std::vector<uint8_t> bytes) { return hexstring_safe(bytes.data(), bytes.size()); } /** * @description: Convert hexstring to bytes array, note that * the size of got data is half of len * @param src -> Source char* * @param len -> Source char* length * @return: Bytes array */ uint8_t *hex_string_to_bytes(const void *src, size_t len) { if (len % 2 != 0 || len == 0) { return NULL; } const char *rsrc = (const char *)src; uint8_t *p_target; uint8_t *target = (uint8_t *)enc_malloc(len / 2); if (target == NULL) { return NULL; } memset(target, 0, len / 2); p_target = target; for (size_t i = 0; i < len; i += 2) { *(target++) = (uint8_t)(char_to_int(rsrc[0]) * 16 + char_to_int(rsrc[1])); rsrc += 2; } return p_target; } /** * @description: convert byte array to hex string * @param in -> byte array * @param size -> the size of byte array * @return: hex string */ std::string unsigned_char_array_to_hex_string(const unsigned char *in, size_t size) { char *result = new char[size * 2 + 1]; size_t now_pos = 0; for (size_t i = 0; i < size; i++) { char *temp = unsigned_char_to_hex(in[i]); result[now_pos++] = temp[0]; result[now_pos++] = temp[1]; delete[] temp; } result[now_pos] = '\0'; std::string out_str(result); delete[] result; return out_str; } /** * @description: convert byte array to byte vector * @param in -> byte array * @param size -> the size of byte array * @return: byte vector */ std::vector<unsigned char> unsigned_char_array_to_unsigned_char_vector(const unsigned char *in, size_t size) { std::vector<unsigned char> out(size); std::copy(in, in + size, out.begin()); return out; } /** * @description: convert byte to hex char array * @param in -> byte * @return: hex char array */ char *unsigned_char_to_hex(const unsigned char in) { char *result = new char[2]; if (in / 16 < 10) { result[0] = (char)(in / 16 + '0'); } else { result[0] = (char)(in / 16 - 10 + 'a'); } if (in % 16 < 10) { result[1] = (char)(in % 16 + '0'); } else { result[1] = (char)(in % 16 - 10 + 'a'); } return result; } /** * @description: Seal data by using input bytes with MRENCLAVE method * @param p_src -> bytes for seal * @param src_len -> the length of input bytes * @param p_sealed_data -> the output of seal * @param sealed_data_size -> the length of output bytes * @return: Seal status */ crust_status_t seal_data_mrenclave(const uint8_t *p_src, size_t src_len, sgx_sealed_data_t **p_sealed_data, size_t *sealed_data_size) { sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; uint32_t sealed_data_sz = sgx_calc_sealed_data_size(0, src_len); *p_sealed_data = (sgx_sealed_data_t *)enc_malloc(sealed_data_sz); if (*p_sealed_data == NULL) { log_err("Malloc memory failed!\n"); return CRUST_MALLOC_FAILED; } memset(*p_sealed_data, 0, sealed_data_sz); sgx_attributes_t sgx_attr; sgx_attr.flags = 0xFF0000000000000B; sgx_attr.xfrm = 0; sgx_misc_select_t sgx_misc = 0xF0000000; sgx_status = Sgx_seal_data_ex(0x0001, sgx_attr, sgx_misc, 0, NULL, src_len, p_src, sealed_data_sz, *p_sealed_data); if (SGX_SUCCESS != sgx_status) { log_err("Seal data failed!Error code:%lx\n", sgx_status); crust_status = CRUST_SEAL_DATA_FAILED; free(*p_sealed_data); *p_sealed_data = NULL; } *sealed_data_size = (size_t)sealed_data_sz; return crust_status; } /** * @description: Seal data by using input bytes with MRSIGNER method * @param p_src -> bytes for seal * @param src_len -> the length of input bytes * @param p_sealed_data -> the output of seal * @param sealed_data_size -> the length of output bytes * @return: Seal status */ crust_status_t seal_data_mrsigner(const uint8_t *p_src, size_t src_len, sgx_sealed_data_t **p_sealed_data, size_t *sealed_data_size) { sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; uint8_t *p_src_r = const_cast<uint8_t *>(p_src); uint32_t sealed_data_sz = sgx_calc_sealed_data_size(0, src_len); *p_sealed_data = (sgx_sealed_data_t *)enc_malloc(sealed_data_sz); if (*p_sealed_data == NULL) { log_err("Malloc memory failed!\n"); return CRUST_MALLOC_FAILED; } memset(*p_sealed_data, 0, sealed_data_sz); int ret = sgx_is_within_enclave(p_src, src_len); if (ret == 0) { p_src_r = (uint8_t *)enc_malloc(src_len); if (p_src_r == NULL) { return CRUST_MALLOC_FAILED; } memset(p_src_r, 0, src_len); memcpy(p_src_r, p_src, src_len); } Defer def_src_r([&p_src_r, &ret](void) { if (ret == 0) { free(p_src_r); } }); sgx_status = Sgx_seal_data(0, NULL, src_len, p_src_r, sealed_data_sz, *p_sealed_data); if (SGX_SUCCESS != sgx_status) { log_err("Seal data failed!Error code:%lx\n", sgx_status); free(*p_sealed_data); *p_sealed_data = NULL; return CRUST_SEAL_DATA_FAILED; } *sealed_data_size = (size_t)sealed_data_sz; return crust_status; } /** * @description: Validate merkle tree in json format * @param tree -> Merkle tree json format * @return: Validate status */ crust_status_t validate_merkletree_json(json::JSON tree) { if (tree[MT_LINKS].size() == 0) { return CRUST_SUCCESS; } if (tree[MT_LINKS].size() < 0) { return CRUST_UNEXPECTED_ERROR; } crust_status_t crust_status = CRUST_SUCCESS; sgx_sha256_hash_t parent_hash; uint8_t *parent_hash_org = NULL; uint8_t *parent_data_hash = NULL; // Validate sub tree and get all sub trees hash data size_t children_buffer_size = tree[MT_LINKS].size() * HASH_LENGTH; uint8_t *children_hashs = (uint8_t *)enc_malloc(children_buffer_size); if (children_hashs == NULL) { return CRUST_MALLOC_FAILED; } memset(children_hashs, 0, children_buffer_size); for (int i = 0; i < tree[MT_LINKS].size(); i++) { if (tree[MT_LINKS][i].hasKey(MT_LINKS)) { if (validate_merkletree_json(tree[MT_LINKS][i]) != CRUST_SUCCESS) { crust_status = CRUST_INVALID_MERKLETREE; goto cleanup; } } std::string hash; hash = tree[MT_LINKS][i][MT_DATA_HASH].ToString(); uint8_t *tmp_hash = hex_string_to_bytes(hash.c_str(), hash.size()); if (tmp_hash == NULL) { crust_status = CRUST_UNEXPECTED_ERROR; goto cleanup; } memcpy(children_hashs + i * HASH_LENGTH, tmp_hash, HASH_LENGTH); free(tmp_hash); } // Compute and compare hash value sgx_sha256_msg(children_hashs, children_buffer_size, &parent_hash); parent_hash_org = hex_string_to_bytes(tree[MT_HASH].ToString().c_str(), HASH_LENGTH * 2); if (parent_hash_org == NULL) { crust_status = CRUST_MALLOC_FAILED; goto cleanup; } if (memcmp(parent_hash_org, parent_hash, HASH_LENGTH) != 0) { crust_status = CRUST_NOT_EQUAL; goto cleanup; } cleanup: if (parent_data_hash != NULL) free(parent_data_hash); if (children_hashs != NULL) free(children_hashs); if (parent_hash_org != NULL) free(parent_hash_org); return crust_status; } /** * @description: Wrapper for malloc function, add tryout * @param size -> malloc buffer size * @return: Pointer to malloc buffer */ void *enc_malloc(size_t size) { int tryout = 0; void *p = NULL; while (tryout++ < ENCLAVE_MALLOC_TRYOUT && p == NULL) { p = (void *)malloc(size); } return p; } /** * @description: Wrapper for realloc function, add tryout * @param p -> Realloc pointer * @param size -> realloc buffer size * @return: Realloc buffer pointer */ void *enc_realloc(void *p, size_t size) { int tryout = 0; if (p != NULL) { free(p); p = NULL; } while (tryout++ < ENCLAVE_MALLOC_TRYOUT && p == NULL) { p = (void *)enc_malloc(size); } return p; } /** * @description: Malloc new size and copy old buffer to it * @param p -> Pointer to old buffer * @param old_size -> Old buffer size * @param new_size -> New buffer size * @return: Pointer to new buffer with old buffer data */ void *enc_crealloc(void *p, size_t old_size, size_t new_size) { void *old_p = NULL; if (old_size != 0 && p != NULL) { old_p = (void *)enc_malloc(old_size); if (old_p == NULL) { free(p); return NULL; } memset(old_p, 0, old_size); memcpy(old_p, p, old_size); } p = (void *)enc_realloc(p, new_size); if (p == NULL) { if (old_p != NULL) { free(old_p); } return NULL; } if (old_p != NULL) { memcpy(p, old_p, old_size); free(old_p); } return p; } /** * @description: A wrapper for sgx_seal_data * @param additional_MACtext_length -> Additional data length * @param p_additional_MACtext -> Pointer to additional data * @param text2encrypt_length -> Text to be encrypted length * @param p_text2encrypt -> Pointer to be encrypted data * @param sealed_data_size -> Sealed data size * @param p_sealed_data -> Pointer to sealed data * @return: Seal result status */ sgx_status_t Sgx_seal_data(const uint32_t additional_MACtext_length, const uint8_t *p_additional_MACtext, const uint32_t text2encrypt_length, const uint8_t *p_text2encrypt, const uint32_t sealed_data_size, sgx_sealed_data_t *p_sealed_data) { uint8_t *p_test = (uint8_t *)enc_malloc(sealed_data_size); if (p_test == NULL) { log_err("Malloc memory failed!\n"); return SGX_ERROR_OUT_OF_MEMORY; } free(p_test); return sgx_seal_data(additional_MACtext_length, p_additional_MACtext, text2encrypt_length, p_text2encrypt, sealed_data_size, p_sealed_data); } /** * @description: A wrapper function for sgx_seal_data_ex * @param key_policy -> Key policy * @param attribute_mask -> Attribute mask * @param misc_mask -> Misc mask * @param additional_MACtext_length -> Additional data length * @param p_additional_MACtext -> Pointer to additional data * @param text2encrypt_length -> Text to be encrypted length * @param p_text2encrypt -> Pointer to be encrypted data * @param sealed_data_size -> Sealed data size * @param p_sealed_data -> Pointer to sealed data * @return: Seal result status */ sgx_status_t Sgx_seal_data_ex(const uint16_t key_policy, const sgx_attributes_t attribute_mask, const sgx_misc_select_t misc_mask, const uint32_t additional_MACtext_length, const uint8_t *p_additional_MACtext, const uint32_t text2encrypt_length, const uint8_t *p_text2encrypt, const uint32_t sealed_data_size, sgx_sealed_data_t *p_sealed_data) { uint8_t *p_test = (uint8_t *)enc_malloc(sealed_data_size); if (p_test == NULL) { log_err("Malloc memory failed!\n"); return SGX_ERROR_OUT_OF_MEMORY; } free(p_test); return sgx_seal_data_ex(key_policy, attribute_mask, misc_mask, additional_MACtext_length, p_additional_MACtext, text2encrypt_length, p_text2encrypt, sealed_data_size, p_sealed_data); } /** * @description: Remove indicated character from given string * @param data -> Reference to given string * @param c -> Indicated character */ void remove_char(std::string &data, char c) { data.erase(std::remove(data.begin(), data.end(), c), data.end()); } /** * @description: Replace org_str to det_str in data * @param data -> Reference to origin data * @param org_str -> Replaced string * @param det_str -> Replaced to string */ void replace(std::string &data, std::string org_str, std::string det_str) { size_t spos, epos; spos = epos = 0; while (true) { spos = data.find(org_str, epos); if (spos == data.npos) { break; } data.replace(spos, org_str.size(), det_str); epos = spos + det_str.size(); } } /** * @description: base64 decode function * @param msg -> To be decoded message * @param sz -> Message size * @return: Decoded result */ char *base64_decode(const char *msg, size_t *sz) { BIO *b64, *bmem; char *buf; size_t len = strlen(msg); buf = (char *)enc_malloc(len + 1); if (buf == NULL) return NULL; memset(buf, 0, len + 1); b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new_mem_buf(msg, (int)len); BIO_push(b64, bmem); int rsz = BIO_read(b64, buf, (int)len); if (rsz == -1) { free(buf); return NULL; } *sz = rsz; BIO_free_all(bmem); return buf; } /** * @description: base58 encode function * @param input -> To be encoded message * @param len -> Message size * @return: Encoded result */ std::string base58_encode(const uint8_t *input, size_t len) { int length = 0, pbegin = 0, pend; if (!(pend = len)) { return ""; } int size = 1 + base58_ifactor * (double)(pend - pbegin); unsigned char b58[size] = {0}; while (pbegin != pend) { unsigned int carry = input[pbegin]; int i = 0; for (int it1 = size - 1; (carry || i < length) && (it1 != -1); it1--, i++) { carry += 256 * b58[it1]; b58[it1] = carry % 58; carry /= 58; } if (carry) { return 0; } length = i; pbegin++; } int it2 = size - length; while ((it2 - size) && !b58[it2]) { it2++; } std::string res(size - it2, '\0'); size_t res_index = 0; for (; it2 < size; ++it2) { res[res_index] = BASE58_ALPHABET[b58[it2]]; res_index++; } return res; } /** * @description: convert hash to cid function * @param hash -> To be encoded hash * @return: CID */ std::string hash_to_cid(const uint8_t *hash) { int length = 0, pbegin = 0, pend = HASH_LENGTH + 2; int size = 1 + base58_ifactor * (double)(pend - pbegin); unsigned char b58[size] = {0}; while (pbegin != pend) { unsigned int carry = pbegin == 0 ? 18 : pbegin == 1 ? 32 : hash[pbegin - 2]; int i = 0; for (int it1 = size - 1; (carry || i < length) && (it1 != -1); it1--, i++) { carry += 256 * b58[it1]; b58[it1] = carry % 58; carry /= 58; } if (carry) { return 0; } length = i; pbegin++; } int it2 = size - length; while ((it2 - size) && !b58[it2]) { it2++; } std::string res(size - it2, '\0'); size_t res_index = 0; for (; it2 < size; ++it2) { res[res_index] = BASE58_ALPHABET[b58[it2]]; res_index++; } return res; } /** * @description: Unseal decrypted data * @param data -> Pointer to sealed data * @param data_size -> Sealed data size * @param p_decrypted_data -> Pointer to pointer decrypted data * @param decrypted_data_len -> Poniter to decrypted data length * @return: Unseal result */ crust_status_t unseal_data_mrsigner(const sgx_sealed_data_t *data, uint32_t data_size, uint8_t **p_decrypted_data, uint32_t *decrypted_data_len) { sgx_sealed_data_t *data_r = const_cast<sgx_sealed_data_t *>(data); *decrypted_data_len = sgx_get_encrypt_txt_len(data); *p_decrypted_data = (uint8_t *)enc_malloc(*decrypted_data_len); if (*p_decrypted_data == NULL) { return CRUST_MALLOC_FAILED; } memset(*p_decrypted_data, 0, *decrypted_data_len); // Do unseal int ret = sgx_is_within_enclave(data, data_size); if (ret == 0) { data_r = (sgx_sealed_data_t *)enc_malloc(data_size); if (data_r == NULL) { return CRUST_MALLOC_FAILED; } memset(data_r, 0, data_size); memcpy(data_r, data, data_size); } Defer def_data_r([&data_r, &ret](void) { if (ret == 0) { free(data_r); } }); sgx_status_t sgx_status = sgx_unseal_data(data_r, NULL, NULL, *p_decrypted_data, decrypted_data_len); if (SGX_SUCCESS != sgx_status) { log_err("SGX unseal failed! Internal error:%lx\n", sgx_status); free(*p_decrypted_data); return CRUST_UNSEAL_DATA_FAILED; } return CRUST_SUCCESS; } /** * @description: Safe store data outside enclave * @param t -> Ocall function type * @param u -> Pointer to data * @param s -> Data length * @return: Ocall result */ crust_status_t safe_ocall_store2(ocall_store_type_t t, const uint8_t *u, size_t s) { sgx_status_t ret = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; size_t offset = 0; uint32_t buffer_key = 0; sgx_read_rand(reinterpret_cast<uint8_t *>(&buffer_key), sizeof(buffer_key)); while (s > offset) { size_t partial_size = std::min(s - offset, (size_t)BOUNDARY_SIZE_THRESHOLD); ret = ocall_safe_store2(&crust_status, t, u + offset, s, partial_size, offset, buffer_key); if (SGX_SUCCESS != ret) { return CRUST_SGX_FAILED; } if (CRUST_SUCCESS != crust_status) { return crust_status; } offset += partial_size; } return crust_status; } /** * @description: Get data from outside using enclave buffer * @param f -> Getting data ocall function * @param u -> Pointer to allocated buffer * @param s -> Pointer to allocated buffer size * @return: Get result */ crust_status_t safe_ocall_get2(ocall_get2_f f, uint8_t *u, size_t *s) { if (u == NULL || *s == 0) { return CRUST_UNEXPECTED_ERROR; } size_t os = *s; crust_status_t c_ret = CRUST_SUCCESS; sgx_status_t s_ret = f(&c_ret, u, os, s); if (SGX_SUCCESS != s_ret) { return CRUST_SGX_FAILED; } if (CRUST_SUCCESS != c_ret) { if (CRUST_OCALL_NO_ENOUGH_BUFFER == c_ret) { free (u); if (os == *s) { *s = *s * 2; } u = (uint8_t *)enc_malloc(*s); if (u == NULL) { return CRUST_MALLOC_FAILED; } s_ret = f(&c_ret, u, *s, s); if (SGX_SUCCESS != s_ret) { return CRUST_SGX_FAILED; } } } return c_ret; }
24,800
C++
.cpp
861
22.680604
108
0.57023
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,320
Validator.cpp
crustio_crust-sworker/src/enclave/validator/Validator.cpp
#include "Validator.h" // Srd related variables std::vector<uint8_t *> g_del_srd_v; sgx_thread_mutex_t g_del_srd_v_mutex = SGX_THREAD_MUTEX_INITIALIZER; std::map<int, uint8_t *> g_validate_srd_m; std::map<int, uint8_t *>::const_iterator g_validate_srd_m_iter; sgx_thread_mutex_t g_validate_srd_m_iter_mutex = SGX_THREAD_MUTEX_INITIALIZER; uint32_t g_validated_srd_num = 0; sgx_thread_mutex_t g_validated_srd_num_mutex = SGX_THREAD_MUTEX_INITIALIZER; // File related method and variables std::vector<json::JSON *> g_changed_files_v; sgx_thread_mutex_t g_changed_files_v_mutex = SGX_THREAD_MUTEX_INITIALIZER; std::map<std::string, json::JSON> g_validate_files_m; std::map<std::string, json::JSON>::const_iterator g_validate_files_m_iter; sgx_thread_mutex_t g_validate_files_m_iter_mutex = SGX_THREAD_MUTEX_INITIALIZER; uint32_t g_validated_files_num = 0; sgx_thread_mutex_t g_validated_files_num_mutex = SGX_THREAD_MUTEX_INITIALIZER; uint32_t g_validate_random = 0; sgx_thread_mutex_t g_validate_random_mutex = SGX_THREAD_MUTEX_INITIALIZER; /** * @description: validate srd disk */ void validate_srd() { crust_status_t crust_status = CRUST_SUCCESS; Workload *wl = Workload::get_instance(); Defer def_clean_del_buffer([&wl](void) { // Clean deleted srd wl->deal_deleted_srd(); }); if (ENC_UPGRADE_STATUS_SUCCESS == Workload::get_instance()->get_upgrade_status()) { return; } sgx_thread_mutex_lock(&wl->srd_mutex); std::map<int, uint8_t *> tmp_validate_srd_m; size_t srd_validate_num = std::max((size_t)(wl->srd_hashs.size() * SRD_VALIDATE_RATE), (size_t)SRD_VALIDATE_MIN_NUM); srd_validate_num = std::min(srd_validate_num, wl->srd_hashs.size()); // Randomly choose validate srd files uint32_t rand_val; uint32_t rand_idx = 0; if (srd_validate_num >= wl->srd_hashs.size()) { for (size_t i = 0; i < wl->srd_hashs.size(); i++) { tmp_validate_srd_m[i] = wl->srd_hashs[i]; } } else { for (size_t i = 0; i < srd_validate_num; i++) { sgx_read_rand((uint8_t *)&rand_val, 4); rand_idx = rand_val % wl->srd_hashs.size(); tmp_validate_srd_m[rand_idx] = wl->srd_hashs[rand_idx]; } } sgx_thread_mutex_unlock(&wl->srd_mutex); // ----- Validate SRD ----- // sgx_status_t sgx_status = SGX_SUCCESS; sgx_thread_mutex_lock(&g_validate_srd_m_iter_mutex); g_validate_srd_m.insert(tmp_validate_srd_m.begin(), tmp_validate_srd_m.end()); tmp_validate_srd_m.clear(); g_validate_srd_m_iter = g_validate_srd_m.begin(); sgx_thread_mutex_unlock(&g_validate_srd_m_iter_mutex); // Generate validate random flag sgx_thread_mutex_lock(&g_validate_random_mutex); sgx_read_rand((uint8_t *)&g_validate_random, sizeof(g_validate_random)); sgx_thread_mutex_unlock(&g_validate_random_mutex); // Reset index and finish number sgx_thread_mutex_lock(&g_validated_srd_num_mutex); g_validated_srd_num = 0; sgx_thread_mutex_unlock(&g_validated_srd_num_mutex); for (size_t i = 0; i < g_validate_srd_m.size(); i++) { // If ocall failed, add srd to deleted buffer if (SGX_SUCCESS != (sgx_status = ocall_recall_validate_srd())) { log_err("Invoke validate srd task failed! Error code:%lx\n", sgx_status); // Increase validate srd iterator sgx_thread_mutex_lock(&g_validate_srd_m_iter_mutex); uint32_t srd_index = g_validate_srd_m_iter->first; uint8_t *p_srd = g_validate_srd_m_iter->second; g_validate_srd_m_iter++; sgx_thread_mutex_unlock(&g_validate_srd_m_iter_mutex); // Increase validated srd finish num sgx_thread_mutex_lock(&g_validated_srd_num_mutex); g_validated_srd_num++; sgx_thread_mutex_unlock(&g_validated_srd_num_mutex); // Push current g_hash to delete buffer sgx_thread_mutex_lock(&g_del_srd_v_mutex); g_del_srd_v.push_back(p_srd); sgx_thread_mutex_unlock(&g_del_srd_v_mutex); wl->add_srd_to_deleted_buffer(srd_index); } } // Wait srd validation complete size_t wait_interval = 1000; size_t wait_time = 0; size_t timeout = (size_t)REPORT_SLOT * BLOCK_INTERVAL * 1000000; while (true) { SafeLock sl(g_validated_srd_num_mutex); sl.lock(); if (g_validated_srd_num >= g_validate_srd_m.size()) { wl->report_add_validated_srd_proof(); break; } sl.unlock(); ocall_usleep(wait_interval); // Check if timeout wait_time += wait_interval; if (wait_time > timeout) { log_warn("Validate srd timeout which will lead to generating work report failed! Please check your hardware.\n"); break; } } // Delete failed srd metadata sgx_thread_mutex_lock(&g_del_srd_v_mutex); for (auto hash : g_del_srd_v) { std::string del_path = hexstring_safe(hash, SRD_LENGTH); ocall_delete_folder_or_file(&crust_status, del_path.c_str(), STORE_TYPE_SRD); } // Clear deleted srd buffer g_del_srd_v.clear(); sgx_thread_mutex_unlock(&g_del_srd_v_mutex); // Clear validate buffer sgx_thread_mutex_lock(&g_validate_srd_m_iter_mutex); g_validate_srd_m.clear(); sgx_thread_mutex_unlock(&g_validate_srd_m_iter_mutex); } /** * @description: Validate srd real */ void validate_srd_real() { // Get current validate random sgx_thread_mutex_lock(&g_validate_random_mutex); uint32_t cur_validate_random = g_validate_random; sgx_thread_mutex_unlock(&g_validate_random_mutex); // Get srd info from iterator SafeLock sl_iter(g_validate_srd_m_iter_mutex); sl_iter.lock(); uint32_t srd_index = g_validate_srd_m_iter->first; uint8_t *p_srd = g_validate_srd_m_iter->second; g_validate_srd_m_iter++; sl_iter.unlock(); // Get g_hash corresponding path std::string srd_hex = hexstring_safe(p_srd, SRD_LENGTH); std::string g_hash_hex = srd_hex.substr(UUID_LENGTH * 2 + LAYER_LENGTH * 2, srd_hex.length()); Workload *wl = Workload::get_instance(); bool deleted = false; Defer finish_defer([&cur_validate_random, &deleted, &p_srd, &srd_index, &wl](void) { // Get current validate random sgx_thread_mutex_lock(&g_validate_random_mutex); uint32_t now_validate_srd_random = g_validate_random; sgx_thread_mutex_unlock(&g_validate_random_mutex); // Check if validata random is the same if (cur_validate_random == now_validate_srd_random) { sgx_thread_mutex_lock(&g_validated_srd_num_mutex); g_validated_srd_num++; sgx_thread_mutex_unlock(&g_validated_srd_num_mutex); // Deal with result if (deleted) { sgx_thread_mutex_lock(&g_del_srd_v_mutex); g_del_srd_v.push_back(p_srd); sgx_thread_mutex_unlock(&g_del_srd_v_mutex); wl->add_srd_to_deleted_buffer(srd_index); } } }); // Get M hashs uint8_t *m_hashs_org = NULL; size_t m_hashs_size = 0; crust_status_t crust_status = srd_get_file(get_m_hashs_file_path(srd_hex.c_str()).c_str(), &m_hashs_org, &m_hashs_size); if (CRUST_SUCCESS != crust_status) { if (!wl->add_srd_to_deleted_buffer(srd_index)) { return; } log_err("Get srd(%s) metadata failed, please check your disk. Error code:%lx\n", g_hash_hex.c_str(), crust_status); deleted = true; return; } Defer hashs_org_defer([&m_hashs_org](void) { free(m_hashs_org); }); uint8_t *m_hashs = (uint8_t *)enc_malloc(m_hashs_size); if (m_hashs == NULL) { log_err("Malloc memory failed!\n"); return; } Defer hashs_defer([&m_hashs](void) { free(m_hashs); }); memset(m_hashs, 0, m_hashs_size); memcpy(m_hashs, m_hashs_org, m_hashs_size); // Compare M hashs sgx_sha256_hash_t m_hashs_sha256; sgx_sha256_msg(m_hashs, m_hashs_size, &m_hashs_sha256); if (memcmp(p_srd + UUID_LENGTH + LAYER_LENGTH, m_hashs_sha256, HASH_LENGTH) != 0) { log_err("Wrong srd(%s) metadata.\n", g_hash_hex.c_str()); deleted = true; return; } // Get leaf data uint32_t rand_val; sgx_read_rand((uint8_t*)&rand_val, 4); size_t srd_block_index = rand_val % SRD_RAND_DATA_NUM; std::string leaf_path = get_leaf_path(srd_hex.c_str(), srd_block_index, m_hashs + srd_block_index * HASH_LENGTH); uint8_t *leaf_data = NULL; size_t leaf_data_len = 0; crust_status = srd_get_file(leaf_path.c_str(), &leaf_data, &leaf_data_len); if (CRUST_SUCCESS != crust_status) { if (!wl->add_srd_to_deleted_buffer(srd_index)) { return; } log_err("Get srd(%s) block(%s) failed. Error code:%x\n", g_hash_hex.c_str(), hexstring_safe(m_hashs + srd_block_index * HASH_LENGTH, HASH_LENGTH).c_str(), crust_status); deleted = true; return; } Defer leaf_defer([&leaf_data](void) { free(leaf_data); }); // Compare leaf data sgx_sha256_hash_t leaf_hash; sgx_sha256_msg(leaf_data, leaf_data_len, &leaf_hash); if (memcmp(m_hashs + srd_block_index * HASH_LENGTH, leaf_hash, HASH_LENGTH) != 0) { log_err("Wrong srd block data hash '%s'(file path:%s).\n", g_hash_hex.c_str(), g_hash_hex.c_str()); deleted = true; } } /** * @description: Validate Meaningful files */ void validate_meaningful_file() { Workload *wl = Workload::get_instance(); Defer def_clean_del_buffer([&wl](void) { // Clean deleted file wl->deal_deleted_file(); }); if (ENC_UPGRADE_STATUS_SUCCESS == Workload::get_instance()->get_upgrade_status()) { return; } // Lock wl->sealed_files std::map<std::string, json::JSON> tmp_validate_files_m; sgx_thread_mutex_lock(&wl->file_mutex); // Get to be checked files indexes size_t check_file_num = std::max((size_t)(wl->sealed_files.size() * MEANINGFUL_VALIDATE_RATE), (size_t)MEANINGFUL_VALIDATE_MIN_NUM); check_file_num = std::min(check_file_num, wl->sealed_files.size()); uint32_t rand_val; size_t rand_index = 0; if (check_file_num >= wl->sealed_files.size()) { for (size_t i = 0; i < wl->sealed_files.size(); i++) { tmp_validate_files_m[wl->sealed_files[i][FILE_CID].ToString()] = wl->sealed_files[i]; } } else { for (size_t i = 0; i < check_file_num; i++) { sgx_read_rand((uint8_t *)&rand_val, 4); rand_index = rand_val % wl->sealed_files.size(); tmp_validate_files_m[wl->sealed_files[rand_index][FILE_CID].ToString()] = wl->sealed_files[rand_index]; } } sgx_thread_mutex_unlock(&wl->file_mutex); // ----- Validate file ----- // // Used to indicate which meaningful file status has been changed // If new file hasn't been verified, skip this validation sgx_status_t sgx_status = SGX_SUCCESS; sgx_thread_mutex_lock(&g_validate_files_m_iter_mutex); g_validate_files_m.insert(tmp_validate_files_m.begin(), tmp_validate_files_m.end()); tmp_validate_files_m.clear(); g_validate_files_m_iter = g_validate_files_m.begin(); sgx_thread_mutex_unlock(&g_validate_files_m_iter_mutex); Defer validate_files([](void) { // Clear validate buffer sgx_thread_mutex_lock(&g_validate_files_m_iter_mutex); g_validate_files_m.clear(); sgx_thread_mutex_unlock(&g_validate_files_m_iter_mutex); }); // Generate validate random flag sgx_thread_mutex_lock(&g_validate_random_mutex); sgx_read_rand((uint8_t *)&g_validate_random, sizeof(g_validate_random)); sgx_thread_mutex_unlock(&g_validate_random_mutex); // Reset validate file finish flag sgx_thread_mutex_lock(&g_validated_files_num_mutex); g_validated_files_num = 0; sgx_thread_mutex_unlock(&g_validated_files_num_mutex); // Check if IPFS is online if (g_validate_files_m.size() > 0) { bool ipfs_ret = false; ocall_ipfs_online(&ipfs_ret); if (!ipfs_ret) { wl->set_report_file_flag(false); } } for (size_t i = 0; i < g_validate_files_m.size(); i++) { // If ocall failed, add file to deleted buffer if (SGX_SUCCESS != (sgx_status = ocall_recall_validate_file())) { log_err("Invoke validate file task failed! Error code:%lx\n", sgx_status); // Get current file info sgx_thread_mutex_lock(&g_validate_files_m_iter_mutex); json::JSON *file = const_cast<json::JSON *>(&g_validate_files_m_iter->second); g_validate_files_m_iter++; sgx_thread_mutex_unlock(&g_validate_files_m_iter_mutex); // Increase validated files number sgx_thread_mutex_lock(&g_validated_files_num_mutex); g_validated_files_num++; sgx_thread_mutex_unlock(&g_validated_files_num_mutex); // Add file to deleted buffer sgx_thread_mutex_lock(&g_changed_files_v_mutex); g_changed_files_v.push_back(file); sgx_thread_mutex_unlock(&g_changed_files_v_mutex); } } // If report file flag is true, check if validating file is complete size_t wait_interval = 1000; size_t wait_time = 0; size_t timeout = (size_t)REPORT_SLOT * BLOCK_INTERVAL * 1000000; while (true) { SafeLock sl(g_validated_files_num_mutex); sl.lock(); if (g_validated_files_num >= g_validate_files_m.size()) { wl->report_add_validated_file_proof(); break; } sl.unlock(); ocall_usleep(wait_interval); // Check if timeout wait_time += wait_interval; if (wait_time > timeout) { log_warn("Validate file timeout which will lead to generating work report failed! Please check your hardware.\n"); break; } } // Change file status sgx_thread_mutex_lock(&g_changed_files_v_mutex); std::vector<json::JSON *> tmp_changed_files_v; tmp_changed_files_v.insert(tmp_changed_files_v.begin(), g_changed_files_v.begin(), g_changed_files_v.end()); g_changed_files_v.clear(); sgx_thread_mutex_unlock(&g_changed_files_v_mutex); if (tmp_changed_files_v.size() > 0) { SafeLock sl(wl->file_mutex); sl.lock(); for (auto file : tmp_changed_files_v) { std::string cid = (*file)[FILE_CID].ToString(); size_t index = 0; if(wl->is_file_dup_nolock(cid, index)) { long cur_block_num = wl->sealed_files[index][CHAIN_BLOCK_NUMBER].ToInt(); long val_block_num = g_validate_files_m[cid][CHAIN_BLOCK_NUMBER].ToInt(); // We can get original file and new sealed file(this situation maybe exist) // If these two files are not the same one, cannot delete the file if (cur_block_num == val_block_num) { char old_status = (*file)[FILE_STATUS].get_char(CURRENT_STATUS); char new_status = old_status; const char *old_status_ptr = NULL; const char *new_status_ptr = NULL; if (FILE_STATUS_VALID == old_status) { new_status = FILE_STATUS_LOST; new_status_ptr = FILE_TYPE_LOST; old_status_ptr = FILE_TYPE_VALID; } else if (FILE_STATUS_LOST == old_status) { new_status = FILE_STATUS_VALID; new_status_ptr = FILE_TYPE_VALID; old_status_ptr = FILE_TYPE_LOST; } else { continue; } log_info("File status changed, hash: %s status: %s -> %s\n", cid.c_str(), file_status_2_name[old_status].c_str(), file_status_2_name[new_status].c_str()); // Change file status wl->sealed_files[index][FILE_STATUS].set_char(CURRENT_STATUS, new_status); if (FILE_STATUS_LOST == new_status) { wl->sealed_files[index][FILE_LOST_INDEX] = (*file)[FILE_LOST_INDEX]; } else { wl->sealed_files[index][FILE_LOST_INDEX] = -1; } // Reduce valid file wl->set_file_spec(new_status, g_validate_files_m[cid][FILE_SIZE].ToInt()); wl->set_file_spec(old_status, -g_validate_files_m[cid][FILE_SIZE].ToInt()); // Sync with APP sealed file info ocall_change_file_type(cid.c_str(), old_status_ptr, new_status_ptr); } } else { log_err("Deal with bad file(%s) failed!\n", cid.c_str()); } } } } /** * @description: Validate meaningful files real */ void validate_meaningful_file_real() { Workload *wl = Workload::get_instance(); // Get current validate random sgx_thread_mutex_lock(&g_validate_random_mutex); uint32_t cur_validate_random = g_validate_random; sgx_thread_mutex_unlock(&g_validate_random_mutex); // Get file info from iterator SafeLock sl_iter(g_validate_files_m_iter_mutex); sl_iter.lock(); if (g_validate_files_m.size() == 0) { return; } std::string cid = g_validate_files_m_iter->first; json::JSON *file = const_cast<json::JSON *>(&g_validate_files_m_iter->second); g_validate_files_m_iter++; sl_iter.unlock(); bool changed = false; bool lost = false; bool deleted = false; Defer finish_defer([&cur_validate_random, cid, &deleted, &changed, &file, &wl](void) { // Get current validate random sgx_thread_mutex_lock(&g_validate_random_mutex); uint32_t now_validate_random = g_validate_random; sgx_thread_mutex_unlock(&g_validate_random_mutex); // Check if validate random is the same if (cur_validate_random == now_validate_random) { // Increase validated files number sgx_thread_mutex_lock(&g_validated_files_num_mutex); g_validated_files_num++; sgx_thread_mutex_unlock(&g_validated_files_num_mutex); // Deal with result if (changed) { sgx_thread_mutex_lock(&g_changed_files_v_mutex); g_changed_files_v.push_back(file); sgx_thread_mutex_unlock(&g_changed_files_v_mutex); } if (deleted) { storage_delete_file(cid.c_str()); } } }); // If file status is not FILE_STATUS_VALID, return auto status = (*file)[FILE_STATUS]; if (status.get_char(CURRENT_STATUS) == FILE_STATUS_PENDING || status.get_char(CURRENT_STATUS) == FILE_STATUS_DELETED) { return; } std::string root_cid = (*file)[FILE_CID].ToString(); std::string root_hash = (*file)[FILE_HASH].ToString(); size_t file_block_num = (*file)[FILE_BLOCK_NUM].ToInt(); // Get tree string uint8_t *p_tree = NULL; size_t tree_sz = 0; crust_status_t crust_status = persist_get_unsafe(root_cid, &p_tree, &tree_sz); if (CRUST_SUCCESS != crust_status) { if (wl->is_in_deleted_file_buffer(root_cid)) { return; } log_err("Validate meaningful data failed! Get tree:%s failed! Error code:%lx, will delete file.\n", root_cid.c_str(), crust_status); deleted = true; return; } Defer defer_tree([&p_tree](void) { free(p_tree); }); // Validate merkle tree sgx_sha256_hash_t tree_hash; sgx_sha256_msg(p_tree, tree_sz, &tree_hash); if (memcmp((*file)[FILE_HASH].ToBytes(), &tree_hash, HASH_LENGTH) != 0) { log_err("File:%s merkle tree is not valid! Root hash doesn't equal!\n", root_cid.c_str()); if (status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { lost = true; } return; } // ----- Validate file block ----- // // Get to be checked block index std::set<size_t> block_idx_s; size_t tmp_idx = 0; uint32_t rand_val; for (size_t i = 0; i < MEANINGFUL_VALIDATE_MIN_BLOCK_NUM && i < file_block_num; i++) { sgx_read_rand((uint8_t *)&rand_val, 4); tmp_idx = rand_val % file_block_num; if (block_idx_s.find(tmp_idx) == block_idx_s.end()) { block_idx_s.insert(tmp_idx); } } // Validate lost data if have if (status.get_char(CURRENT_STATUS) == FILE_STATUS_LOST) { long lost_index = (*file)[FILE_LOST_INDEX].ToInt(); if (lost_index >= 0 && lost_index < (*file)[FILE_BLOCK_NUM].ToInt()) { block_idx_s.insert(lost_index); } } // Do check for (auto check_block_idx : block_idx_s) { // Get current node hash uint8_t *p_leaf = p_tree + check_block_idx * FILE_ITEM_LENGTH; std::string file_item = hexstring_safe(p_leaf, FILE_ITEM_LENGTH); std::string uuid = file_item.substr(0, UUID_LENGTH * 2); std::string leaf_hash = file_item.substr(UUID_LENGTH * 2, HASH_LENGTH * 2); // Compute current node hash by data uint8_t *p_sealed_data = NULL; size_t sealed_data_sz = 0; std::string leaf_path = uuid + root_cid + "/" + leaf_hash; crust_status = storage_get_file(leaf_path.c_str(), &p_sealed_data, &sealed_data_sz); if (CRUST_SUCCESS != crust_status) { if (wl->is_in_deleted_file_buffer(root_cid)) { continue; } if (status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { log_err("Get file(%s) block:%ld failed!\n", leaf_path.c_str(), check_block_idx); (*file)[FILE_LOST_INDEX] = check_block_idx; } lost = true; continue; } Defer def_sealed_data([&p_sealed_data](void) { free(p_sealed_data); }); // Validate sealed hash sgx_sha256_hash_t got_hash; sgx_sha256_msg(p_sealed_data, sealed_data_sz, &got_hash); if (memcmp(p_leaf + UUID_LENGTH, got_hash, HASH_LENGTH) != 0) { if (status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { log_err("File(%s) Index:%ld block hash is not expected!\n", root_cid.c_str(), check_block_idx); log_err("Get hash : %s\n", hexstring(got_hash, HASH_LENGTH)); log_err("Org hash : %s\n", leaf_hash.c_str()); (*file)[FILE_LOST_INDEX] = check_block_idx; } lost = true; continue; } } if ((!lost && status.get_char(CURRENT_STATUS) == FILE_STATUS_LOST) || (lost && status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID)) { changed = true; } }
23,515
C++
.cpp
581
31.819277
140
0.584167
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,321
Persistence.cpp
crustio_crust-sworker/src/enclave/persistence/Persistence.cpp
#include "Persistence.h" using namespace std; void inner_ocall_persist_get(crust_status_t* crust_status, const char *key, uint8_t **value, size_t *value_len); /** * @description: Add value by key * @param key -> Pointer to key * @param value -> Pointer to value * @param value_len -> value length * @return: Add status */ crust_status_t persist_add(std::string key, const uint8_t *value, size_t value_len) { crust_status_t crust_status = CRUST_SUCCESS; sgx_sealed_data_t *p_sealed_data = NULL; size_t sealed_data_size = 0; crust_status = seal_data_mrenclave(value, value_len, &p_sealed_data, &sealed_data_size); if (CRUST_SUCCESS != crust_status) { return crust_status; } ocall_persist_add(&crust_status, key.c_str(), (uint8_t *)p_sealed_data, sealed_data_size); free(p_sealed_data); return crust_status; } /** * @description: Delete value by key * @param key -> Pointer to key * @return: Delete status */ crust_status_t persist_del(std::string key) { crust_status_t crust_status = CRUST_SUCCESS; ocall_persist_del(&crust_status, key.c_str()); return crust_status; } /** * @description: Update value by key * @param key -> Pointer to key * @param value -> Pointer to value * @param value_len -> value length * @return: Update status */ crust_status_t persist_set(std::string key, const uint8_t *value, size_t value_len) { crust_status_t crust_status = CRUST_SUCCESS; sgx_sealed_data_t *p_sealed_data = NULL; size_t sealed_data_size = 0; crust_status = seal_data_mrenclave(value, value_len, &p_sealed_data, &sealed_data_size); if (CRUST_SUCCESS != crust_status) { return crust_status; } uint8_t *p_sealed_data_u = (uint8_t *)p_sealed_data; uint8_t *store_buf = NULL; size_t offset = 0; if (sealed_data_size > BOUNDARY_SIZE_THRESHOLD) { // Data size larger than default size uint32_t part_size = 0; while (sealed_data_size > offset) { part_size = std::min((uint32_t)(sealed_data_size - offset), (uint32_t)BOUNDARY_SIZE_THRESHOLD); ocall_persist_set(&crust_status, key.c_str(), p_sealed_data_u + offset, part_size, sealed_data_size, &store_buf, offset); if (CRUST_SUCCESS != crust_status) { log_err("Store part data to DB failed!\n"); goto cleanup; } offset += part_size; } } else { // Set new data ocall_persist_set(&crust_status, key.c_str(), p_sealed_data_u, sealed_data_size, sealed_data_size, &store_buf, offset); } cleanup: if (p_sealed_data != NULL) { free(p_sealed_data); } return crust_status; } /** * @description: Update value by key without seal * @param key -> Pointer to key * @param value -> Pointer to value * @param value_len -> value length * @return: Update status */ crust_status_t persist_set_unsafe(std::string key, const uint8_t *value, size_t value_len) { crust_status_t crust_status = CRUST_SUCCESS; uint8_t *store_buf = NULL; size_t offset = 0; if (value_len > BOUNDARY_SIZE_THRESHOLD) { // Data size larger than default size uint32_t part_size = 0; while (value_len > offset) { part_size = std::min((uint32_t)(value_len - offset), (uint32_t)BOUNDARY_SIZE_THRESHOLD); ocall_persist_set(&crust_status, key.c_str(), value + offset, part_size, value_len, &store_buf, offset); if (CRUST_SUCCESS != crust_status) { log_err("Store part data to DB failed!\n"); return crust_status; } offset += part_size; } } else { // Set new data ocall_persist_set(&crust_status, key.c_str(), value, value_len, value_len, &store_buf, offset); } return crust_status; } /** * @description: Get value by key from ocall * @param crust_status -> status * @param key -> Pointer to key * @param value -> Pointer points to value * @param value_len -> Pointer to value length */ void inner_ocall_persist_get(crust_status_t* crust_status, const char *key, uint8_t **value, size_t *value_len) { uint8_t *tmp_value = NULL; size_t tmp_value_len = 0; ocall_persist_get(crust_status, key, &tmp_value, &tmp_value_len); if (CRUST_SUCCESS != *crust_status) { *value = NULL; *value_len = 0; return; } *value = (uint8_t*)enc_malloc(tmp_value_len); if(*value == NULL) { ocall_free_outer_buffer(crust_status, &tmp_value); if (CRUST_SUCCESS != *crust_status) { return; } *crust_status = CRUST_MALLOC_FAILED; return; } memset(*value, 0, tmp_value_len); memcpy(*value, tmp_value, tmp_value_len); *value_len = tmp_value_len; ocall_free_outer_buffer(crust_status, &tmp_value); if (CRUST_SUCCESS != *crust_status) { free(*value); *value = NULL; *value_len = 0; return; } } /** * @description: Get value by key * @param key -> Pointer to key * @param value -> Pointer points to value * @param value_len -> Pointer to value length * @return: Get status */ crust_status_t persist_get(std::string key, uint8_t **value, size_t *value_len) { crust_status_t crust_status = CRUST_SUCCESS; sgx_status_t sgx_status = SGX_SUCCESS; size_t sealed_data_size = 0; sgx_sealed_data_t *p_sealed_data = NULL; // Get sealed data inner_ocall_persist_get(&crust_status, key.c_str(), (uint8_t **)&p_sealed_data, &sealed_data_size); if (CRUST_SUCCESS != crust_status) { return CRUST_PERSIST_GET_FAILED; } // Get unsealed data uint32_t unsealed_data_size = sgx_get_encrypt_txt_len(p_sealed_data); uint8_t *p_unsealed_data = (uint8_t*)enc_malloc(unsealed_data_size); if (p_unsealed_data == NULL) { log_err("Malloc memory failed!\n"); goto cleanup; } memset(p_unsealed_data, 0, unsealed_data_size); sgx_status = sgx_unseal_data(p_sealed_data, NULL, NULL, p_unsealed_data, &unsealed_data_size); if (SGX_SUCCESS != sgx_status) { log_err("Unseal data failed!Error code:%lx\n", sgx_status); crust_status = CRUST_UNSEAL_DATA_FAILED; free(p_unsealed_data); goto cleanup; } *value = p_unsealed_data; *value_len = unsealed_data_size; cleanup: free(p_sealed_data); return crust_status; } /** * @description: Get value by key * @param key -> Pointer to key * @param value -> Pointer points to value * @param value_len -> Pointer to value length * @return: Get status */ crust_status_t persist_get_unsafe(std::string key, uint8_t **value, size_t *value_len) { crust_status_t crust_status = CRUST_SUCCESS; inner_ocall_persist_get(&crust_status, key.c_str(), value, value_len); if (CRUST_SUCCESS != crust_status) { return CRUST_PERSIST_GET_FAILED; } return crust_status; }
7,147
C++
.cpp
223
26.381166
112
0.622135
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,322
Identity.cpp
crustio_crust-sworker/src/enclave/identity/Identity.cpp
#include "Identity.h" using namespace std; // Protect metadata sgx_thread_mutex_t g_metadata_mutex = SGX_THREAD_MUTEX_INITIALIZER; // Upgrade generate metadata sgx_thread_mutex_t g_gen_work_report = SGX_THREAD_MUTEX_INITIALIZER; // Intel SGX root certificate static const char INTELSGXATTROOTCA[] = "-----BEGIN CERTIFICATE-----" "\n" "MIIFSzCCA7OgAwIBAgIJANEHdl0yo7CUMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV" "\n" "BAYTAlVTMQswCQYDVQQIDAJDQTEUMBIGA1UEBwwLU2FudGEgQ2xhcmExGjAYBgNV" "\n" "BAoMEUludGVsIENvcnBvcmF0aW9uMTAwLgYDVQQDDCdJbnRlbCBTR1ggQXR0ZXN0" "\n" "YXRpb24gUmVwb3J0IFNpZ25pbmcgQ0EwIBcNMTYxMTE0MTUzNzMxWhgPMjA0OTEy" "\n" "MzEyMzU5NTlaMH4xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEUMBIGA1UEBwwL" "\n" "U2FudGEgQ2xhcmExGjAYBgNVBAoMEUludGVsIENvcnBvcmF0aW9uMTAwLgYDVQQD" "\n" "DCdJbnRlbCBTR1ggQXR0ZXN0YXRpb24gUmVwb3J0IFNpZ25pbmcgQ0EwggGiMA0G" "\n" "CSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCfPGR+tXc8u1EtJzLA10Feu1Wg+p7e" "\n" "LmSRmeaCHbkQ1TF3Nwl3RmpqXkeGzNLd69QUnWovYyVSndEMyYc3sHecGgfinEeh" "\n" "rgBJSEdsSJ9FpaFdesjsxqzGRa20PYdnnfWcCTvFoulpbFR4VBuXnnVLVzkUvlXT" "\n" "L/TAnd8nIZk0zZkFJ7P5LtePvykkar7LcSQO85wtcQe0R1Raf/sQ6wYKaKmFgCGe" "\n" "NpEJUmg4ktal4qgIAxk+QHUxQE42sxViN5mqglB0QJdUot/o9a/V/mMeH8KvOAiQ" "\n" "byinkNndn+Bgk5sSV5DFgF0DffVqmVMblt5p3jPtImzBIH0QQrXJq39AT8cRwP5H" "\n" "afuVeLHcDsRp6hol4P+ZFIhu8mmbI1u0hH3W/0C2BuYXB5PC+5izFFh/nP0lc2Lf" "\n" "6rELO9LZdnOhpL1ExFOq9H/B8tPQ84T3Sgb4nAifDabNt/zu6MmCGo5U8lwEFtGM" "\n" "RoOaX4AS+909x00lYnmtwsDVWv9vBiJCXRsCAwEAAaOByTCBxjBgBgNVHR8EWTBX" "\n" "MFWgU6BRhk9odHRwOi8vdHJ1c3RlZHNlcnZpY2VzLmludGVsLmNvbS9jb250ZW50" "\n" "L0NSTC9TR1gvQXR0ZXN0YXRpb25SZXBvcnRTaWduaW5nQ0EuY3JsMB0GA1UdDgQW" "\n" "BBR4Q3t2pn680K9+QjfrNXw7hwFRPDAfBgNVHSMEGDAWgBR4Q3t2pn680K9+Qjfr" "\n" "NXw7hwFRPDAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADANBgkq" "\n" "hkiG9w0BAQsFAAOCAYEAeF8tYMXICvQqeXYQITkV2oLJsp6J4JAqJabHWxYJHGir" "\n" "IEqucRiJSSx+HjIJEUVaj8E0QjEud6Y5lNmXlcjqRXaCPOqK0eGRz6hi+ripMtPZ" "\n" "sFNaBwLQVV905SDjAzDzNIDnrcnXyB4gcDFCvwDFKKgLRjOB/WAqgscDUoGq5ZVi" "\n" "zLUzTqiQPmULAQaB9c6Oti6snEFJiCQ67JLyW/E83/frzCmO5Ru6WjU4tmsmy8Ra" "\n" "Ud4APK0wZTGtfPXU7w+IBdG5Ez0kE1qzxGQaL4gINJ1zMyleDnbuS8UicjJijvqA" "\n" "152Sq049ESDz+1rRGc2NVEqh1KaGXmtXvqxXcTB+Ljy5Bw2ke0v8iGngFBPqCTVB" "\n" "3op5KBG3RjbF6RRSzwzuWfL7QErNC8WEy5yDVARzTA5+xmBc388v9Dm21HGfcC8O" "\n" "DD+gT9sSpssq0ascmvH49MOgjt1yoysLtdCtJW/9FZpoOypaHx0R+mJTLwPXVMrv" "\n" "DaVzWh5aiEx+idkSGMnX" "\n" "-----END CERTIFICATE-----"; static enum _error_type { e_none, e_crypto, e_system, e_api } error_type = e_none; /** * @description: Used to decode url in cert * @param str -> Url * @return: Decoded url */ string url_decode(string str) { string decoded; size_t i; size_t len = str.length(); for (i = 0; i < len; i++) { if (str[i] == '+') decoded += ' '; else if (str[i] == '%') { char *e = NULL; unsigned long int v; // Have a % but run out of characters in the string if (i + 3 > len) throw length_error("premature end of string"); v = strtoul(str.substr(i + 1, 2).c_str(), &e, 16); // Have %hh but hh is not a valid hex code. if (*e) throw out_of_range("invalid encoding"); decoded += static_cast<char>(v); i += 2; } else decoded += str[i]; } return decoded; } /** * @description: Load cert * @param cert -> X509 certificate * @param pemdata -> PEM data * @param sz -> PEM data size * @return: Load status */ int cert_load_size(X509 **cert, const char *pemdata, size_t sz) { BIO *bmem; error_type = e_none; bmem = BIO_new(BIO_s_mem()); if (bmem == NULL) { error_type = e_crypto; goto cleanup; } if (BIO_write(bmem, pemdata, (int)sz) != (int)sz) { error_type = e_crypto; goto cleanup; } *cert = PEM_read_bio_X509(bmem, NULL, NULL, NULL); if (*cert == NULL) error_type = e_crypto; cleanup: if (bmem != NULL) BIO_free(bmem); return (error_type == e_none); } /** * @description: Load cert based on data size * @param cert -> X509 certificate * @param pemdata -> PEM data * @return: Load status */ int cert_load(X509 **cert, const char *pemdata) { return cert_load_size(cert, pemdata, strlen(pemdata)); } /** * @description: Take an array of certificate pointers and build a stack. * @param certs -> Pointer to X509 certificate array * @return: x509 cert */ STACK_OF(X509) * cert_stack_build(X509 **certs) { X509 **pcert; STACK_OF(X509) * stack; error_type = e_none; stack = sk_X509_new_null(); if (stack == NULL) { error_type = e_crypto; return NULL; } for (pcert = certs; *pcert != NULL; ++pcert) sk_X509_push(stack, *pcert); return stack; } /** * @description: Verify cert chain against our CA in store. Assume the first cert in * the chain is the one to validate. Note that a store context can only * be used for a single verification so we need to do this every time * we want to validate a cert. * @param store -> X509 store * @param chain -> X509 chain * @return: Verify status */ int cert_verify(X509_STORE *store, STACK_OF(X509) * chain) { X509_STORE_CTX *ctx; X509 *cert = sk_X509_value(chain, 0); error_type = e_none; ctx = X509_STORE_CTX_new(); if (ctx == NULL) { error_type = e_crypto; return 0; } if (X509_STORE_CTX_init(ctx, store, cert, chain) != 1) { error_type = e_crypto; goto cleanup; } if (X509_verify_cert(ctx) != 1) error_type = e_crypto; cleanup: if (ctx != NULL) X509_STORE_CTX_free(ctx); return (error_type == e_none); } /** * @description: Free cert stack * @param chain -> X509 chain */ void cert_stack_free(STACK_OF(X509) * chain) { sk_X509_free(chain); } /** * @description: Verify content signature * @param msg -> Verified message * @param mlen -> Verified message length * @param sig -> Signature * @param sigsz -> Signature size * @param pkey -> EVP key * @return: Verify status */ int sha256_verify(const uint8_t *msg, size_t mlen, uint8_t *sig, size_t sigsz, EVP_PKEY *pkey) { EVP_MD_CTX *ctx; error_type = e_none; ctx = EVP_MD_CTX_new(); if (ctx == NULL) { error_type = e_crypto; goto cleanup; } if (EVP_DigestVerifyInit(ctx, NULL, EVP_sha256(), NULL, pkey) != 1) { error_type = e_crypto; goto cleanup; } if (EVP_DigestVerifyUpdate(ctx, msg, mlen) != 1) { error_type = e_crypto; goto cleanup; } if (EVP_DigestVerifyFinal(ctx, sig, sigsz) != 1) error_type = e_crypto; cleanup: if (ctx != NULL) EVP_MD_CTX_free(ctx); return (error_type == e_none); } /** * @description: Init CA * @param cert -> X509 certificate * @return: x509 store */ X509_STORE *cert_init_ca(X509 *cert) { X509_STORE *store; error_type = e_none; store = X509_STORE_new(); if (store == NULL) { error_type = e_crypto; return NULL; } if (X509_STORE_add_cert(store, cert) != 1) { X509_STORE_free(store); error_type = e_crypto; return NULL; } return store; } /** * @description: Verify IAS report and upload identity * @param IASReport -> Pointer to vector address * @param size -> Vector size * @return: Verify status */ crust_status_t id_verify_upload_epid_identity(char **IASReport, size_t size) { string certchain_1; size_t cstart, cend, count, i; vector<X509 *> certvec; size_t sigsz; crust_status_t status = CRUST_SUCCESS; size_t qbsz; sgx_ecc_state_handle_t ecc_state = NULL; sgx_ec256_signature_t ecc_signature; BIO *bio_mem = BIO_new(BIO_s_mem()); BIO_puts(bio_mem, INTELSGXATTROOTCA); X509 *intelRootPemX509 = PEM_read_bio_X509(bio_mem, NULL, NULL, NULL); vector<string> response(IASReport, IASReport + size); Workload *wl = Workload::get_instance(); // ----- Verify IAS signature ----- // /* * The response body has the attestation report. The headers have * a signature of the report, and the public signing certificate. * We need to: * * 1) Verify the certificate chain, to ensure it's issued by the * Intel CA (passed with the -A option). * * 2) Extract the public key from the signing cert, and verify * the signature. */ // Get the certificate chain from the headers std::string certchain = response[0]; if (certchain == "") { return CRUST_IAS_BAD_CERTIFICATE; } // URL decode try { certchain = url_decode(certchain); } catch (...) { return CRUST_IAS_BAD_CERTIFICATE; } // Build the cert stack. Find the positions in the string where we // have a BEGIN block. cstart = cend = 0; while (cend != string::npos) { X509 *cert; size_t len; cend = certchain.find("-----BEGIN", cstart + 1); len = ((cend == string::npos) ? certchain.length() : cend) - cstart; if (certchain_1.size() == 0) { certchain_1 = certchain.substr(cstart, len); } if (!cert_load(&cert, certchain.substr(cstart, len).c_str())) { return CRUST_IAS_BAD_CERTIFICATE; } certvec.push_back(cert); cstart = cend; } count = certvec.size(); Defer def_certvec([&certvec, &count](void) { for (size_t i = 0; i < count; i++) { X509_free(certvec[i]); } }); X509 **certar = (X509 **)enc_malloc(sizeof(X509 *) * (count + 1)); if (certar == NULL) { return CRUST_IAS_INTERNAL_ERROR; } Defer def_certar([&certar](void) { free(certar); }); for (i = 0; i < count; i++) certar[i] = certvec[i]; certar[count] = NULL; // Create a STACK_OF(X509) stack from our certs STACK_OF(X509) *stack = cert_stack_build(certar); if (stack == NULL) { return CRUST_IAS_INTERNAL_ERROR; } Defer def_stack([&stack](void) { cert_stack_free(stack); }); // Now verify the signing certificate int rv = cert_verify(cert_init_ca(intelRootPemX509), stack); if (!rv) { return CRUST_IAS_BAD_CERTIFICATE; } // The signing cert is valid, so extract and verify the signature std::string ias_sig = response[1]; if (ias_sig == "") { return CRUST_IAS_BAD_SIGNATURE; } uint8_t *sig = (uint8_t *)base64_decode(ias_sig.c_str(), &sigsz); if (sig == NULL) { return CRUST_IAS_BAD_SIGNATURE; } Defer def_sig([&sig](void) { free(sig); }); X509 *sign_cert = certvec[0]; /* The first cert in the list */ /* * The report body is SHA256 signed with the private key of the * signing cert. Extract the public key from the certificate and * verify the signature. */ EVP_PKEY *pkey = X509_get_pubkey(sign_cert); if (pkey == NULL) { return CRUST_IAS_GETPUBKEY_FAILED; } Defer def_pkey([&pkey](void) { EVP_PKEY_free(pkey); }); std::string isv_body = response[2]; // verify IAS signature if (!sha256_verify((const uint8_t *)isv_body.c_str(), isv_body.length(), sig, sigsz, pkey)) { return CRUST_IAS_BAD_SIGNATURE; } else { status = CRUST_SUCCESS; } // Verify quote int quoteSPos = (int)isv_body.find("\"" IAS_ISV_BODY_TAG "\":\""); quoteSPos = (int)isv_body.find("\":\"", quoteSPos) + 3; int quoteEPos = (int)isv_body.size() - 2; std::string ias_quote_body = isv_body.substr(quoteSPos, quoteEPos - quoteSPos); char *p_decode_quote_body = base64_decode(ias_quote_body.c_str(), &qbsz); if (p_decode_quote_body == NULL) { return CRUST_IAS_BAD_BODY; } Defer def_decode_quote_body([&p_decode_quote_body](void) { free(p_decode_quote_body); }); sgx_quote_t *iasQuote = (sgx_quote_t *)enc_malloc(sizeof(sgx_quote_t)); if (iasQuote == NULL) { log_err("Malloc memory failed!\n"); return CRUST_MALLOC_FAILED; } Defer def_iasQuote([&iasQuote](void) { free(iasQuote); }); memset(iasQuote, 0, sizeof(sgx_quote_t)); memcpy(iasQuote, p_decode_quote_body, qbsz); sgx_report_body_t *iasReportBody = &iasQuote->report_body; // This report data is our ecc public key // should be equal to the one contained in IAS report if (memcmp(iasReportBody->report_data.d, &wl->get_pub_key(), sizeof(sgx_ec256_public_t)) != 0) { return CRUST_IAS_REPORTDATA_NE; } // The mr_enclave should be equal to the one contained in IAS report if (memcmp(&iasReportBody->mr_enclave, &wl->get_mr_enclave(), sizeof(sgx_measurement_t)) != 0) { return CRUST_IAS_BADMEASUREMENT; } // ----- Sign IAS report with current private key ----- // sgx_status_t sgx_status = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SIGN_PUBKEY_FAILED; } Defer def_ecc_state([&ecc_state](void) { sgx_ecc256_close_context(ecc_state); }); // Generate identity data for sig size_t spos = certchain_1.find("-----BEGIN CERTIFICATE-----\n") + strlen("-----BEGIN CERTIFICATE-----\n"); size_t epos = certchain_1.find("\n-----END CERTIFICATE-----"); certchain_1 = certchain_1.substr(spos, epos - spos); replace(certchain_1, "\n", ""); string chain_account_id = wl->get_account_id(); uint8_t *p_account_id_u = hex_string_to_bytes(chain_account_id.c_str(), chain_account_id.size()); if (p_account_id_u == NULL) { return CRUST_UNEXPECTED_ERROR; } Defer def_account_id_u([&p_account_id_u](void) { free(p_account_id_u); }); size_t account_id_u_len = chain_account_id.size() / 2; std::vector<uint8_t> sig_buffer; vector_end_insert(sig_buffer, certchain_1); vector_end_insert(sig_buffer, ias_sig); vector_end_insert(sig_buffer, isv_body); vector_end_insert(sig_buffer, p_account_id_u, account_id_u_len); sgx_status = sgx_ecdsa_sign(sig_buffer.data(), sig_buffer.size(), const_cast<sgx_ec256_private_t *>(&wl->get_pri_key()), &ecc_signature, ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SIGN_PUBKEY_FAILED; } // Get sworker identity and store it outside of sworker json::JSON id_json; id_json[IAS_CERT] = certchain_1; id_json[IAS_SIG] = ias_sig; id_json[IAS_ISV_BODY] = isv_body; id_json[IAS_CHAIN_ACCOUNT_ID] = chain_account_id; id_json[IAS_REPORT_SIG] = hexstring_safe(&ecc_signature, sizeof(sgx_ec256_signature_t)); std::string id_str = id_json.dump(); // Upload identity to chain ocall_upload_epid_identity(&status, id_str.c_str()); return status; } /** * @description: Get and upload ECDSA identity * @param p_quote -> Pointer to quote buffer * @param quote_size -> Quote buffer size * @return: Get result */ crust_status_t id_gen_upload_ecdsa_quote(uint8_t *p_quote, uint32_t quote_size) { // Generate signature Workload *wl = Workload::get_instance(); std::vector<uint8_t> sig_buffer; vector_end_insert(sig_buffer, p_quote, quote_size); vector_end_insert(sig_buffer, Workload::get_instance()->get_account_id()); sgx_ecc_state_handle_t ecc_state = NULL; sgx_status_t sgx_status = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SIGN_PUBKEY_FAILED; } Defer def_ecc_state([&ecc_state](void) { sgx_ecc256_close_context(ecc_state); }); sgx_ec256_signature_t ecc_signature; sgx_status = sgx_ecdsa_sign(sig_buffer.data(), sig_buffer.size(), const_cast<sgx_ec256_private_t *>(&wl->get_pri_key()), &ecc_signature, ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SIGN_PUBKEY_FAILED; } // Generate identity and upload crust_status_t crust_status = CRUST_SUCCESS; json::JSON id_json; id_json["quote"] = hexstring_safe(p_quote, quote_size); id_json["account"] = Workload::get_instance()->get_account_id(); id_json["sig"] = hexstring_safe(&ecc_signature, sizeof(sgx_ec256_signature_t)); std::string id = id_json.dump(); remove_char(id, '\\'); remove_char(id, '\n'); remove_char(id, ' '); ocall_upload_ecdsa_quote(&crust_status, id.c_str()); return crust_status; } /** * @description: Generate and upload ECDSA identity to crust chain * @param report -> Pointer to report buffer * @param size -> Report size * @return: Result status */ crust_status_t id_gen_upload_ecdsa_identity(const char *report, uint32_t size) { log_debug("report:%s\n", report); Workload *wl = Workload::get_instance(); crust_status_t crust_status = CRUST_SUCCESS; json::JSON report_json = json::JSON::Load(&crust_status, reinterpret_cast<const uint8_t *>(report), size); if (CRUST_SUCCESS != crust_status) { return crust_status; } if (report_json.JSONType() != json::JSON::Class::Array) { return CRUST_UNEXPECTED_ERROR; } // Generate identity std::vector<uint8_t> sig_buffer; std::string quote; json::JSON id_json; id_json["pubkeys"] = json::Array(); id_json["sigs"] = json::Array(); for (auto it : report_json.ArrayRange()) { json::JSON quote_json; quote_json["code"] = it["payload"]["code"]; quote_json["who"] = it["payload"]["who"]; quote_json["pubkey"] = it["payload"]["pubkey"]; std::string quote_str = quote_json.dump(); remove_char(quote_str, '\\'); remove_char(quote_str, '\n'); remove_char(quote_str, ' '); if (quote.size() == 0) { std::string account = it["payload"]["who"].ToString(); std::string pubkey = it["payload"]["pubkey"].ToString(); std::string ePubkey = hexstring_safe(&wl->get_pub_key(), sizeof(sgx_ec256_public_t)); if (account.substr(2) != wl->get_account_id()) { log_err("Quote verification error, enclave account:%s, report account:%s\n", wl->get_account_id().c_str(), account.c_str()); return CRUST_UNEXPECTED_ERROR; } if (pubkey.substr(2) != ePubkey) { log_err("Quote verification error, enclave pubkey:%s, report pubkey:%s\n", ePubkey.c_str(), pubkey.c_str()); return CRUST_UNEXPECTED_ERROR; } quote = quote_str; std::string code = it["payload"]["code"].ToString(); id_json["code"] = code; id_json["who"] = account; id_json["pubkey"] = pubkey; uint8_t *p_code_u = hex_string_to_bytes(code.substr(2).c_str(), code.size()-2); if (p_code_u == NULL) { return CRUST_UNEXPECTED_ERROR; } uint8_t *p_account_u = hex_string_to_bytes(account.substr(2).c_str(), account.size()-2); if (p_account_u == NULL) { return CRUST_UNEXPECTED_ERROR; } vector_end_insert(sig_buffer, p_code_u, (code.size()-2)/2); vector_end_insert(sig_buffer, p_account_u, (account.size()-2)/2); vector_end_insert(sig_buffer, reinterpret_cast<const uint8_t *>(&wl->get_pub_key()), sizeof(sgx_ec256_public_t)); } else { if (quote != quote_str) { log_err("Quote verification error, different quote found in report!\n"); return CRUST_UNEXPECTED_ERROR; } } std::string pubkey_t = it["payload"]["public"]["sr25519"].ToString(); std::string sig_t = it["signature"]["sr25519"].ToString(); id_json["pubkeys"].append(pubkey_t); id_json["sigs"].append(sig_t); uint8_t *p_pubkey_t_u = hex_string_to_bytes(pubkey_t.substr(2).c_str(), pubkey_t.size()-2); if (p_pubkey_t_u == NULL) { return CRUST_UNEXPECTED_ERROR; } uint8_t *p_sig_t_u = hex_string_to_bytes(sig_t.substr(2).c_str(), sig_t.size()-2); if (p_sig_t_u == NULL) { return CRUST_UNEXPECTED_ERROR; } vector_end_insert(sig_buffer, p_pubkey_t_u, (pubkey_t.size()-2)/2); vector_end_insert(sig_buffer, p_sig_t_u, (sig_t.size()-2)/2); } std::string id = id_json.dump(); remove_char(id, '\\'); remove_char(id, '\n'); remove_char(id, ' '); // Generate signature sgx_ecc_state_handle_t ecc_state = NULL; sgx_status_t sgx_status = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SIGN_PUBKEY_FAILED; } Defer def_ecc_state([&ecc_state](void) { sgx_ecc256_close_context(ecc_state); }); sgx_ec256_signature_t ecc_signature; sgx_status = sgx_ecdsa_sign(sig_buffer.data(), sig_buffer.size(), const_cast<sgx_ec256_private_t *>(&wl->get_pri_key()), &ecc_signature, ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SIGN_PUBKEY_FAILED; } id_json["sig"] = "0x" + hexstring_safe(&ecc_signature, sizeof(sgx_ec256_signature_t)); // Upload identity to crust chain std::string entrance = id_json.dump(); remove_char(entrance, '\\'); remove_char(entrance, '\n'); remove_char(entrance, ' '); ocall_upload_ecdsa_identity(&crust_status, entrance.c_str()); return crust_status; } /** * @description: Generate ecc key pair and store it in enclave * @param account_id (in) -> Pointer to account id * @param len -> Account id length * @return: Generate status */ sgx_status_t id_gen_key_pair(const char *account_id, size_t len) { Workload *wl = Workload::get_instance(); if (wl->try_get_key_pair()) { log_err("Identity key pair has been generated!\n"); return SGX_ERROR_UNEXPECTED; } if (account_id == NULL || 0 == len) { log_err("Invalid account id!\n"); return SGX_ERROR_UNEXPECTED; } // Generate public and private key sgx_ec256_public_t pub_key; sgx_ec256_private_t pri_key; memset(&pub_key, 0, sizeof(pub_key)); memset(&pri_key, 0, sizeof(pri_key)); sgx_status_t se_ret; sgx_ecc_state_handle_t ecc_state = NULL; se_ret = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != se_ret) { return se_ret; } se_ret = sgx_ecc256_create_key_pair(&pri_key, &pub_key, ecc_state); if (SGX_SUCCESS != se_ret) { return se_ret; } if (ecc_state != NULL) { sgx_ecc256_close_context(ecc_state); } // Store key pair in enclave ecc_key_pair tmp_key_pair; memcpy(&tmp_key_pair.pub_key, &pub_key, sizeof(sgx_ec256_public_t)); memcpy(&tmp_key_pair.pri_key, &pri_key, sizeof(sgx_ec256_private_t)); wl->set_key_pair(tmp_key_pair); // Set chain account id Workload::get_instance()->set_account_id(string(account_id, len)); return SGX_SUCCESS; } /** * @description: Get sgx report, our generated public key contained * in report data * @param report -> Sgx report * @param target_info -> Sgx target info * @return: Get sgx report status */ sgx_status_t id_get_quote_report(sgx_report_t *report, sgx_target_info_t *target_info) { // Copy public key to report data Workload *wl = Workload::get_instance(); sgx_report_data_t report_data; memset(&report_data, 0, sizeof(report_data)); memcpy(&report_data, &wl->get_pub_key(), sizeof(sgx_ec256_public_t)); #ifdef SGX_HW_SIM return sgx_create_report(NULL, &report_data, report); #else return sgx_create_report(target_info, &report_data, report); #endif } /** * @description: Generate current code measurement * @return: Generate status */ sgx_status_t id_gen_sgx_measurement() { sgx_status_t status = SGX_SUCCESS; sgx_report_t verify_report; sgx_target_info_t verify_target_info; sgx_report_data_t verify_report_data; memset(&verify_report, 0, sizeof(sgx_report_t)); memset(&verify_report_data, 0, sizeof(sgx_report_data_t)); memset(&verify_target_info, 0, sizeof(sgx_target_info_t)); status = sgx_create_report(&verify_target_info, &verify_report_data, &verify_report); if (SGX_SUCCESS != status) { return status; } Workload::get_instance()->set_mr_enclave(verify_report.body.mr_enclave); return status; } /** * @description: Store metadata periodically * Just store all metadata except meaningful files. * @return: Store status */ crust_status_t id_store_metadata() { if (ENC_UPGRADE_STATUS_SUCCESS == Workload::get_instance()->get_upgrade_status()) { return CRUST_SUCCESS; } SafeLock sl(g_metadata_mutex); sl.lock(); // Get original metadata Workload *wl = Workload::get_instance(); crust_status_t crust_status = CRUST_SUCCESS; std::string hex_id_key_str = hexstring_safe(&wl->get_key_pair(), sizeof(ecc_key_pair)); // ----- Store metadata ----- // std::vector<uint8_t> meta_buffer; // Append private data tag vector_end_insert(meta_buffer, reinterpret_cast<const uint8_t *>(SWORKER_PRIVATE_TAG), strlen(SWORKER_PRIVATE_TAG)); std::vector<uint8_t> meta_data; do { json::JSON meta_json; // Append id key pair meta_json[ID_KEY_PAIR] = hex_id_key_str; // Append report height meta_json[ID_REPORT_HEIGHT] = std::to_string(wl->get_report_height()); // Append chain account id meta_json[ID_CHAIN_ACCOUNT_ID] = wl->get_account_id(); // Append srd meta_json[ID_SRD] = wl->serialize_srd(); // Append files meta_json[ID_FILE] = wl->serialize_file(); // Append previous public key if (wl->is_upgrade()) { meta_json[ID_PRE_PUB_KEY] = hexstring_safe(&wl->pre_pub_key, sizeof(wl->pre_pub_key)); } meta_data = meta_json.dump_vector(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } } while (0); if (CRUST_SUCCESS != (crust_status = vector_end_insert(meta_buffer, meta_data))) { return crust_status; } crust_status = persist_set(ID_METADATA, meta_buffer.data(), meta_buffer.size()); sl.unlock(); return crust_status; } /** * @description: Restore enclave all metadata * @return: Restore status */ crust_status_t id_restore_metadata() { Workload *wl = Workload::get_instance(); SafeLock sl(g_metadata_mutex); sl.lock(); // ----- Get metadata ----- // json::JSON meta_json; uint8_t *p_data = NULL; size_t data_len = 0; crust_status_t crust_status = persist_get(ID_METADATA, &p_data, &data_len); if (CRUST_SUCCESS != crust_status) { log_warn("No metadata, this may be the first start\n"); return CRUST_UNEXPECTED_ERROR; } log_debug("Get metadata successfully!\n"); meta_json = json::JSON::Load(&crust_status, p_data + strlen(SWORKER_PRIVATE_TAG), data_len); if (CRUST_SUCCESS != crust_status) { log_err("Parse metadata failed! Error code:%lx\n", crust_status); return crust_status; } free(p_data); if (meta_json.size() == 0) { log_warn("Invalid metadata!\n"); return CRUST_INVALID_META_DATA; } log_debug("Load metadata successfully!\n"); // Verify meta data std::string id_key_pair_str = meta_json[ID_KEY_PAIR].ToString(); uint8_t *p_id_key = hex_string_to_bytes(id_key_pair_str.c_str(), id_key_pair_str.size()); if (p_id_key == NULL) { log_err("Identity: Get id key pair failed!\n"); return CRUST_INVALID_META_DATA; } log_debug("Load id key pair successfully!\n"); Defer def_id_key([&p_id_key](void) { free(p_id_key); }); if (wl->try_get_key_pair() && memcmp(p_id_key, &wl->get_key_pair(), sizeof(ecc_key_pair)) != 0) { log_err("Identity: Get wrong id key pair!\n"); return CRUST_INVALID_META_DATA; } log_debug("Verify metadata successfully!\n"); // ----- Restore metadata ----- // Defer def_clean_all([&crust_status, &wl](void) { if (CRUST_SUCCESS != crust_status) { wl->clean_all(); } }); // Restore srd if (CRUST_SUCCESS != (crust_status = wl->restore_srd(meta_json[ID_SRD]))) { return crust_status; } log_debug("Restore srd successfully!\n"); // Restore file if (CRUST_SUCCESS != (crust_status = wl->restore_file(meta_json[ID_FILE]))) { return crust_status; } log_debug("Restore file successfully!\n"); // Restore id key pair ecc_key_pair tmp_key_pair; memcpy(&tmp_key_pair, p_id_key, sizeof(ecc_key_pair)); wl->set_key_pair(tmp_key_pair); log_debug("Restore id key pair successfully!\n"); // Restore report height wl->set_report_height(meta_json[ID_REPORT_HEIGHT].ToInt()); // Restore previous public key if (CRUST_SUCCESS != (crust_status = wl->restore_pre_pub_key(meta_json))) { return crust_status; } // Restore chain account id wl->set_account_id(meta_json[ID_CHAIN_ACCOUNT_ID].ToString()); // Set restart flag wl->set_restart_flag(); return CRUST_SUCCESS; } /** * @description: Compare chain account with enclave's * @param account_id -> Pointer to account id * @param len -> account id length * @return: Compare status */ crust_status_t id_cmp_chain_account_id(const char *account_id, size_t len) { Workload *wl = Workload::get_instance(); if (memcmp(wl->get_account_id().c_str(), account_id, len) != 0) { return CRUST_NOT_EQUAL; } return CRUST_SUCCESS; } /** * @description: Show enclave id information */ void id_get_info() { Workload *wl = Workload::get_instance(); json::JSON id_info; id_info["pub_key"] = hexstring_safe(&wl->get_pub_key(), sizeof(sgx_ec256_public_t)); id_info["mrenclave"] = hexstring_safe(&wl->get_mr_enclave(), sizeof(sgx_measurement_t)); std::string id_str = id_info.dump(); ocall_store_enclave_id_info(id_str.c_str()); } /** * @description: Generate upgrade data * @param block_height -> Current block height * @return: Generate result */ crust_status_t id_gen_upgrade_data(size_t block_height) { SafeLock sl(g_gen_work_report); sl.lock(); crust_status_t crust_status = CRUST_SUCCESS; sgx_status_t sgx_status = SGX_SUCCESS; Workload *wl = Workload::get_instance(); // ----- Generate and upload work report ----- // // Current era has reported, wait for next slot if (block_height <= wl->get_report_height()) { return CRUST_BLOCK_HEIGHT_EXPIRED; } if (block_height < REPORT_SLOT + wl->get_report_height()) { return CRUST_UPGRADE_WAIT_FOR_NEXT_ERA; } size_t report_height = wl->get_report_height(); while (block_height > REPORT_SLOT + report_height) { report_height += REPORT_SLOT; } char report_hash[HASH_LENGTH * 2]; if (report_hash == NULL) { return CRUST_MALLOC_FAILED; } memset(report_hash, 0, HASH_LENGTH * 2); ocall_get_block_hash(&crust_status, report_height, report_hash, HASH_LENGTH * 2); if (CRUST_SUCCESS != crust_status) { return CRUST_UPGRADE_GET_BLOCK_HASH_FAILED; } // Send work report // Wait a random time:[10, 50] block time size_t random_time = 0; sgx_read_rand(reinterpret_cast<uint8_t *>(&random_time), sizeof(size_t)); random_time = ((random_time % (UPGRADE_WAIT_BLOCK_MAX - UPGRADE_WAIT_BLOCK_MIN + 1)) + UPGRADE_WAIT_BLOCK_MIN) * BLOCK_INTERVAL; log_info("Upgrade: Will generate and send work report after %ld blocks...\n", random_time / BLOCK_INTERVAL); if (CRUST_SUCCESS != (crust_status = gen_and_upload_work_report(report_hash, report_height, random_time, false, false))) { log_err("Fatal error! Send work report failed! Error code:%lx\n", crust_status); return CRUST_UPGRADE_GEN_WORKREPORT_FAILED; } log_debug("Upgrade: generate and send work report successfully!\n"); // ----- Generate upgrade data ----- // // Sign upgrade data std::string report_height_str = std::to_string(report_height); sgx_ecc_state_handle_t ecc_state = NULL; sgx_status = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SGX_SIGN_FAILED; } Defer defer_ecc_state([&ecc_state](void) { if (ecc_state != NULL) { sgx_ecc256_close_context(ecc_state); } }); json::JSON srd_json = wl->get_upgrade_srd_info(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } log_debug("Serialize srd data successfully!\n"); json::JSON file_json = wl->get_upgrade_file_info(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } log_debug("Serialize file data successfully!\n"); std::vector<uint8_t> sig_buffer; // Pub key const uint8_t *p_pub_key = reinterpret_cast<const uint8_t *>(&wl->get_pub_key()); vector_end_insert(sig_buffer, p_pub_key, sizeof(sgx_ec256_public_t)); // Block height vector_end_insert(sig_buffer, report_height_str); // Block hash vector_end_insert(sig_buffer, reinterpret_cast<uint8_t *>(report_hash), HASH_LENGTH * 2); // Srd root vector_end_insert(sig_buffer, srd_json[WL_SRD_ROOT_HASH].ToBytes(), HASH_LENGTH); // Files root vector_end_insert(sig_buffer, file_json[WL_FILE_ROOT_HASH].ToBytes(), HASH_LENGTH); sgx_ec256_signature_t sgx_sig; sgx_status = sgx_ecdsa_sign(sig_buffer.data(), sig_buffer.size(), const_cast<sgx_ec256_private_t *>(&wl->get_pri_key()), &sgx_sig, ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SGX_SIGN_FAILED; } log_debug("Generate upgrade signature successfully!\n"); // ----- Get final upgrade data ----- // std::vector<uint8_t> upgrade_data; do { json::JSON upgrade_json; // Public key upgrade_json[UPGRADE_PUBLIC_KEY] = hexstring_safe(&wl->get_pub_key(), sizeof(sgx_ec256_public_t)); // BLock height upgrade_json[UPGRADE_BLOCK_HEIGHT] = report_height_str; // Block hash upgrade_json[UPGRADE_BLOCK_HASH] = std::string(report_hash, HASH_LENGTH * 2); // Srd upgrade_json[UPGRADE_SRD] = srd_json[WL_SRD]; // Files upgrade_json[UPGRADE_FILE] = file_json[WL_FILES]; // Srd root upgrade_json[UPGRADE_SRD_ROOT] = srd_json[WL_SRD_ROOT_HASH].ToString(); // Files root upgrade_json[UPGRADE_FILE_ROOT] = file_json[WL_FILE_ROOT_HASH].ToString(); // Signature upgrade_json[UPGRADE_SIG] = hexstring_safe(&sgx_sig, sizeof(sgx_ec256_signature_t)); upgrade_data = upgrade_json.dump_vector(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } } while (0); // Store upgrade data crust_status = safe_ocall_store2(OCALL_STORE_UPGRADE_DATA, upgrade_data.data(), upgrade_data.size()); if (CRUST_SUCCESS != crust_status) { return crust_status; } log_debug("Store upgrade data successfully!\n"); wl->set_upgrade_status(ENC_UPGRADE_STATUS_SUCCESS); return crust_status; } /** * @description: Restore workload from upgrade data * @param data -> Upgrade data per transfer * @param data_size -> Upgrade data size per transfer * @return: Restore status */ crust_status_t id_restore_from_upgrade(const uint8_t *data, size_t data_size) { crust_status_t crust_status = CRUST_SUCCESS; sgx_status_t sgx_status = SGX_SUCCESS; json::JSON upgrade_json = json::JSON::Load(&crust_status, data, data_size); if (CRUST_SUCCESS != crust_status) { log_err("Parse upgrade data failed! Error code:%lx\n", crust_status); return crust_status; } Workload *wl = Workload::get_instance(); std::string report_height_str = upgrade_json[UPGRADE_BLOCK_HEIGHT].ToString(); std::string report_hash_str = upgrade_json[UPGRADE_BLOCK_HASH].ToString(); std::string a_pub_key_str = upgrade_json[UPGRADE_PUBLIC_KEY].ToString(); uint8_t *a_pub_key_u = hex_string_to_bytes(a_pub_key_str.c_str(), a_pub_key_str.size()); if (a_pub_key_u == NULL) { return CRUST_UNEXPECTED_ERROR; } sgx_ec256_public_t sgx_a_pub_key; memcpy(&sgx_a_pub_key, a_pub_key_u, sizeof(sgx_ec256_public_t)); free(a_pub_key_u); // ----- Restore workload ----- // // Restore srd if (CRUST_SUCCESS != (crust_status = wl->restore_srd(upgrade_json[UPGRADE_SRD]))) { log_err("Restore srd failed! Error code:%lx\n", crust_status); return CRUST_UPGRADE_RESTORE_SRD_FAILED; } log_debug("Restore srd data successfully!\n"); // Restore file if (CRUST_SUCCESS != (crust_status = wl->restore_file(upgrade_json[UPGRADE_FILE]))) { log_err("Restore file failed! Error code:%lx\n", crust_status); return CRUST_UPGRADE_RESTORE_FILE_FAILED; } log_debug("Restore file data successfully!\n"); // ----- Verify workload signature ----- // json::JSON wl_info = wl->gen_workload_info(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } std::string wl_sig = upgrade_json[UPGRADE_SIG].ToString(); std::vector<uint8_t> sig_buffer; // A's public key const uint8_t *p_a_pub_key = reinterpret_cast<const uint8_t *>(&sgx_a_pub_key); vector_end_insert(sig_buffer, p_a_pub_key, sizeof(sgx_ec256_public_t)); // Block height vector_end_insert(sig_buffer, report_height_str); // Block hash vector_end_insert(sig_buffer, report_hash_str); // Srd root vector_end_insert(sig_buffer, wl_info[WL_SRD_ROOT_HASH].ToBytes(), wl_info[WL_SRD_ROOT_HASH].size()); // Files root vector_end_insert(sig_buffer, wl_info[WL_FILE_ROOT_HASH].ToBytes(), wl_info[WL_FILE_ROOT_HASH].size()); // Verify signature sgx_ecc_state_handle_t ecc_state = NULL; sgx_status = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SGX_SIGN_FAILED; } Defer defer([&ecc_state](void) { if (ecc_state != NULL) { sgx_ecc256_close_context(ecc_state); } }); uint8_t *wl_sig_u = hex_string_to_bytes(wl_sig.c_str(), wl_sig.size()); if (wl_sig_u == NULL) { return CRUST_UNEXPECTED_ERROR; } sgx_ec256_signature_t sgx_wl_sig; memcpy(&sgx_wl_sig, wl_sig_u, sizeof(sgx_ec256_signature_t)); free(wl_sig_u); uint8_t p_result; sgx_status = sgx_ecdsa_verify(sig_buffer.data(), sig_buffer.size(), &sgx_a_pub_key, &sgx_wl_sig, &p_result, ecc_state); if (SGX_SUCCESS != sgx_status || p_result != SGX_EC_VALID) { log_err("Verify workload failed!Error code:%lx, result:%d\n", sgx_status, p_result); return CRUST_SGX_VERIFY_SIG_FAILED; } // Verify workload srd and file root hash std::string upgrade_srd_root_str = upgrade_json[UPGRADE_SRD_ROOT].ToString(); std::string upgrade_files_root_str = upgrade_json[UPGRADE_FILE_ROOT].ToString(); if (wl_info[WL_SRD_ROOT_HASH].ToString().compare(upgrade_srd_root_str) != 0) { log_err("Verify workload srd root hash failed!\n"); return CRUST_UPGRADE_BAD_SRD; } if (wl_info[WL_FILE_ROOT_HASH].ToString().compare(upgrade_files_root_str) != 0) { log_err("Verify workload file root hash failed!current hash:%s\n", wl_info[WL_FILE_ROOT_HASH].ToString().c_str()); return CRUST_UPGRADE_BAD_FILE; } // ----- Entry network ----- // wl->set_upgrade(sgx_a_pub_key); ocall_entry_network(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } // ----- Send current version's work report ----- // wl->report_add_validated_srd_proof(); wl->report_add_validated_file_proof(); if (CRUST_SUCCESS != (crust_status = gen_and_upload_work_report(report_hash_str.c_str(), std::atoi(report_height_str.c_str()), 0, true, true))) { return crust_status; } return crust_status; }
40,570
C++
.cpp
1,137
29.96394
147
0.632633
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,323
Report.cpp
crustio_crust-sworker/src/enclave/report/Report.cpp
#include "Report.h" extern sgx_thread_mutex_t g_gen_work_report; /** * @description: Generate and upload signed validation report * @param block_hash (in) -> block hash * @param block_height (in) -> block height * @param wait_time -> Waiting time before upload * @param is_upgrading -> Is this upload kind of upgrade * @param locked -> Lock this upload or not * @return: sign status */ crust_status_t gen_and_upload_work_report(const char *block_hash, size_t block_height, long wait_time, bool is_upgrading, bool locked) { SafeLock gen_sl(g_gen_work_report); if (locked) { gen_sl.lock(); } crust_status_t crust_status = CRUST_SUCCESS; // Wait indicated time if (wait_time != 0) { ocall_usleep(wait_time * 1000000); } // Generate work report if (CRUST_SUCCESS != (crust_status = gen_work_report(block_hash, block_height, is_upgrading))) { return crust_status; } // Upload work report ocall_upload_workreport(&crust_status); // Confirm work report result if (CRUST_SUCCESS == crust_status) { Workload::get_instance()->handle_report_result(); } return crust_status; } /** * @description: Get signed validation report * @param block_hash (in) -> block hash * @param block_height -> block height * @param is_upgrading -> Check if this turn is uprade * @return: sign status */ crust_status_t gen_work_report(const char *block_hash, size_t block_height, bool is_upgrading) { Workload *wl = Workload::get_instance(); crust_status_t crust_status = CRUST_SUCCESS; // Judge whether block height is expired if (block_height == 0 || wl->get_report_height() + REPORT_SLOT > block_height) { return CRUST_BLOCK_HEIGHT_EXPIRED; } Defer defer_status([&wl, &block_height](void) { wl->set_report_height(block_height); wl->set_report_file_flag(true); wl->reduce_restart_flag(); wl->report_reset_validated_proof(); }); if (wl->get_restart_flag()) { // The first 4 report after restart will not be processed return CRUST_FIRST_WORK_REPORT_AFTER_REPORT; } if (!wl->get_report_file_flag()) { // Have files and no IPFS return CRUST_SERVICE_UNAVAILABLE; } if (!wl->report_has_validated_proof()) { // Judge whether the current data is validated return CRUST_WORK_REPORT_NOT_VALIDATED; } ecc_key_pair id_key_pair = wl->get_key_pair(); sgx_status_t sgx_status; // ----- Get srd info ----- // SafeLock srd_sl(wl->srd_mutex); srd_sl.lock(); // Compute srd root hash size_t srd_workload; sgx_sha256_hash_t srd_root; size_t g_hashs_num = wl->srd_hashs.size(); if (g_hashs_num > 0) { uint8_t *srd_data = (uint8_t *)enc_malloc(g_hashs_num * SRD_LENGTH); if (srd_data == NULL) { log_err("Malloc memory failed!\n"); return CRUST_MALLOC_FAILED; } size_t hashs_offset = 0; for (auto g_hash : wl->srd_hashs) { memcpy(srd_data + hashs_offset, g_hash, SRD_LENGTH); hashs_offset += SRD_LENGTH; } // Generate srd information srd_workload = g_hashs_num * 1024 * 1024 * 1024; sgx_sha256_msg(srd_data, (uint32_t)(g_hashs_num * SRD_LENGTH), &srd_root); free(srd_data); } else { srd_workload = 0; memset(srd_root, 0, HASH_LENGTH); } srd_sl.unlock(); // ----- Get files info ----- // SafeLock sealed_files_sl(wl->file_mutex); sealed_files_sl.lock(); // Clear reported_files_idx wl->reported_files_idx.clear(); json::JSON added_files = json::Array(); json::JSON deleted_files = json::Array(); size_t reported_files_acc = 0; long long files_size = 0; std::vector<size_t> report_valid_idx_v; for (uint32_t i = 0; i < wl->sealed_files.size(); i++) { // Get report information auto status = &wl->sealed_files[i][FILE_STATUS]; if (is_upgrading) { if (status->get_char(CURRENT_STATUS) == FILE_STATUS_VALID && status->get_char(ORIGIN_STATUS) == FILE_STATUS_VALID) { report_valid_idx_v.push_back(i); files_size += wl->sealed_files[i][FILE_SIZE].ToInt(); } } else { // Write current status to waiting status status->set_char(WAITING_STATUS, status->get_char(CURRENT_STATUS)); if (status->get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { report_valid_idx_v.push_back(i); } if (status->get_char(ORIGIN_STATUS) == FILE_STATUS_VALID) { files_size += wl->sealed_files[i][FILE_SIZE].ToInt(); } // Generate report files queue if (reported_files_acc < WORKREPORT_FILE_LIMIT) { if ((status->get_char(CURRENT_STATUS) == FILE_STATUS_VALID && status->get_char(ORIGIN_STATUS) == FILE_STATUS_UNVERIFIED) || (status->get_char(CURRENT_STATUS) == FILE_STATUS_LOST && status->get_char(ORIGIN_STATUS) == FILE_STATUS_VALID) || (status->get_char(CURRENT_STATUS) == FILE_STATUS_VALID && status->get_char(ORIGIN_STATUS) == FILE_STATUS_LOST) || (status->get_char(CURRENT_STATUS) == FILE_STATUS_DELETED && status->get_char(ORIGIN_STATUS) == FILE_STATUS_VALID)) { json::JSON file_json = json::FIOObject(); file_json[FILE_CID] = wl->sealed_files[i][FILE_CID].ToString(); file_json[FILE_SIZE] = wl->sealed_files[i][FILE_SIZE].ToInt(); file_json[FILE_CHAIN_BLOCK_NUM] = wl->sealed_files[i][FILE_CHAIN_BLOCK_NUM].ToInt(); if (status->get_char(CURRENT_STATUS) == FILE_STATUS_DELETED || status->get_char(CURRENT_STATUS) == FILE_STATUS_LOST) { deleted_files.append(file_json); // Update new files size files_size -= wl->sealed_files[i][FILE_SIZE].ToInt(); } else if (status->get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { added_files.append(file_json); // Update new files size files_size += wl->sealed_files[i][FILE_SIZE].ToInt(); } wl->reported_files_idx.insert(wl->sealed_files[i][FILE_CID].ToString()); reported_files_acc++; } } } } // Generate files information size_t files_root_buffer_len = report_valid_idx_v.size() * HASH_LENGTH; sgx_sha256_hash_t files_root; if (files_root_buffer_len > 0) { uint8_t *files_root_buffer = (uint8_t *)enc_malloc(files_root_buffer_len); if (files_root_buffer == NULL) { return CRUST_MALLOC_FAILED; } memset(files_root_buffer, 0, files_root_buffer_len); for (size_t i = 0; i < report_valid_idx_v.size(); i++) { size_t idx = report_valid_idx_v[i]; std::string file_id; file_id.append(wl->sealed_files[idx][FILE_CID].ToString()) .append(std::to_string(wl->sealed_files[idx][FILE_SIZE].ToInt())); sgx_sha256_hash_t file_id_hash; sgx_sha256_msg(reinterpret_cast<const uint8_t *>(file_id.c_str()), file_id.size(), &file_id_hash); memcpy(files_root_buffer + i * HASH_LENGTH, reinterpret_cast<uint8_t *>(&file_id_hash), HASH_LENGTH); } sgx_sha256_msg(files_root_buffer, files_root_buffer_len, &files_root); free(files_root_buffer); } else { memset(&files_root, 0, sizeof(sgx_sha256_hash_t)); } sealed_files_sl.unlock(); // ----- Create signature data ----- // std::string pre_pub_key; size_t pre_pub_key_size = 0; if (wl->is_upgrade()) { pre_pub_key_size = sizeof(wl->pre_pub_key); pre_pub_key = hexstring_safe(&wl->pre_pub_key, sizeof(wl->pre_pub_key)); } std::string block_height_str = std::to_string(block_height); std::string reserved_str = std::to_string(srd_workload); std::string files_size_str = std::to_string(files_size); std::vector<uint8_t> sig_buffer; // Current public key vector_end_insert(sig_buffer, reinterpret_cast<const uint8_t *>(&id_key_pair.pub_key), sizeof(id_key_pair.pub_key)); // Previous public key if (wl->is_upgrade()) { vector_end_insert(sig_buffer, reinterpret_cast<const uint8_t *>(&wl->pre_pub_key), pre_pub_key_size); } // Block height vector_end_insert(sig_buffer, block_height_str); // Block hash uint8_t *block_hash_u = hex_string_to_bytes(block_hash, HASH_LENGTH * 2); if (block_hash_u == NULL) { return CRUST_UNEXPECTED_ERROR; } vector_end_insert(sig_buffer, block_hash_u, HASH_LENGTH); free(block_hash_u); // Reserved vector_end_insert(sig_buffer, reserved_str); // Files size vector_end_insert(sig_buffer, files_size_str); // Reserved root vector_end_insert(sig_buffer, srd_root, sizeof(sgx_sha256_hash_t)); // Files root vector_end_insert(sig_buffer, files_root, sizeof(sgx_sha256_hash_t)); // Added files do { std::vector<uint8_t> added_data = added_files.dump_vector_unsafe(); vector_end_insert(sig_buffer, added_data.data(), added_data.size()); } while (0); // Deleted files do { std::vector<uint8_t> deleted_data = deleted_files.dump_vector_unsafe(); vector_end_insert(sig_buffer, deleted_data.data(), deleted_data.size()); } while (0); // Sign work report sgx_ecc_state_handle_t ecc_state = NULL; sgx_status = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SGX_SIGN_FAILED; } sgx_ec256_signature_t sgx_sig; sgx_status = sgx_ecdsa_sign(sig_buffer.data(), sig_buffer.size(), &id_key_pair.pri_key, &sgx_sig, ecc_state); sgx_ecc256_close_context(ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SGX_SIGN_FAILED; } // Store workreport std::vector<uint8_t> wr_data; do { json::JSON wr_json; wr_json[WORKREPORT_PUB_KEY] = hexstring_safe(&id_key_pair.pub_key, sizeof(id_key_pair.pub_key)); wr_json[WORKREPORT_PRE_PUB_KEY] = pre_pub_key; wr_json[WORKREPORT_BLOCK_HEIGHT] = block_height_str; wr_json[WORKREPORT_BLOCK_HASH] = std::string(block_hash, HASH_LENGTH * 2); wr_json[WORKREPORT_RESERVED] = srd_workload; wr_json[WORKREPORT_FILES_SIZE] = files_size; wr_json[WORKREPORT_RESERVED_ROOT] = hexstring_safe(srd_root, HASH_LENGTH); wr_json[WORKREPORT_FILES_ROOT] = hexstring_safe(files_root, HASH_LENGTH); wr_json[WORKREPORT_FILES_ADDED] = added_files; wr_json[WORKREPORT_FILES_DELETED] = deleted_files; wr_json[WORKREPORT_SIG] = hexstring_safe(&sgx_sig, sizeof(sgx_ec256_signature_t)); wr_data = wr_json.dump_vector(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } } while (0); return safe_ocall_store2(OCALL_STORE_WORKREPORT, wr_data.data(), wr_data.size()); }
11,541
C++
.cpp
291
31.347079
141
0.592626
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,324
App.cpp
crustio_crust-sworker/src/app/App.cpp
#include "App.h" bool offline_chain_mode = false; bool g_upgrade_flag = false; bool is_ecdsa_mode = false; extern std::string config_file_path; crust::Log *p_log = crust::Log::get_instance(); /** * @description: application main entry * @param argc -> the number of command parameters * @param argv[] -> parameter array * @return: exit flag */ int SGX_CDECL main(int argc, char *argv[]) { // Get configure file path if exists bool is_set_config = false; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { goto show_help; } else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) { if (i + 1 >= argc) { p_log->err("-c|--config option needs configure file path as argument!\n"); return 1; } config_file_path = std::string(argv[i + 1]); is_set_config = true; i++; } else if (strcmp(argv[i], "--ecdsa") == 0) { is_ecdsa_mode = true; } else if (strcmp(argv[i], "--upgrade") == 0) { g_upgrade_flag = true; } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) { printf("Release version: %s\ \nSWorker version: %s\n", VERSION, SWORKER_VERSION); return 0; } else if (strcmp(argv[i], "--offline") == 0) { offline_chain_mode = true; } else if (strcmp(argv[i], "--debug") == 0) { p_log->set_debug(true); p_log->info("Debug log is opened.\n"); } else { goto show_help; } } // Check if configure path has been indicated if (!is_set_config) { p_log->info("-c argument is not provided, default config path: %s.json will be used.\n", config_file_path.c_str()); } // Main branch return main_daemon(); show_help: printf(" Usage: \n"); printf(" %s <option> <argument>\n", argv[0]); printf(" option: \n"); printf(" -h, --help: help information. \n"); printf(" -c, --config: required, indicate configure file path, followed by configure file path. Like: '--config Config.json'\n"); printf(" If no file provided, default path is %s. \n", config_file_path.c_str()); printf(" -v, --version: show whole version and sworker version. \n"); printf(" --offline: add this flag, program will not interact with the chain. \n"); printf(" --debug: add this flag, program will output debug logs. \n"); printf(" --upgrade: used to upgrade.\n"); printf(" --ecdsa: run in SGX ECDSA mode.\n"); return 0; } /** * @description: run main progress * @return: exit flag */ int main_daemon() { return process_run(); }
3,012
C++
.cpp
90
26.433333
143
0.520082
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,325
Ipfs.cpp
crustio_crust-sworker/src/app/ipfs/Ipfs.cpp
#include "Ipfs.h" crust::Log *p_log = crust::Log::get_instance(); HttpClient *ipfs_client = NULL; Ipfs *Ipfs::ipfs = NULL; std::mutex ipfs_mutex; const std::string block_get_timeout = "1s"; const std::string cat_timeout = "6s"; const std::string add_timeout = "600s"; const std::string del_timeout = "60s"; /** * @description: single instance class function to get instance * @return: ipfs instance */ Ipfs *Ipfs::get_instance() { if (Ipfs::ipfs == NULL) { Config *p_config = Config::get_instance(); ipfs_mutex.lock(); if (Ipfs::ipfs == NULL) { Ipfs::ipfs = new Ipfs(p_config->ipfs_url); } ipfs_mutex.unlock(); } return Ipfs::ipfs; } /** * @description: constructor * @param url -> API base url */ Ipfs::Ipfs(std::string url) { this->url = url; this->form_boundary = "sWorker" + std::to_string(time(NULL)) + "FormBoundary"; ipfs_client = new HttpClient(); } /** * @description: destructor */ Ipfs::~Ipfs() { if (ipfs_client != NULL) { delete ipfs_client; ipfs_client = NULL; } } /** * @description: Test if there is usable IPFS * @return: Test result */ bool Ipfs::online() { std::string path = this->url + "/version"; http::response<http::string_body> res = ipfs_client->Post(path); if ((int)res.result() == 200) { return true; } return false; } /** * @description: Get block from ipfs * @param cid -> File content id * @param p_data_out -> Pointer to pointer to data output * @return: size of block, 0 for error */ size_t Ipfs::block_get(const char *cid, unsigned char **p_data_out) { std::string path = this->url + "/block/get?arg=" + cid + "&timeout=" + block_get_timeout; http::response<http::string_body> res = ipfs_client->Post(path); int res_code = (int)res.result(); if (res_code != 200) { switch (res_code) { case 404: p_log->debug("IPFS is offline! Please start it.\n"); break; case 500: p_log->err("Get IPFS file block failed!\n"); break; default: p_log->err("Get IPFS file block error, code: %d\n", res_code); } return 0; } std::string res_data = res.body(); *p_data_out = (uint8_t *)malloc(res_data.size()); memset(*p_data_out, 0, res_data.size()); memcpy(*p_data_out, res_data.c_str(), res_data.size()); return res_data.size(); } /** * @description: Cat file * @param cid -> File content id * @param p_data_out -> Pointer to pointer to data output * @return: size of file, 0 for error */ size_t Ipfs::cat(const char *cid, unsigned char **p_data_out) { std::string path = this->url + "/cat?arg=" + cid + "&timeout=" + cat_timeout; http::response<http::string_body> res = ipfs_client->Post(path); if ((int)res.result() != 200) { p_log->err("Get file error, code is: %d\n", (int)res.result()); return 0; } std::string res_data = res.body(); *p_data_out = (uint8_t *)malloc(res_data.size()); memset(*p_data_out, 0, res_data.size()); memcpy(*p_data_out, res_data.c_str(), res_data.size()); return res_data.size(); } /** * @description: Add file to ipfs * @param p_data_in -> Pointer to data to be added * @param size -> Size of added data * @return: Hash of the file */ std::string Ipfs::add(unsigned char *p_data_in, size_t size) { std::string path = this->url + "/add" + "?timeout=" + add_timeout; std::string data(reinterpret_cast<char const *>(p_data_in), size); data = "\r\n--" + this->form_boundary + "\r\nContent-Disposition: form-data; name=\"\"\r\n\r\n" + data + "\r\n--" + this->form_boundary + "--\r\n\r\n"; http::response<http::string_body> res = ipfs_client->Post(path, data, "multipart/form-data; boundary=" + this->form_boundary); if ((int)res.result() != 200) { p_log->err("Add file error, code is: %d\n", (int)res.result()); return ""; } json::JSON obj = json::JSON::Load_unsafe(res.body()); return obj["Hash"].ToString(); } /** * @description: Delete file * @param cid -> File content id * @return: Delete result */ bool Ipfs::del(std::string cid) { std::string path = this->url + "/pin/rm?arg=" + cid + "&timeout=" + del_timeout; http::response<http::string_body> res = ipfs_client->Post(path); int res_code = (int)res.result(); if (res_code != 200) { switch (res_code) { case 404: p_log->debug("IPFS is offline! Please start it.\n"); break; case 500: p_log->err("Cannot find IPFS file block!\n"); break; default: p_log->err("Delete file error, code is: %d\n", res_code); } return false; } return true; }
4,920
C++
.cpp
163
24.97546
130
0.583914
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,326
HttpClient.cpp
crustio_crust-sworker/src/app/http/HttpClient.cpp
#include "HttpClient.h" namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace net = boost::asio; // from <boost/asio.hpp> namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> crust::Log *p_log = crust::Log::get_instance(); // ------------------------------ http request ------------------------------ // // ---------- http Get ---------- // http::response<http::string_body> HttpClient::Get(std::string url) { return request_sync(http::verb::get, url, ""); } http::response<http::string_body> HttpClient::Get(std::string url, std::string body) { return request_sync(http::verb::get, url, body); } http::response<http::string_body> HttpClient::Get(std::string url, std::string body, std::string content_type) { return request_sync(http::verb::get, url, body, content_type); } http::response<http::string_body> HttpClient::Get(std::string url, std::string body, ApiHeaders &headers) { return request_sync(http::verb::get, url, body, "text/plain", &headers); } http::response<http::string_body> HttpClient::Get(std::string url, std::string body, std::string content_type, ApiHeaders &headers) { return request_sync(http::verb::get, url, body, content_type, &headers); } // ---------- http Post ---------- // http::response<http::string_body> HttpClient::Post(std::string url) { return request_sync(http::verb::post, url, ""); } http::response<http::string_body> HttpClient::Post(std::string url, std::string body) { return request_sync(http::verb::post, url, body); } http::response<http::string_body> HttpClient::Post(std::string url, std::string body, std::string content_type) { return request_sync(http::verb::post, url, body, content_type); } http::response<http::string_body> HttpClient::Post(std::string url, std::string body, ApiHeaders &headers) { return request_sync(http::verb::post, url, body, "text/plain", &headers); } http::response<http::string_body> HttpClient::Post(std::string url, std::string body, std::string content_type, ApiHeaders &headers) { return request_sync(http::verb::post, url, body, content_type, &headers); } // ------------------------------ SSL request ------------------------------ // // ---------- ssl Get ---------- // http::response<http::string_body> HttpClient::SSLGet(std::string url) { return request_sync_ssl(http::verb::get, url, ""); } http::response<http::string_body> HttpClient::SSLGet(std::string url, std::string body) { return request_sync_ssl(http::verb::get, url, body); } http::response<http::string_body> HttpClient::SSLGet(std::string url, std::string body, std::string content_type) { return request_sync_ssl(http::verb::get, url, body, content_type); } http::response<http::string_body> HttpClient::SSLGet(std::string url, std::string body, ApiHeaders &headers) { return request_sync_ssl(http::verb::get, url, body, "text/plain", &headers); } http::response<http::string_body> HttpClient::SSLGet(std::string url, std::string body, std::string content_type, ApiHeaders &headers) { return request_sync_ssl(http::verb::get, url, body, content_type, &headers); } // ---------- ssl Post ---------- // http::response<http::string_body> HttpClient::SSLPost(std::string url) { return request_sync_ssl(http::verb::post, url, ""); } http::response<http::string_body> HttpClient::SSLPost(std::string url, std::string body) { return request_sync_ssl(http::verb::post, url, body); } http::response<http::string_body> HttpClient::SSLPost(std::string url, std::string body, request_type_t type) { return request_sync_ssl(http::verb::post, url, body, "text/plain", NULL, type); } http::response<http::string_body> HttpClient::SSLPost(std::string url, std::string body, std::string content_type) { return request_sync_ssl(http::verb::post, url, body, content_type); } http::response<http::string_body> HttpClient::SSLPost(std::string url, std::string body, std::string content_type, request_type_t type) { return request_sync_ssl(http::verb::post, url, body, content_type, NULL, type); } http::response<http::string_body> HttpClient::SSLPost(std::string url, std::string body, ApiHeaders &headers) { return request_sync_ssl(http::verb::post, url, body, "text/plain", &headers); } http::response<http::string_body> HttpClient::SSLPost(std::string url, std::string body, ApiHeaders &headers, request_type_t type) { return request_sync_ssl(http::verb::post, url, body, "text/plain", &headers, type); } http::response<http::string_body> HttpClient::SSLPost(std::string url, std::string body, std::string content_type, ApiHeaders &headers) { return request_sync_ssl(http::verb::post, url, body, content_type, &headers); } http::response<http::string_body> HttpClient::SSLPost(std::string url, std::string body, std::string content_type, ApiHeaders &headers, request_type_t type) { return request_sync_ssl(http::verb::post, url, body, content_type, &headers, type); } /** * @description: Performs an SSL request and prints the response * @param method -> Head, Get or Post * @param url -> Request url * @param body -> Request body * @param content_type -> Indicates content type * @param headers -> Poniter to header * @param type -> Request type * @return: Json result */ http::response<http::string_body> HttpClient::request_sync_ssl(http::verb method, std::string url, std::string body,std::string content_type, ApiHeaders *headers, request_type_t type) { // Declare a container to hold the response http::response<http::string_body> res; try { UrlEndPoint url_end_point = get_url_end_point(url); auto const host = url_end_point.ip.c_str(); auto port = std::to_string(url_end_point.port).c_str(); auto const path = url_end_point.base.c_str(); int version = 10; if (std::strncmp(port, "-1", 2) == 0) { port = "443"; } //int version = argc == 5 && !std::strcmp("1.0", argv[4]) ? 10 : 11; // The io_context is required for all I/O net::io_context ioc; // These objects perform our I/O tcp::resolver resolver(ioc); // The SSL context is required, and holds certificates ssl::context ctx(ssl::context::tlsv12_client); //ssl::context ctx(ssl::context::sslv23); ctx.set_default_verify_paths(); // This holds the root certificate used for verification //ctx = SSL_CTX_new(SSLv23_client_method()); //load_root_certificates_http(ctx); // Verify the remote server's certificate if (HTTP_REQ_SECURE == type) { ctx.set_verify_mode(ssl::verify_peer); } beast::ssl_stream<beast::tcp_stream> stream(ioc, ctx); // Set SNI Hostname (many hosts need this to handshake successfully) if(! SSL_set_tlsext_host_name(stream.native_handle(), const_cast<char*>(host))) { beast::error_code ec{static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()}; throw beast::system_error{ec}; } // Look up the domain name auto const results = resolver.resolve(host, port); // Make the connection on the IP address we get from a lookup beast::get_lowest_layer(stream).connect(results); // Perform the SSL handshake stream.handshake(ssl::stream_base::client); // Set up an HTTP GET request message http::request<http::string_body> req{method, path, version}; req.set(http::field::host, host); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); req.set(http::field::content_type, content_type); req.set(http::field::content_length, body.size()); // Set header if (headers != NULL) { for (auto entry = headers->begin(); entry != headers->end(); entry++) { req.set(entry->first, entry->second); } } // Set body req.body() = body; // Send the HTTP request to the remote host http::write(stream, req); // This buffer is used for reading and must be persisted beast::flat_buffer buffer; // Receive the HTTP response http::response_parser<http::string_body> parser; parser.body_limit(HTTP_BODY_LIMIT); http::read(stream, buffer, parser); res = parser.get(); // Gracefully close the stream beast::error_code ec; beast::get_lowest_layer(stream).close(); //stream.shutdown(ec); if(ec == net::error::eof) { // Rationale: // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error ec = {}; } if(ec) throw beast::system_error{ec}; // If we get here then the connection is closed gracefully } catch(std::exception const& e) { p_log->err("Http request error: %s\n", e.what()); res.result(404); return res; } return res; } /** * @description: Performs an HTTP request and prints the response * @param method -> Head, Get or Post * @param url -> Request url * @param body -> Request body * @param content_type -> Indicates content type * @param headers -> Poniter to header * @return: Json result */ http::response<http::string_body> HttpClient::request_sync(http::verb method, std::string url, std::string body, std::string content_type, ApiHeaders *headers) { // Declare a container to hold the response http::response<http::string_body> res; try { UrlEndPoint url_end_point = get_url_end_point(url); auto const host = url_end_point.ip.c_str(); auto const port = std::to_string(url_end_point.port).c_str(); auto const path = url_end_point.base.c_str(); int version = 10; // The io_context is required for all I/O net::io_context ioc; // These objects perform our I/O tcp::resolver resolver(ioc); beast::tcp_stream stream(ioc); // Look up the domain name auto const results = resolver.resolve(host, port); // Make the connection on the IP address we get from a lookup stream.connect(results); // Set up an HTTP GET request message http::request<http::string_body> req{method, path, version}; req.set(http::field::host, host); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); req.set(http::field::content_type, content_type); req.set(http::field::content_length, body.size()); // Set header if (headers != NULL) { for (auto entry = headers->begin(); entry != headers->end(); entry++) { req.set(entry->first, entry->second); } } // Set body req.body() = body; // Send the HTTP request to the remote host http::write(stream, req); // This buffer is used for reading and must be persisted beast::flat_buffer buffer; // Receive the HTTP response http::response_parser<http::string_body> parser; parser.body_limit(HTTP_BODY_LIMIT); http::read(stream, buffer, parser); res = parser.get(); // Gracefully close the socket beast::error_code ec; stream.socket().shutdown(tcp::socket::shutdown_both, ec); // not_connected happens sometimes // so don't bother reporting it. // if(ec && ec != beast::errc::not_connected) throw beast::system_error{ec}; // If we get here then the connection is closed gracefully } catch(std::exception const& e) { res.body() = std::string("Http request error: ") + e.what(); res.result(404); return res; } return res; }
12,060
C++
.cpp
285
36.449123
156
0.638583
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,327
ApiHandler.cpp
crustio_crust-sworker/src/app/http/ApiHandler.cpp
#include "ApiHandler.h" namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp> namespace net = boost::asio; // from <boost/asio.hpp> namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> extern sgx_enclave_id_t global_eid; crust::Log *p_log = crust::Log::get_instance(); /** * @description: Append an HTTP rel-path to a local filesystem path. * The returned path is normalized for the platform. * @param base -> Url base path * @param path -> Url specific path * @return: Analyzed path */ std::string path_cat(beast::string_view base, beast::string_view path) { if(base.empty()) return std::string(path); std::string result(base); #ifdef BOOST_MSVC char constexpr path_separator = '\\'; if(result.back() == path_separator) result.resize(result.size() - 1); result.append(path.data(), path.size()); for (auto& c : result) if(c == '/') c = path_separator; #else char constexpr path_separator = '/'; if(result.back() == path_separator) result.resize(result.size() - 1); result.append(path.data(), path.size()); #endif return result; } /** * @description: Get url parameters * @param url -> Request URL * @return: Key value pair url parameters */ std::map<std::string, std::string> get_params(std::string &url) { std::map<std::string, std::string> ans; size_t spos = url.find('\?'); size_t epos; if (spos == std::string::npos) { ans["req_route"] = url; return ans; } ans["req_route"] = url.substr(0, spos); spos++; while (spos < url.size()) { epos = url.find('&', spos); if (epos == std::string::npos) { epos = url.size(); } size_t ppos = url.find('=', spos); if (ppos > epos || ppos == std::string::npos) { return ans; } std::string key = url.substr(spos, ppos - spos); ppos++; std::string val = url.substr(ppos, epos - ppos); ans[key] = val; spos = epos + 1; } return ans; } /** * @description: Handle websocket request * @param path -> Request path * @param data -> Request data * @param close_connection -> Indicate whether to close connection * @return: Response data as json format */ std::string ApiHandler::websocket_handler(std::string &/*path*/, std::string &/*data*/, bool &/*close_connection*/) { //Config *p_config = Config::get_instance(); json::JSON res; //UrlEndPoint url_end_point = get_url_end_point(p_config->base_url); res["status"] = 300; res["body"] = "Websocket doesn't provide service now!"; return res.dump(); }
2,916
C++
.cpp
90
27.777778
115
0.610085
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,328
WebsocketClient.cpp
crustio_crust-sworker/src/app/http/WebsocketClient.cpp
#include "WebsocketClient.h" namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace websocket = beast::websocket; namespace net = boost::asio; // from <boost/asio.hpp> namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> crust::Log *p_log = crust::Log::get_instance(); // Report a failure void fail(beast::error_code ec, char const* what) { if(ec == net::ssl::error::stream_truncated) return; p_log->err("Webserver error: %s : %s\n", what, ec.message().c_str()); //std::cerr << what << ": " << ec.message() << "\n"; } /** * @description: Initialize websocket * @param host -> Host name or ip address * @param port -> Server port * @param route -> Request route path * @return: Initialize status */ bool WebsocketClient::websocket_init(std::string host, std::string port, std::string route) { try { // The io_context is required for all I/O //net::io_context ioc; this->_ioc = std::make_shared<net::io_context>(); // The SSL context is required, and holds certificates ssl::context ctx{ssl::context::tlsv12_client}; // This holds the root certificate used for verification load_root_certificates(ctx); // These objects perform our I/O //tcp::resolver resolver{ioc}; this->_resolver = std::make_shared<tcp::resolver>(*this->_ioc); //websocket::stream<beast::ssl_stream<tcp::socket>> ws{ioc, ctx}; //websocket::stream<tcp::socket> ws{ioc}; this->_ws = std::make_shared<websocket::stream<tcp::socket>>(*this->_ioc); // Look up the domain name auto const results = this->_resolver->resolve(host, port); // Make the connection on the IP address we get from a lookup //net::connect(ws.next_layer().next_layer(), results.begin(), results.end()); //net::connect(ws.next_layer(), results.begin(), results.end()); net::connect(this->_ws->next_layer(), results.begin(), results.end()); // Perform the SSL handshake //ws.next_layer().handshake(ssl::stream_base::client); // Set a decorator to change the User-Agent of the handshake this->_ws->set_option(websocket::stream_base::decorator( [](websocket::request_type& req) { req.set(http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-coro"); })); // Perform the websocket handshake this->_ws->handshake(host, route); } catch(std::exception const& e) { // p_log->debug("Initialize websocket client failed! Error: %s\n", e.what()); this->_ws = NULL; return false; } return true; } /** * @description: Send request content to server * @param content -> Request content * @param res -> Response from server * @return: Request status */ bool WebsocketClient::websocket_request(std::string content, std::string &res) { if (this->_ws == NULL) { p_log->info("Websocket request failed! Please initialize websocket first!\n"); return false; } try { // Send the message this->_ws->write(net::buffer(content)); // This buffer will hold the incoming message beast::flat_buffer buffer; // Read a message into our buffer this->_ws->read(buffer); res = beast::buffers_to_string(buffer.data()); } catch(std::exception const& e) { p_log->err("Send websocket request failed! Error: %s\n", e.what()); return false; } return true; } /** * @description: Close websocket */ void WebsocketClient::websocket_close() { // Close the WebSocket connection if (this->_ws != NULL) { beast::error_code ec; this->_ws->close(websocket::close_code::normal, ec); if (ec) fail(ec, "close"); this->_ws = NULL; } }
4,104
C++
.cpp
112
30.375
91
0.61244
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,329
WebServer.cpp
crustio_crust-sworker/src/app/http/WebServer.cpp
#include "WebServer.h" namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp> namespace net = boost::asio; // from <boost/asio.hpp> namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> crust::Log *p_log = crust::Log::get_instance(); std::shared_ptr<net::io_context> p_ioc = NULL; pid_t g_webservice_pid; int g_start_server_success = -1; // Return a reasonable mime type based on the extension of a file. beast::string_view mime_type(beast::string_view path) { using beast::iequals; auto const ext = [&path] { auto const pos = path.rfind("."); if(pos == beast::string_view::npos) return beast::string_view{}; return path.substr(pos); }(); if(iequals(ext, ".htm")) return "text/html"; if(iequals(ext, ".html")) return "text/html"; if(iequals(ext, ".php")) return "text/html"; if(iequals(ext, ".css")) return "text/css"; if(iequals(ext, ".txt")) return "text/plain"; if(iequals(ext, ".js")) return "application/javascript"; if(iequals(ext, ".json")) return "application/json"; if(iequals(ext, ".xml")) return "application/xml"; if(iequals(ext, ".swf")) return "application/x-shockwave-flash"; if(iequals(ext, ".flv")) return "video/x-flv"; if(iequals(ext, ".png")) return "image/png"; if(iequals(ext, ".jpe")) return "image/jpeg"; if(iequals(ext, ".jpeg")) return "image/jpeg"; if(iequals(ext, ".jpg")) return "image/jpeg"; if(iequals(ext, ".gif")) return "image/gif"; if(iequals(ext, ".bmp")) return "image/bmp"; if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon"; if(iequals(ext, ".tiff")) return "image/tiff"; if(iequals(ext, ".tif")) return "image/tiff"; if(iequals(ext, ".svg")) return "image/svg+xml"; if(iequals(ext, ".svgz")) return "image/svg+xml"; return "application/text"; } //------------------------------------------------------------------------------ // Report a failure void fail(beast::error_code ec, char const* what) { // ssl::error::stream_truncated, also known as an SSL "short read", // indicates the peer closed the connection without performing the // required closing handshake (for example, Google does this to // improve performance). Generally this can be a security issue, // but if your communication protocol is self-terminated (as // it is with both HTTP and WebSocket) then you may simply // ignore the lack of close_notify. // // https://github.com/boostorg/beast/issues/38 // // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown // // When a short read would cut off the end of an HTTP message, // Beast returns the error beast::http::error::partial_message. // Therefore, if we see a short read here, it has occurred // after the message has been completed, so it is safe to ignore it. if(ec == net::ssl::error::stream_truncated) return; p_log->err("Webserver error: %s : %s\n", what, ec.message().c_str()); //std::cerr << what << ": " << ec.message() << "\n"; } //------------------------------------------------------------------------------ // Echoes back all received WebSocket messages. // This uses the Curiously Recurring Template Pattern so that // the same code works with both SSL streams and regular sockets. template<class Derived> class websocket_session { // Access the derived class, this is part of // the Curiously Recurring Template Pattern idiom. Derived& derived() { return static_cast<Derived&>(*this); } beast::flat_buffer buffer_; ApiHandler *api_handler_; std::string path_; bool close_connection_; // Start the asynchronous operation template<class Body, class Allocator> void do_accept(http::request<Body, http::basic_fields<Allocator>> req) { // Get base path path_ = req.target().data(); // Set suggested timeout settings for the websocket derived().ws().set_option( websocket::stream_base::timeout::suggested( beast::role_type::server)); // Set a decorator to change the Server of the handshake derived().ws().set_option( websocket::stream_base::decorator( [](websocket::response_type& res) { res.set(http::field::server, std::string(BOOST_BEAST_VERSION_STRING) + " advanced-server-flex"); })); // Accept the websocket handshake derived().ws().async_accept( req, beast::bind_front_handler( &websocket_session::on_accept, derived().shared_from_this())); } void on_accept(beast::error_code ec) { if(ec) return fail(ec, "accept"); // Read a message do_read(); } void do_read() { // Read a message into our buffer derived().ws().async_read( buffer_, beast::bind_front_handler( &websocket_session::on_read, derived().shared_from_this())); } void on_read(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); // This indicates that the websocket_session was closed if(ec == websocket::error::closed) return; if(ec) { fail(ec, "read"); return; } // Deal the message std::string buf = beast::buffers_to_string(buffer_.data()); close_connection_ = false; std::string res = api_handler_->websocket_handler(path_, buf, close_connection_); // ----- Async write data ----- // derived().ws().async_write( boost::asio::buffer(res.c_str(), res.size()), beast::bind_front_handler( &websocket_session::on_write, derived().shared_from_this())); } void on_write(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if(ec) { return fail(ec, "write"); } // Clear the buffer buffer_.consume(buffer_.size()); if (close_connection_) return; // Do another read do_read(); } public: websocket_session(ApiHandler *api_handler): api_handler_(api_handler) {} // Start the asynchronous operation template<class Body, class Allocator> void run(http::request<Body, http::basic_fields<Allocator>> req) { // Accept the WebSocket upgrade request do_accept(std::move(req)); } }; //------------------------------------------------------------------------------ // Handles a plain WebSocket connection class plain_websocket_session : public websocket_session<plain_websocket_session> , public std::enable_shared_from_this<plain_websocket_session> { websocket::stream<beast::tcp_stream> ws_; public: // Create the session explicit plain_websocket_session( beast::tcp_stream&& stream, ApiHandler *api_handler) : websocket_session<plain_websocket_session>(api_handler) , ws_(std::move(stream)) { } // Called by the base class websocket::stream<beast::tcp_stream>& ws() { return ws_; } }; //------------------------------------------------------------------------------ // Handles an SSL WebSocket connection class ssl_websocket_session : public websocket_session<ssl_websocket_session> , public std::enable_shared_from_this<ssl_websocket_session> { websocket::stream< beast::ssl_stream<beast::tcp_stream>> ws_; public: // Create the ssl_websocket_session explicit ssl_websocket_session( beast::ssl_stream<beast::tcp_stream>&& stream, ApiHandler *api_handler) : websocket_session<ssl_websocket_session>(api_handler) , ws_(std::move(stream)) { } // Called by the base class websocket::stream<beast::ssl_stream<beast::tcp_stream>>& ws() { return ws_; } }; //------------------------------------------------------------------------------ template<class Body, class Allocator> void make_websocket_session( beast::tcp_stream stream, http::request<Body, http::basic_fields<Allocator>> req, ApiHandler *api_handler) { std::make_shared<plain_websocket_session>( std::move(stream), api_handler)->run(std::move(req)); } template<class Body, class Allocator> void make_websocket_session( beast::ssl_stream<beast::tcp_stream> stream, http::request<Body, http::basic_fields<Allocator>> req, ApiHandler *api_handler) { std::make_shared<ssl_websocket_session>( std::move(stream), api_handler)->run(std::move(req)); } //------------------------------------------------------------------------------ // Handles an HTTP server connection. // This uses the Curiously Recurring Template Pattern so that // the same code works with both SSL streams and regular sockets. template<class Derived> class http_session { // Access the derived class, this is part of // the Curiously Recurring Template Pattern idiom. Derived& derived() { return static_cast<Derived&>(*this); } // This Queue is used for HTTP pipelining. class Queue { enum { // Maximum number of responses we will Queue //limit = 8 limit = 64 }; // The type-erased, saved work item struct work { virtual ~work() = default; virtual void operator()() = 0; }; http_session& self_; std::vector<std::unique_ptr<work>> items_; public: explicit Queue(http_session& self) : self_(self) { static_assert(limit > 0, "Queue limit must be positive"); items_.reserve(limit); } // Returns `true` if we have reached the Queue limit bool is_full() const { return items_.size() >= limit; } // Called when a message finishes sending // Returns `true` if the caller should initiate a read bool on_write() { BOOST_ASSERT(! items_.empty()); auto const was_full = is_full(); items_.erase(items_.begin()); if(! items_.empty()) (*items_.front())(); return was_full; } // Called by the HTTP handler to send a response. template<bool isRequest, class Body, class Fields> void operator()(http::message<isRequest, Body, Fields>&& msg) { // This holds a work item struct work_impl : work { http_session& self_; http::message<isRequest, Body, Fields> msg_; work_impl( http_session& self, http::message<isRequest, Body, Fields>&& msg) : self_(self) , msg_(std::move(msg)) { } void operator()() { http::async_write( self_.derived().stream(), msg_, beast::bind_front_handler( &http_session::on_write, self_.derived().shared_from_this(), msg_.need_eof())); } }; // Allocate and store the work items_.push_back( boost::make_unique<work_impl>(self_, std::move(msg))); // If there was no previous work, start this one if(items_.size() == 1) (*items_.front())(); } }; std::shared_ptr<std::string const> doc_root_; Queue queue_; // The parser is stored in an optional container so we can // construct it from scratch it at the beginning of each new message. boost::optional<http::request_parser<http::vector_body<uint8_t>>> parser_; protected: beast::flat_buffer buffer_; ApiHandler *api_handler_; bool is_ssl_; public: // Construct the session http_session( beast::flat_buffer buffer, std::shared_ptr<std::string const> const& doc_root, ApiHandler *api_handler, bool is_ssl = false) : doc_root_(doc_root) , queue_(*this) , buffer_(std::move(buffer)) , api_handler_(api_handler) , is_ssl_(is_ssl) { } void do_read() { // Construct a new parser for each message parser_.emplace(); // Apply a reasonable limit to the allowed size // of the body in bytes to prevent abuse. parser_->body_limit(HTTP_BODY_LIMIT); // Set the timeout. beast::get_lowest_layer( derived().stream()).expires_after(std::chrono::seconds(WEB_TIMEOUT)); // Read a request using the parser-oriented interface http::async_read( derived().stream(), buffer_, *parser_, beast::bind_front_handler( &http_session::on_read, derived().shared_from_this())); } void on_read(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); // This means they closed the connection if(ec == http::error::end_of_stream) return derived().do_eof(); if(ec) return fail(ec, "read"); // See if it is a WebSocket Upgrade if(websocket::is_upgrade(parser_->get())) { // Disable the timeout. // The websocket::stream uses its own timeout settings. beast::get_lowest_layer(derived().stream()).expires_never(); // Create a websocket session, transferring ownership // of both the socket and the HTTP request. return make_websocket_session( derived().release_stream(), parser_->release(), api_handler_); } // Send the response api_handler_->http_handler(*doc_root_, parser_->release(), queue_, is_ssl_); // If we aren't at the Queue limit, try to pipeline another request if(! queue_.is_full()) do_read(); } void on_write(bool close, beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if(ec) return fail(ec, "write"); // Clear the buffer buffer_.consume(buffer_.size()); if(close) { // This means we should close the connection, usually because // the response indicated the "Connection: close" semantic. return derived().do_eof(); } // Inform the Queue that a write completed if(queue_.on_write()) { // Read another request do_read(); } } }; //------------------------------------------------------------------------------ // Handles a plain HTTP connection class plain_http_session : public http_session<plain_http_session> , public std::enable_shared_from_this<plain_http_session> { beast::tcp_stream stream_; ApiHandler *api_handler_; public: // Create the session plain_http_session( beast::tcp_stream&& stream, beast::flat_buffer&& buffer, std::shared_ptr<std::string const> const& doc_root, ApiHandler *api_handler) : http_session<plain_http_session>( std::move(buffer), doc_root, api_handler) , stream_(std::move(stream)) , api_handler_(api_handler) { } // Start the session void run() { this->do_read(); } // Called by the base class beast::tcp_stream& stream() { return stream_; } // Called by the base class beast::tcp_stream release_stream() { return std::move(stream_); } // Called by the base class void do_eof() { // Send a TCP shutdown beast::error_code ec; stream_.socket().shutdown(tcp::socket::shutdown_send, ec); // At this point the connection is closed gracefully } }; //------------------------------------------------------------------------------ // Handles an SSL HTTP connection class ssl_http_session : public http_session<ssl_http_session> , public std::enable_shared_from_this<ssl_http_session> { beast::ssl_stream<beast::tcp_stream> stream_; ApiHandler *api_handler_; public: // Create the http_session ssl_http_session( beast::tcp_stream&& stream, ssl::context& ctx, beast::flat_buffer&& buffer, std::shared_ptr<std::string const> const& doc_root, ApiHandler *api_handler) : http_session<ssl_http_session>( std::move(buffer), doc_root, api_handler, true) , stream_(std::move(stream), ctx) , api_handler_(api_handler) { } // Start the session void run() { // Set the timeout. beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30)); // Perform the SSL handshake // Note, this is the buffered version of the handshake. stream_.async_handshake( ssl::stream_base::server, buffer_.data(), beast::bind_front_handler( &ssl_http_session::on_handshake, shared_from_this())); } // Called by the base class beast::ssl_stream<beast::tcp_stream>& stream() { return stream_; } // Called by the base class beast::ssl_stream<beast::tcp_stream> release_stream() { return std::move(stream_); } // Called by the base class void do_eof() { // Set the timeout. beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30)); // Perform the SSL shutdown stream_.async_shutdown( beast::bind_front_handler( &ssl_http_session::on_shutdown, shared_from_this())); } private: void on_handshake( beast::error_code ec, std::size_t bytes_used) { if(ec) return fail(ec, "handshake"); // Consume the portion of the buffer used by the handshake buffer_.consume(bytes_used); do_read(); } void on_shutdown(beast::error_code ec) { if(ec) return fail(ec, "shutdown"); // At this point the connection is closed gracefully } }; //------------------------------------------------------------------------------ // Detects SSL handshakes class detect_session : public std::enable_shared_from_this<detect_session> { beast::tcp_stream stream_; ssl::context& ctx_; std::shared_ptr<std::string const> doc_root_; beast::flat_buffer buffer_; ApiHandler *api_handler_; public: explicit detect_session( tcp::socket&& socket, ssl::context& ctx, std::shared_ptr<std::string const> const& doc_root, ApiHandler *api_handler) : stream_(std::move(socket)) , ctx_(ctx) , doc_root_(doc_root) , api_handler_(api_handler) { } // Launch the detector void run() { // Set the timeout. stream_.expires_after(std::chrono::seconds(30)); beast::async_detect_ssl( stream_, buffer_, beast::bind_front_handler( &detect_session::on_detect, this->shared_from_this())); } void on_detect(beast::error_code ec, boost::tribool result) { if(ec) { //return fail(ec, "detect"); return; } if(result) { // Launch SSL session std::make_shared<ssl_http_session>( std::move(stream_), ctx_, std::move(buffer_), doc_root_, api_handler_)->run(); return; } // Launch plain session std::make_shared<plain_http_session>( std::move(stream_), std::move(buffer_), doc_root_, api_handler_)->run(); } }; //-------------------------------------------------------------------------- // WebServer class //-------------------------------------------------------------------------- WebServer::WebServer( net::io_context& ioc, ssl::context& ctx, tcp::endpoint endpoint, std::shared_ptr<std::string const> const& doc_root) : ioc_(ioc) , ctx_(ctx) , acceptor_(net::make_strand(ioc)) , doc_root_(doc_root) { beast::error_code ec; endpoint_ = endpoint; // Open the acceptor acceptor_.open(endpoint.protocol(), ec); if(ec) { fail(ec, "open"); return; } // Allow address reuse acceptor_.set_option(net::socket_base::reuse_address(true), ec); if(ec) { fail(ec, "set_option"); return; } } void WebServer::stop() { this->ioc_.stop(); } // Start accepting incoming connections bool WebServer::run() { beast::error_code ec; // Bind to the server address acceptor_.bind(endpoint_, ec); if(ec) { fail(ec, "bind"); return false; } // Start listening for connections acceptor_.listen( net::socket_base::max_listen_connections, ec); if(ec) { fail(ec, "listen"); return false; } do_accept(); return true; } void WebServer::do_accept() { // The new connection gets its own strand acceptor_.async_accept( net::make_strand(ioc_), beast::bind_front_handler( &WebServer::on_accept, shared_from_this())); } void WebServer::on_accept(beast::error_code ec, tcp::socket socket) { if(ec) { fail(ec, "accept"); } else { // Create the detector http_session and run it ApiHandler *api_handler = new ApiHandler(); std::make_shared<detect_session>( std::move(socket), ctx_, doc_root_, api_handler)->run(); } // Accept another connection do_accept(); } void WebServer::set_api_handler(ApiHandler *api_handler) { this->api_handler = api_handler; } void stop_webservice(void) { if (p_ioc != NULL) { p_ioc->stop(); } } void start_webservice(void) { // Check command line arguments. Config *p_config = Config::get_instance(); UrlEndPoint url_end_point = get_url_end_point(p_config->base_url); auto const address = net::ip::make_address(url_end_point.ip); auto const port = static_cast<unsigned short>(url_end_point.port); auto const doc_root = std::make_shared<std::string>(url_end_point.base); auto const threads = std::max<int>(1, WEBSOCKET_THREAD_NUM); // The io_context is required for all I/O //net::io_context ioc{threads}; std::shared_ptr<net::io_context> ioc = std::make_shared<net::io_context>(threads); p_ioc = ioc; // The SSL context is required, and holds certificates ssl::context ctx{ssl::context::tlsv12}; // This holds the self-signed certificate used by the server load_server_certificate(ctx); // Create and launch a server if (! std::make_shared<WebServer>(*ioc, ctx, tcp::endpoint{address, port}, doc_root)->run()) { g_start_server_success = 0; return; } g_start_server_success = 1; // Capture SIGINT and SIGTERM to perform a clean shutdown //net::signal_set signals(ioc, SIGINT, SIGTERM); //signals.async_wait( // [&](beast::error_code const&, int) // { // // Stop the `io_context`. This will cause `run()` // // to return immediately, eventually destroying the // // `io_context` and all of the sockets in it. // ioc.stop(); // }); // Run the I/O service on the requested number of threads std::vector<std::thread> v; v.reserve(threads - 1); for (auto i = threads - 1; i > 0; --i) { v.emplace_back( [&ioc] { ioc->run(); }); } ioc->run(); g_webservice_pid = getpid(); // (If we get here, it means we got a SIGINT or SIGTERM) // Block until all the threads exit for (auto& t : v) t.join(); }
25,046
C++
.cpp
753
25.687915
100
0.560174
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,330
Process.cpp
crustio_crust-sworker/src/app/process/Process.cpp
#include "Process.h" #include "WebServer.h" bool upgrade_try_start(); bool upgrade_try_restore(); void upgrade_try_complete(bool success); bool start_task(task_func_t func); bool restore_tasks(); // Global EID shared by multiple threads sgx_enclave_id_t global_eid = 0; // Pointor to configure instance Config *p_config = NULL; // Map to record specific task std::map<task_func_t, std::shared_ptr<std::future<void>>> g_tasks_m; crust::Log *p_log = crust::Log::get_instance(); extern int g_start_server_success; extern bool g_upgrade_flag; extern bool offline_chain_mode; /** * @description: Init configuration * @return: Init status */ bool initialize_config(void) { // New configure p_config = Config::get_instance(); if (p_config == NULL) { return false; } p_config->show(); return true; } /** * @description: Call sgx_create_enclave to initialize an enclave instance * @return: Success or failure */ bool initialize_enclave() { int sgx_support; sgx_status_t ret = SGX_ERROR_UNEXPECTED; // ----- Can we run SGX? ----- // p_log->info("Initial enclave...\n"); sgx_support = get_sgx_support(); if (sgx_support & SGX_SUPPORT_NO) { p_log->err("This system does not support Intel SGX.\n"); return false; } else { if (sgx_support & SGX_SUPPORT_ENABLE_REQUIRED) { p_log->err("Intel SGX is supported on this system but disabled in the BIOS\n"); return false; } else if (sgx_support & SGX_SUPPORT_REBOOT_REQUIRED) { p_log->err("Intel SGX will be enabled after the next reboot\n"); return false; } else if (!(sgx_support & SGX_SUPPORT_ENABLED)) { p_log->err("Intel SGX is supported on this sytem but not available for use. " "The system may lock BIOS support, or the Platform Software is not available\n"); return false; } } p_log->debug("Your machine can support SGX.\n"); // ----- Launch the enclave ----- // uint8_t *p_wl_data = NULL; size_t wl_data_size = 0; if (CRUST_SUCCESS == get_file(SGX_WL_FILE_PATH, &p_wl_data, &wl_data_size)) { sgx_status_t reg_ret = sgx_register_wl_cert_chain(p_wl_data, wl_data_size); if (SGX_SUCCESS != reg_ret) { p_log->warn("Encounter problem when registering local white list cert, code:%lx.\n", reg_ret); } free(p_wl_data); } ret = sgx_create_enclave(ENCLAVE_FILE_PATH, SGX_DEBUG_FLAG, NULL, NULL, &global_eid, NULL); if (ret != SGX_SUCCESS) { switch (ret) { case SGX_ERROR_NO_DEVICE: p_log->err("Init enclave failed. Open sgx driver failed, please uninstall your sgx " "driver (OOT driver and DCAP driver) and reinstall it (OOT driver). " "If it still fails, please try to reinstall the system. Error code:%lx\n", ret); break; default: p_log->err("Init enclave failed.Error code:%lx\n", ret); } return false; } p_log->info("Initial enclave successfully!Enclave id:%d\n", global_eid); // ----- Generate code measurement ----- // if (SGX_SUCCESS != Ecall_gen_sgx_measurement(global_eid, &ret)) { p_log->err("Generate code measurement failed!error code:%lx\n", ret); return false; } p_log->debug("Generate code measurement successfully!\n"); return true; } /** * @description: Initialize the components: * config -> user configurations and const configurations * api handler -> external API interface * @return: Success or failure */ bool initialize_components(void) { // Create path if (CRUST_SUCCESS != create_directory(p_config->base_path)) { p_log->err("Create base path failed!!\n"); return false; } // Init crust if (crust::Chain::get_instance() == NULL) { p_log->err("Init crust chain failed!\n"); return false; } // Initialize DataBase if (crust::DataBase::get_instance() == NULL) { p_log->err("Initialize DataBase failed!\n"); return false; } // Restore debug flag crust::Log::get_instance()->restore_debug_flag(); p_log->info("Init components successfully!\n"); return true; } /** * @description: Inform old version to start upgrade * @return: Inform result */ bool upgrade_try_start() { std::shared_ptr<HttpClient> client(new HttpClient()); ApiHeaders headers = {{"backup",p_config->chain_backup}}; p_log->info("Informing old version to get ready for upgrade...\n"); int start_wait_time = 16; std::string err_msg; while (true) { http::response<http::string_body> res_inform = client->Get(p_config->base_url + "/upgrade/start", "", headers); if ((int)res_inform.result() != 200) { if ((int)res_inform.result() == 404) { p_log->err("Please make sure old sWorker is running!Error code:%d\n", res_inform.result()); return false; } if (res_inform.body().compare(err_msg) != 0) { p_log->info("Old version not ready for upgrade!Message:%s, status:%d, try again...\n", res_inform.body().c_str(), res_inform.result()); err_msg = res_inform.body(); } sleep(start_wait_time); continue; } p_log->info("Inform old version to upgrade successfully!\n"); break; } return true; } /** * @description: Restore upgrade data * @return: Restore result */ bool upgrade_try_restore() { std::shared_ptr<HttpClient> client(new HttpClient()); ApiHeaders headers = {{"backup",p_config->chain_backup}}; p_log->info("Waiting for upgrade data...\n"); int restore_tryout = 3; int meta_wait_time = 3; http::response<http::string_body> res_meta; sgx_status_t sgx_status = SGX_SUCCESS; std::string err_msg; while (true) { // Try to get metadata res_meta = client->Get(p_config->base_url + "/upgrade/metadata", "", headers); int res_code = (int)res_meta.result(); if (res_code != 200) { if (res_code == 404) { p_log->err("Get upgrade data failed!Old sWorker is not running!\n"); return false; } if (res_code == 408) { p_log->err("Upgrade timeout for old sworker, will retry later.\n"); return false; } if (res_meta.body().compare(err_msg) != 0) { p_log->info("Old version Message:%s\n", res_meta.body().c_str()); err_msg = res_meta.body(); } sleep(meta_wait_time); continue; } p_log->info("Get upgrade data successfully!Data size:%ld.\n", res_meta.body().size()); break; } restore_try_again: // Init enclave if (!initialize_enclave()) { p_log->err("Init enclave failed!\n"); return false; } // Generate ecc key pair if (SGX_SUCCESS != Ecall_gen_key_pair(global_eid, &sgx_status, p_config->chain_account_id.c_str(), p_config->chain_account_id.size()) || SGX_SUCCESS != sgx_status) { p_log->err("Generate key pair failed!\n"); return false; } p_log->info("Generate key pair successfully!\n"); // Restore workload and report old version's work report crust_status_t crust_status = CRUST_SUCCESS; size_t meta_size = res_meta.body().size(); const char *p_meta = res_meta.body().c_str(); sgx_status = safe_ecall_store2(global_eid, &crust_status, ECALL_RESTORE_FROM_UPGRADE, reinterpret_cast<const uint8_t *>(p_meta), meta_size); if (SGX_SUCCESS != sgx_status) { p_log->err("Invoke SGX API failed!Error code:%lx.\n", sgx_status); return false; } if (CRUST_SUCCESS != crust_status) { if (CRUST_INIT_QUOTE_FAILED == crust_status) { if (--restore_tryout > 0) { sgx_destroy_enclave(global_eid); sleep(60); goto restore_try_again; } } p_log->err("Restore workload from upgrade data failed!Error code:%lx.\n", crust_status); return false; } p_log->info("Restore workload from upgrade data successfully!\n"); return true; } /** * @description: Inform old version upgrade result * @param success -> Upgrade result */ void upgrade_try_complete(bool success) { std::shared_ptr<HttpClient> client(new HttpClient()); ApiHeaders headers = {{"backup",p_config->chain_backup}}; p_log->info("Informing old version upgrade result...\n"); json::JSON upgrade_ret; upgrade_ret["success"] = success; int complete_wait_time = 1; while (true) { // Inform old version to close http::response<http::string_body> res_complete = client->Get(p_config->base_url + "/upgrade/complete", upgrade_ret.dump(), headers); if ((int)res_complete.result() != 200 && (int)res_complete.result() != 404) { p_log->warn("Inform old version failed!Message:%s, try again...\n", res_complete.body().c_str()); sleep(complete_wait_time); continue; } break; } p_log->info("Inform old version upgrade %s!\n", success ? "successfully" : "failed"); if (!success) { print_logo(UPGRADE_FAILED_LOGO, HRED); return; } // Init related components p_log->info("Waiting for old version's webservice stop...\n"); // Waiting old version stop long check_old_api_tryout = 0; while (true) { // Inform old version to close http::response<http::string_body> res_test = client->Get(p_config->base_url + "/enclave/thread_info", "", headers); if ((int)res_test.result() == 404) { break; } if (check_old_api_tryout % 10 == 0) { p_log->info("Old version webservice is still working, please wait...\n"); } check_old_api_tryout++; sleep(3); } sleep(10); UrlEndPoint urlendpoint = get_url_end_point(p_config->base_url); while (!initialize_components()) { p_log->err("Please check if port:%d has been used. If it is being used, stop related process!\n", urlendpoint.port); sleep(10); } print_logo(UPGRADE_SUCCESS_LOGO, HGREEN); } /** * @description: Check if upgrade, this function executes until upgrade successfully */ void do_upgrade() { while (true) { if (!upgrade_try_start()) { sleep(30); continue; } bool res = upgrade_try_restore(); upgrade_try_complete(res); if (res) { break; } sleep(30); } } /** * @description: Wrapper for main loop */ void main_loop(void) { Ecall_main_loop(global_eid); } /** * @description: Start task by name * @param func -> Task function indicator * @return: Start result */ bool start_task(task_func_t func) { // Check if service is started if (g_tasks_m.find(func) != g_tasks_m.end()) { if (g_tasks_m[func]->wait_for(std::chrono::seconds(0)) != std::future_status::ready) { return true; } } // Start service g_tasks_m[func] = std::make_shared<std::future<void>>(std::async(std::launch::async, func)); if (func == start_webservice) { while (g_start_server_success == -1) { sleep(0.01); } if (g_start_server_success == 0) { return false; } g_start_server_success = -1; } return true; } /** * @description: Restore tasks * @return: Restore result */ bool restore_tasks() { for (auto it = g_tasks_m.begin(); it != g_tasks_m.end(); it++) { if (it->second->wait_for(std::chrono::seconds(0)) == std::future_status::ready) { if (!start_task(it->first)) { return false; } } } return true; } /** * @description: Main function to start application * @return: Start status */ int process_run() { pid_t worker_pid = getpid(); sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; int return_status = 1; int check_interval = 15; int upgrade_timeout = 3 * REPORT_SLOT * BLOCK_INTERVAL; int upgrade_tryout = upgrade_timeout / check_interval; int entry_tryout = 3; size_t srd_task = 0; long srd_real_change = 0; std::string srd_task_str; EnclaveData *ed = EnclaveData::get_instance(); crust::DataBase *db = NULL; bool is_restart = false; p_log->info("WorkerPID = %d\n", worker_pid); // Init conifigure if (!initialize_config()) { p_log->err("Init configuration failed!\n"); return_status = -1; goto cleanup; } // Construct uuid to disk path map ed->construct_uuid_disk_path_map(); // There are three startup mode: upgrade, restore and normal // Upgrade mode will communicate with old version for data transferring. // Resotre mode will restore enclave data from database. // Normal mode will start up a new enclave. // ----- Upgrade mode ----- // if (g_upgrade_flag) { // Check and do upgrade do_upgrade(); p_log->info("Upgrade from old version successfully!\n"); } else { // Init related components if (!initialize_components()) { p_log->err("Init component failed!\n"); return_status = -1; goto cleanup; } entry_network_flag: // Init enclave if (!initialize_enclave()) { p_log->err("Init enclave failed!\n"); return_status = -1; goto cleanup; } p_log->info("Worker global eid: %d\n", global_eid); // Start enclave if (SGX_SUCCESS != Ecall_restore_metadata(global_eid, &crust_status) || CRUST_SUCCESS != crust_status) { // ----- Normal startup ----- // // Restore data failed p_log->info("Starting a new enclave...(restore code:%lx)\n", crust_status); // Generate ecc key pair if (SGX_SUCCESS != Ecall_gen_key_pair(global_eid, &sgx_status, p_config->chain_account_id.c_str(), p_config->chain_account_id.size()) || SGX_SUCCESS != sgx_status) { p_log->err("Generate key pair failed!\n"); return_status = -1; goto cleanup; } p_log->info("Generate key pair successfully!\n"); // Start http service if (!start_task(start_webservice)) { p_log->err("Start web service failed!\n"); goto cleanup; } // Entry network if (!offline_chain_mode) { crust_status = entry_network(); if (CRUST_SUCCESS != crust_status) { if (CRUST_INIT_QUOTE_FAILED == crust_status && entry_tryout > 0) { entry_tryout--; sgx_destroy_enclave(global_eid); global_eid = 0; sleep(60); goto entry_network_flag; } goto cleanup; return_status = -1; } } else { p_log->info("Enclave id info:\n%s\n", ed->get_enclave_id_info().c_str()); } // Set init srd capacity srd_task = 1; } else { // ----- Restore data successfully ----- // // Compare crust account it in configure file and recovered file if (SGX_SUCCESS != Ecall_cmp_chain_account_id(global_eid, &crust_status, p_config->chain_account_id.c_str(), p_config->chain_account_id.size()) || CRUST_SUCCESS != crust_status) { p_log->err("Configure chain account id doesn't equal to recovered one!\n"); return_status = -1; goto cleanup; } // Wait for chain running if (!crust::Chain::get_instance()->wait_for_running()) { p_log->err("Waiting for chain running error!\n"); return_status = -1; goto cleanup; } is_restart = true; } } db = crust::DataBase::get_instance(); // Do restart related if (is_restart || g_upgrade_flag) { // Get srd remaining task if (CRUST_SUCCESS == db->get(WL_SRD_REMAINING_TASK, srd_task_str)) { std::stringstream sstream(srd_task_str); size_t srd_task_remain = 0; sstream >> srd_task_remain; srd_task = std::max(srd_task, srd_task_remain); } // Print recovered workload std::string wl_info = ed->gen_workload_str(srd_task); p_log->info("Workload information:\n%s\n", wl_info.c_str()); p_log->info("Restore enclave data successfully, sworker is running now.\n"); } // Restore or add srd task if (srd_task > 0) { p_log->info("Detect %ldGB srd task, will execute later.\n", srd_task); if (SGX_SUCCESS != (sgx_status = Ecall_change_srd_task(global_eid, &crust_status, srd_task, &srd_real_change))) { p_log->err("Set srd change failed!Invoke SGX api failed! Error code:%lx\n", sgx_status); } else { switch (crust_status) { case CRUST_SUCCESS: p_log->info("Add srd task successfully! %ldG has been added, will be executed later.\n", srd_real_change); break; case CRUST_SRD_NUMBER_EXCEED: p_log->warn("Add srd task failed! Srd number has reached the upper limit! Real srd task is %ldG.\n", srd_real_change); break; default: p_log->info("Unexpected error has occurred!\n"); } } } // Start http service if (!start_task(start_webservice)) { p_log->err("Start web service failed!\n"); goto cleanup; } // Check block height and post report to chain start_task(work_report_loop); // Start thread to check srd reserved start_task(srd_check_reserved); // Main validate loop start_task(main_loop); // Check loop while (true) { // Deal with upgrade if (UPGRADE_STATUS_PROCESS == ed->get_upgrade_status()) { if (EnclaveQueue::get_instance()->get_upgrade_ecalls_num() == 0) { ed->set_upgrade_status(UPGRADE_STATUS_END); } } if (UPGRADE_STATUS_END == ed->get_upgrade_status()) { p_log->info("Start generating upgrade data...\n"); crust::BlockHeader block_header; if (!crust::Chain::get_instance()->get_block_header(block_header)) { p_log->err("Get block header failed! Please check your crust-api and crust chain!\n"); } else if (SGX_SUCCESS != (sgx_status = Ecall_gen_upgrade_data(global_eid, &crust_status, block_header.number))) { p_log->err("Generate upgrade metadata failed! Invoke SGX API failed! Error code:%lx. Try next turn!\n", sgx_status); } else if (CRUST_SUCCESS != crust_status) { p_log->warn("Generate upgrade metadata failed! Code:%lx. Try next turn!\n", crust_status); } else { p_log->info("Generate upgrade metadata successfully!\n"); ed->set_upgrade_status(UPGRADE_STATUS_COMPLETE); } } // Upgrade tryout if (UPGRADE_STATUS_NONE != ed->get_upgrade_status()) { if (--upgrade_tryout < 0) { p_log->err("Upgrade timeout!Current version will restore work!\n"); ed->set_upgrade_status(UPGRADE_STATUS_NONE); upgrade_tryout = upgrade_timeout / check_interval; } } else { // Restore related work if (!restore_tasks()) { p_log->err("Restore tasks failed! Will exist...\n"); goto cleanup; } } // Sleep and check exit flag if (!sleep_interval(check_interval, [&ed](void) { if (UPGRADE_STATUS_EXIT == ed->get_upgrade_status()) { // Wait tasks end bool has_task_running = false; for (auto task : g_tasks_m) { if(task.first == start_webservice) { continue; } if (task.second->wait_for(std::chrono::seconds(0)) != std::future_status::ready) { has_task_running = true; } } return has_task_running; } return true; })) { goto cleanup; } } cleanup: // Release database p_log->info("Release database for exit...\n"); if (db != NULL) { delete db; } // Stop web service p_log->info("Kill web service for exit...\n"); stop_webservice(); // Destroy enclave // TODO: Fix me, why destory enclave leads to coredump p_log->info("Destroy enclave for exit...\n"); if (global_eid != 0) { sgx_destroy_enclave(global_eid); } return return_status; }
22,136
C++
.cpp
661
24.8941
151
0.554787
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,331
Validator.cpp
crustio_crust-sworker/src/app/process/Validator.cpp
#include "Validator.h" #include "ECalls.h" extern sgx_enclave_id_t global_eid; Validator *Validator::validator = NULL; std::mutex validator_mutex; /** * @description: Get validator instance * @return: Validator instance */ Validator *Validator::get_instance() { if (Validator::validator == NULL) { validator_mutex.lock(); if (Validator::validator == NULL) { Validator::validator = new Validator(); } validator_mutex.unlock(); } return Validator::validator; } /** * @description: Validator constructor */ Validator::Validator() { uint32_t thread_num = std::min(Config::get_instance()->srd_thread_num, VALIDATE_MAX_THREAD_NUM); this->validate_pool = new ctpl::thread_pool(thread_num); } /** * @description: Validate meaningful files */ void Validator::validate_file() { // Push new task sgx_enclave_id_t eid = global_eid; validate_tasks_v.push_back(std::make_shared<std::future<void>>(validate_pool->push([eid](int /*id*/){ Ecall_validate_file(eid); }))); // Check and remove complete task for (auto it = validate_tasks_v.begin(); it != validate_tasks_v.end(); ) { if ((*it)->wait_for(std::chrono::seconds(0)) == std::future_status::ready) { it = validate_tasks_v.erase(it); } else { it++; } } } /** * @description: Validate srd */ void Validator::validate_srd() { // Push new task sgx_enclave_id_t eid = global_eid; validate_tasks_v.push_back(std::make_shared<std::future<void>>(validate_pool->push([eid](int /*id*/){ Ecall_validate_srd(eid); }))); // Check and remove complete task for (auto it = validate_tasks_v.begin(); it != validate_tasks_v.end(); ) { if ((*it)->wait_for(std::chrono::seconds(0)) == std::future_status::ready) { it = validate_tasks_v.erase(it); } else { it++; } } }
2,005
C++
.cpp
76
21.210526
105
0.60229
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,332
WorkReport.cpp
crustio_crust-sworker/src/app/process/WorkReport.cpp
#include "WorkReport.h" extern sgx_enclave_id_t global_eid; extern bool offline_chain_mode; crust::Log *p_log = crust::Log::get_instance(); /** * @description: used to generate random waiting time to ensure that the reporting workload is not concentrated * @param seed -> Random seed * @return: wait time */ size_t get_random_wait_time(std::string seed) { //[9 199] srand_string(seed); return (rand() % (REPORT_INTERVAL_BLCOK_NUMBER_UPPER_LIMIT - REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT + 1) + REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT - 1) * BLOCK_INTERVAL; } /** * @description: Judge whether need to exit while waiting * @param t -> Wait time * @return true for exiting */ bool wait_and_check_exit(size_t t) { EnclaveData *ed = EnclaveData::get_instance(); for (size_t i = 0; i < t; i++) { if (UPGRADE_STATUS_EXIT == ed->get_upgrade_status()) { p_log->info("Stop work report for exit...\n"); return true; } sleep(1); } return false; } /** * @description: Check if there is enough height, send signed work report to chain */ void work_report_loop(void) { sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; crust::Chain *p_chain = crust::Chain::get_instance(); size_t target_block_height = REPORT_SLOT; size_t wr_wait_time = BLOCK_INTERVAL / 2; int stop_timeout = 10 * BLOCK_INTERVAL; int stop_tryout = stop_timeout / wr_wait_time; EnclaveData *ed = EnclaveData::get_instance(); size_t cut_wait_time = 0; size_t wait_time = 0; // Set srand json::JSON id_json = json::JSON::Load_unsafe(ed->get_enclave_id_info()); // Generate target block height crust::BlockHeader block_header; if (!p_chain->get_block_header(block_header)) { p_log->warn("Cannot get block header! Set target block height %d\n", target_block_height); } else { target_block_height = (block_header.number / REPORT_SLOT + 1) * REPORT_SLOT; p_log->info("Set target block height %d\n", target_block_height); } while (true) { if (UPGRADE_STATUS_EXIT == ed->get_upgrade_status()) { p_log->info("Stop work report for exit...\n"); return; } crust::BlockHeader block_header; // ----- Report work report ----- // if (!p_chain->get_block_header(block_header)) { p_log->warn("Cannot get block header!\n"); goto loop; } if (block_header.number < target_block_height) { goto loop; } // Avoid A competing work-report with B if (UPGRADE_STATUS_STOP_WORKREPORT == ed->get_upgrade_status()) { if (--stop_tryout < 0) { stop_tryout = stop_timeout / wr_wait_time; } else { goto loop; } } cut_wait_time = (block_header.number - (block_header.number / REPORT_SLOT) * REPORT_SLOT) * BLOCK_INTERVAL; wait_time = get_random_wait_time(id_json["pub_key"].ToString()); if (cut_wait_time >= wait_time) { wait_time = 0; } else { wait_time = wait_time - cut_wait_time; } wait_time = std::max(wait_time, (size_t)REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT); p_log->info("It is estimated that the workload will be reported at the %lu block\n", block_header.number + (wait_time / BLOCK_INTERVAL) + 1); block_header.number = (block_header.number / REPORT_SLOT) * REPORT_SLOT; if (!offline_chain_mode) { if(wait_and_check_exit(wait_time)) { return; } } else { if(wait_and_check_exit(10)) { return; } } // Get confirmed block hash block_header.hash = p_chain->get_block_hash(block_header.number); if (block_header.hash == "" || block_header.hash == "0000000000000000000000000000000000000000000000000000000000000000") { p_log->warn("Get block hash failed"); goto loop; } target_block_height = block_header.number + REPORT_SLOT; // Get signed validation report if (SGX_SUCCESS != (sgx_status = Ecall_gen_and_upload_work_report(global_eid, &crust_status, block_header.hash.c_str(), block_header.number))) { p_log->err("Get signed work report failed! Message:Invoke SGX API failed, error code:%lx!\n", sgx_status); } else if (CRUST_SUCCESS != crust_status) { switch (crust_status) { case CRUST_BLOCK_HEIGHT_EXPIRED: p_log->err("Can't generate work report! Block height has expired, please check your chain.\n"); break; case CRUST_FIRST_WORK_REPORT_AFTER_REPORT: p_log->warn("Can't generate work report for the first time after restart, please wait for next slot.\n"); break; case CRUST_SERVICE_UNAVAILABLE: p_log->err("Can't generate work report! IPFS is offline, please check. If IPFS is stopped, please start it.\n"); break; case CRUST_UPGRADE_IS_UPGRADING: p_log->info("Can't generate work report! Stop reporting work in this era, because of upgrading or exiting.\n"); break; case CRUST_SGX_SIGN_FAILED: p_log->err("Can't generate work report, SGX signed failed."); break; case CRUST_WORK_REPORT_NOT_VALIDATED: p_log->err("Can't generate work report! Hardware or network is too slow, validation has not been applied.\n"); break; default: p_log->err("Get work report or upload failed. Error code: %x SF:WRE\n", crust_status); } } loop: if(wait_and_check_exit(wr_wait_time)) { return; } if (offline_chain_mode) { p_chain->add_offline_block_height(REPORT_SLOT/60); } } }
6,285
C++
.cpp
170
27.976471
176
0.577164
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,333
EnclaveData.cpp
crustio_crust-sworker/src/app/process/EnclaveData.cpp
#include "EnclaveData.h" #include "ECalls.h" crust::Log *p_log = crust::Log::get_instance(); EnclaveData *EnclaveData::enclavedata = NULL; std::mutex enclavedata_mutex; extern sgx_enclave_id_t global_eid; /** * @description: Single instance class function to get instance * @return: Enclave data instance */ EnclaveData *EnclaveData::get_instance() { if (EnclaveData::enclavedata == NULL) { enclavedata_mutex.lock(); if (EnclaveData::enclavedata == NULL) { EnclaveData::enclavedata = new EnclaveData(); } enclavedata_mutex.unlock(); } return EnclaveData::enclavedata; } /** * @description: Set enclave identity information * @param id_info -> Identity information */ void EnclaveData::set_enclave_id_info(std::string id_info) { this->enclave_id_info_mutex.lock(); this->enclave_id_info = id_info; this->enclave_id_info_mutex.unlock(); } /** * @description: Get enclave identity information * @return: Enclave information */ std::string EnclaveData::get_enclave_id_info() { SafeLock sl(this->enclave_id_info_mutex); sl.lock(); if (this->enclave_id_info.size() == 0) { sl.unlock(); sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = Ecall_id_get_info(global_eid))) { p_log->err("Get id info from enclave failed! Error code:%lx\n", ret); return ""; } sl.lock(); return this->enclave_id_info; } return this->enclave_id_info; } /** * @description: Store workreport * @param data -> Pointer to workreport data * @param data_size -> Workreport data size */ void EnclaveData::set_workreport(const uint8_t *data, size_t data_size) { workreport_mutex.lock(); this->workreport = std::string(reinterpret_cast<const char *>(data), data_size); workreport_mutex.unlock(); } /** * @description: Get workreport * @return: Workreport */ std::string EnclaveData::get_workreport() { SafeLock sl(workreport_mutex); sl.lock(); return this->workreport; } /** * @description: Set srd information * @param data -> Pointer to srd info data * @param data_size -> Srd info data size */ void EnclaveData::set_srd_info(const uint8_t *data, size_t data_size) { this->srd_info_mutex.lock(); this->srd_info = json::JSON::Load_unsafe(data, data_size); this->srd_info_mutex.unlock(); } /** * @description: Get srd information * @return: Srd information */ json::JSON EnclaveData::get_srd_info() { SafeLock sl(this->srd_info_mutex); sl.lock(); return this->srd_info; } /** * @description: Add pending file size * @param cid -> File content id * @param size -> File size */ void EnclaveData::add_pending_file_size(std::string cid, long size) { this->pending_file_size_um_mutex.lock(); this->pending_file_size_um[cid] += size; this->pending_file_size_um_mutex.unlock(); } /** * @description: Get pending file size * @param cid -> File content id * @return: Pending file size */ long EnclaveData::get_pending_file_size(std::string cid) { SafeLock sl(this->pending_file_size_um_mutex); sl.lock(); return this->pending_file_size_um[cid]; } /** * @description: Delete pending file * @param cid -> File content id */ void EnclaveData::del_pending_file_size(std::string cid) { this->pending_file_size_um_mutex.lock(); this->pending_file_size_um.erase(cid); this->pending_file_size_um_mutex.unlock(); } /** * @description: Get upgrade data * @return: Upgrade data */ std::string EnclaveData::get_upgrade_data() { SafeLock sl(this->upgrade_data_mutex); sl.lock(); return upgrade_data; } /** * @description: Set upgrade data * @param data -> Upgrade data */ void EnclaveData::set_upgrade_data(std::string data) { this->upgrade_data_mutex.lock(); this->upgrade_data = data; this->upgrade_data_mutex.unlock(); } /** * @description: Set upgrade status * @param status -> Upgrade status */ void EnclaveData::set_upgrade_status(upgrade_status_t status) { SafeLock sl(upgrade_status_mutex); sl.lock(); if (upgrade_status == status) { return; } upgrade_status = status; switch(upgrade_status) { case UPGRADE_STATUS_NONE: p_log->info("Set upgrade status to: UPGRADE_STATUS_NONE\n"); break; case UPGRADE_STATUS_STOP_WORKREPORT: p_log->info("Set upgrade status to: UPGRADE_STATUS_STOP_WORKREPORT\n"); break; case UPGRADE_STATUS_PROCESS: p_log->info("Set upgrade status to: UPGRADE_STATUS_PROCESS\n"); break; case UPGRADE_STATUS_END: p_log->info("Set upgrade status to: UPGRADE_STATUS_END\n"); break; case UPGRADE_STATUS_COMPLETE: p_log->info("Set upgrade status to: UPGRADE_STATUS_COMPLETE\n"); break; case UPGRADE_STATUS_EXIT: p_log->info("Set upgrade status to: UPGRADE_STATUS_EXIT\n"); break; default: p_log->warn("Unknown upgrade status!\n"); } sl.unlock(); if (UPGRADE_STATUS_NONE == get_upgrade_status()) { Ecall_disable_upgrade(global_eid); } } /** * @description: Get upgrade status * @return: Upgrade status */ upgrade_status_t EnclaveData::get_upgrade_status() { SafeLock sl(upgrade_status_mutex); sl.lock(); return upgrade_status; } /** * @description: Add sealed file info * @param cid -> IPFS content id * @param type -> File type * @param info -> Related file info */ void EnclaveData::add_file_info(const std::string &cid, std::string type, std::string info) { SafeLock sl(this->sealed_file_mutex); sl.lock(); std::string c_type = type; if (type.compare(FILE_TYPE_PENDING) == 0) { info = "{ \"" FILE_PENDING_STIME "\" : " + std::to_string(get_seconds_since_epoch()) + " }"; } if (type.compare(FILE_TYPE_VALID) == 0) { this->sealed_file[FILE_TYPE_PENDING].erase(cid); this->del_pending_file_size(cid); } this->sealed_file[type][cid] = info; sl.unlock(); } /** * @description: Change sealed file info from old type to new type * @param cid -> File root cid * @param old_type -> Old file type * @param new_type -> New file type */ void EnclaveData::change_file_type(const std::string &cid, std::string old_type, std::string new_type) { SafeLock sl(this->sealed_file_mutex); sl.lock(); if (this->sealed_file.find(old_type) == this->sealed_file.end()) { p_log->warn("Old type:%s no found!\n", old_type.c_str()); return; } if (this->sealed_file[old_type].find(cid) == this->sealed_file[old_type].end()) { p_log->warn("Old type:%s cid:%s not found!\n", old_type.c_str(), cid.c_str()); return; } std::string info = this->sealed_file[old_type][cid]; this->sealed_file[new_type][cid] = this->sealed_file[old_type][cid]; this->sealed_file[old_type].erase(cid); sl.unlock(); } /** * @description: Delete sealed file information * @param cid -> IPFS content id */ void EnclaveData::del_file_info(std::string cid) { SafeLock sl(this->sealed_file_mutex); sl.lock(); bool is_pending_file = false; for (auto it = this->sealed_file.begin(); it != this->sealed_file.end(); it++) { if (it->second.find(cid) != it->second.end()) { if (it->first.compare(FILE_TYPE_PENDING) == 0) is_pending_file = true; it->second.erase(cid); } } sl.unlock(); if (is_pending_file) this->del_pending_file_size(cid); } /** * @description: Delete sealed file information * @param cid -> IPFS content id * @param type -> File type */ void EnclaveData::del_file_info(std::string cid, std::string type) { SafeLock sl(this->sealed_file_mutex); sl.lock(); if (this->sealed_file[type].find(cid) != this->sealed_file[type].end()) { this->sealed_file[type].erase(cid); } sl.unlock(); if (type.compare(FILE_TYPE_PENDING) == 0) this->del_pending_file_size(cid); } /** * @description: Restore sealed file information * @param data -> All file information * @param data_size -> All file information size */ void EnclaveData::restore_file_info(const uint8_t *data, size_t data_size) { // Restore file information SafeLock sl(this->sealed_file_mutex); sl.lock(); json::JSON sealed_files = json::JSON::Load_unsafe(data, data_size); if (sealed_files.JSONType() == json::JSON::Class::Object) { for (auto it : sealed_files.ObjectRange()) { if (it.second.JSONType() == json::JSON::Class::Array) { for (auto f_it : it.second.ArrayRange()) { if (f_it.JSONType() == json::JSON::Class::Object && f_it.size() > 0) { auto val = f_it.ObjectRange().begin(); std::string info = val->second.ToString(); remove_char(info, '\\'); this->sealed_file[it.first][val->first] = info; } } } } } sl.unlock(); } /** * @description: Get sealed file item * @param cid -> File content id * @param info -> Reference to file item * @param raw -> Return raw data or a json * @return: File data */ std::string EnclaveData::get_file_info_item(std::string cid, std::string &info, bool raw) { std::string ans; std::string data = info; remove_char(data, '\\'); json::JSON data_json = json::JSON::Load_unsafe(data); if(data_json.hasKey(FILE_PENDING_STIME)) { long stime = data_json[FILE_PENDING_STIME].ToInt(); long etime = get_seconds_since_epoch(); long utime = etime - stime; data = "{ \"" FILE_PENDING_DOWNLOAD_TIME "\" : \"" + get_time_diff_humanreadable(utime) + "\" , " + "\"" FILE_PENDING_SIZE "\" : \"" + std::to_string(this->get_pending_file_size(cid)) + "\"" + " }"; } if (raw) { return "\""+cid+"\" : " + data; } return "{ \""+cid+"\" : " + data + " }"; } /** * @description: Get pending files' size * @return: Pending files' size */ size_t EnclaveData::get_pending_files_size_all() { this->sealed_file_mutex.lock(); std::map<std::string, std::string> tmp_files = this->sealed_file[FILE_TYPE_PENDING]; this->sealed_file_mutex.unlock(); size_t ans = 0; for (auto it : tmp_files) { ans += this->get_pending_file_size(it.first); } return ans; } /** * @description: Get sealed file information * @param cid -> IPFS content id * @return: Sealed file information */ std::string EnclaveData::get_file_info(std::string cid) { SafeLock sl(this->sealed_file_mutex); sl.lock(); std::string type; if (!find_file_type_nolock(cid, type)) { return ""; } json::JSON file = json::JSON::Load_unsafe(get_file_info_item(cid, this->sealed_file[type][cid], false)); file[cid]["type"] = type; std::string file_str = file.dump(); remove_char(file_str, '\\'); return file_str; } /** * @description: Get all sealed file information * @return: All sealed file information */ std::string EnclaveData::get_file_info_all() { this->sealed_file_mutex.lock(); std::map<std::string, std::map<std::string, std::string>> tmp_sealed_file = this->sealed_file; this->sealed_file_mutex.unlock(); std::string ans = "{"; std::string pad = " "; std::string tag; for (auto it = tmp_sealed_file.begin(); it != tmp_sealed_file.end(); it++) { std::string info = _get_file_info_by_type(it->first, pad + " ", true); if (info.size() != 0) { ans += tag + "\n" + pad + "\"" + it->first + "\" : {\n" + info + "\n" + pad + "}"; tag = ","; } } if (tag.compare(",") == 0) { ans += "\n"; } ans += "}"; return ans; } /** * @description: Get file info by type * @param type -> File type * @return: Result */ std::string EnclaveData::get_file_info_by_type(std::string type) { return _get_file_info_by_type(type, "", false); } /** * @description: Get sealed file information by type * @param type -> File type * @param pad -> Space pad * @param raw -> Is raw data or not * @return: All sealed file information */ std::string EnclaveData::_get_file_info_by_type(std::string type, std::string pad, bool raw) { this->sealed_file_mutex.lock(); std::map<std::string, std::map<std::string, std::string>> tmp_sealed_file = this->sealed_file; this->sealed_file_mutex.unlock(); std::string ans; std::string pad2; if (raw) { pad2 = pad; } else { ans = pad + "{"; pad2 = pad + " "; } for (auto it = tmp_sealed_file[type].begin(); it != tmp_sealed_file[type].end(); it++) { if (!raw || (raw && it != tmp_sealed_file[type].begin())) { ans += "\n"; } ans += pad2 + get_file_info_item(it->first, it->second, true); auto iit = it; iit++; if (iit != tmp_sealed_file[type].end()) { ans += ","; } else if (!raw) { ans += "\n"; } } if (!raw) { ans += pad + "}"; } return ans; } /** * @description: Check if file is duplicated * @param cid -> IPFS content id * @param type -> Reference to file status type * @return: Duplicated or not */ bool EnclaveData::find_file_type_nolock(std::string cid, std::string &type) { for (auto item : this->sealed_file) { if (item.second.find(cid) != item.second.end()) { type = item.first; return true; } } return false; } /** * @description: Check if file is duplicated * @param cid -> IPFS content id * @param type -> Reference to file status type * @return: Duplicated or not */ bool EnclaveData::find_file_type(std::string cid, std::string &type) { SafeLock sl(this->sealed_file_mutex); sl.lock(); for (auto item : this->sealed_file) { if (item.second.find(cid) != item.second.end()) { type = item.first; return true; } } return false; } /** * @description: Generate workload * @param srd_task -> Indicate recovered srd task from restart * @return: Workload in string */ std::string EnclaveData::gen_workload_str(long srd_task) { json::JSON wl_json = this->gen_workload_for_print(srd_task); std::string wl_str = wl_json.dump(); replace(wl_str, "\"{", "{"); replace(wl_str, ": \" ", ": "); replace(wl_str, "}\"", "}"); replace(wl_str, "\\n", "\n"); remove_char(wl_str, '\\'); return wl_str; } /** * @description: Generate workload * @param srd_task -> Indicate recovered srd task from restart * @return: Workload in json */ json::JSON EnclaveData::gen_workload_for_print(long srd_task) { EnclaveData *ed = EnclaveData::get_instance(); // Get srd info json::JSON wl_json; json::JSON srd_info = get_srd_info(); json::JSON disk_json = get_disk_info(); int disk_avail_for_srd = 0; int disk_avail = 0; int disk_volume = 0; std::string disk_info; disk_info.append("{\n"); for (int i = 0; i < disk_json.size(); i++) { std::string uuid = ed->get_uuid(disk_json[i][WL_DISK_PATH].ToString()); std::string disk_path = disk_json[i][WL_DISK_PATH].ToString(); uint32_t buffer_sz = disk_path.size() + 128; char buffer[buffer_sz]; memset(buffer, 0, buffer_sz); sprintf(buffer, " \"%s\" : { \"srd\" : %ld, \"srd_avail\" : %ld, \"avail\" : %ld, \"volumn\" : %ld }", disk_path.c_str(), srd_info[WL_SRD_DETAIL][uuid].ToInt(), disk_json[i][WL_DISK_AVAILABLE_FOR_SRD].ToInt(), disk_json[i][WL_DISK_AVAILABLE].ToInt(), disk_json[i][WL_DISK_VOLUME].ToInt()); disk_info.append(buffer); if (i != disk_json.size() - 1) { disk_info.append(","); } disk_info.append("\n"); disk_avail += disk_json[i][WL_DISK_AVAILABLE].ToInt(); disk_avail_for_srd += disk_json[i][WL_DISK_AVAILABLE_FOR_SRD].ToInt(); disk_volume += disk_json[i][WL_DISK_VOLUME].ToInt(); } disk_info.append("}"); std::string srd_spec; srd_spec.append("{\n") .append("\"" WL_SRD_COMPLETE "\" : ").append(std::to_string(srd_info[WL_SRD_COMPLETE].ToInt())).append(",\n") .append("\"" WL_SRD_REMAINING_TASK "\" : ").append(std::to_string(srd_info[WL_SRD_REMAINING_TASK].ToInt() + srd_task)).append(",\n") .append("\"" WL_DISK_AVAILABLE_FOR_SRD "\" : ").append(std::to_string(disk_avail_for_srd)).append(",\n") .append("\"" WL_DISK_AVAILABLE "\" : ").append(std::to_string(disk_avail)).append(",\n") .append("\"" WL_DISK_VOLUME "\" : ").append(std::to_string(disk_volume)).append(",\n") .append("\"" WL_SYS_DISK_AVAILABLE "\" : ").append(std::to_string(get_avail_space_under_dir_g(Config::get_instance()->base_path))).append(",\n") .append("\"" WL_SRD_DETAIL "\" : ").append(disk_info).append("\n") .append("}"); wl_json[WL_SRD] = srd_spec; // Get file info this->sealed_file_mutex.lock(); std::map<std::string, std::map<std::string, std::string>> tmp_sealed_file = this->sealed_file; this->sealed_file_mutex.unlock(); json::JSON file_info; for (auto type : file_spec_type) { size_t size = 0; for (auto file : tmp_sealed_file[type]) { json::JSON file_json = json::JSON::Load_unsafe(file.second); size += file_json[FILE_SIZE].ToInt(); } file_info[type]["num"].AddNum(tmp_sealed_file[type].size()); file_info[type]["size"].AddNum(size); } json::JSON n_file_info; char buf[128]; int space_num = 0; file_info[FILE_TYPE_PENDING]["size"].AddNum(this->get_pending_files_size_all()); for (auto it : file_info.ObjectRange()) { space_num = std::max(space_num, (int)it.first.size()); } for (auto it : file_info.ObjectRange()) { memset(buf, 0, sizeof(buf)); sprintf(buf, "%s{ \"num\" : %-6ld, \"size\" : %ld }", std::string(space_num - it.first.size(), ' ').c_str(), it.second["num"].ToInt(), it.second["size"].ToInt()); n_file_info[it.first] = std::string(buf); } wl_json[WL_FILES] = n_file_info; return wl_json; } /** * @description: Generate workload * @param srd_task -> Indicate recovered srd task from restart * @return: Workload in json */ json::JSON EnclaveData::gen_workload(long srd_task) { return json::JSON::Load_unsafe(gen_workload_str(srd_task)); } /** * @description: Construct uuid and disk path map */ void EnclaveData::construct_uuid_disk_path_map() { for (auto path : Config::get_instance()->get_data_paths()) { check_or_init_disk(path); } } /** * @description: Set mapping between uuid and disk path * @param uuid -> Disk uuid * @param path -> Disk path */ void EnclaveData::set_uuid_disk_path_map(std::string uuid, std::string path) { if (uuid.size() >= UUID_LENGTH * 2) { std::string r_uuid = uuid.substr(0, UUID_LENGTH * 2); uuid_disk_path_map_mutex.lock(); this->uuid_to_disk_path[r_uuid] = path; this->disk_path_to_uuid[path] = r_uuid; uuid_disk_path_map_mutex.unlock(); } } /** * @description: Get uuid by disk path * @param path -> Disk path * @return: Disk uuid */ std::string EnclaveData::get_uuid(std::string path) { SafeLock sl(uuid_disk_path_map_mutex); sl.lock(); if (this->disk_path_to_uuid.find(path) != this->disk_path_to_uuid.end()) return this->disk_path_to_uuid[path]; else return ""; } /** * @description: Get disk path by uuid * @param uuid -> Disk uuid * @return: Disk path */ std::string EnclaveData::get_disk_path(std::string uuid) { SafeLock sl(uuid_disk_path_map_mutex); sl.lock(); if (this->uuid_to_disk_path.find(uuid) != this->uuid_to_disk_path.end()) return this->uuid_to_disk_path[uuid]; else return ""; } /** * @description: Check if related uuid is existed in given path * @param path -> Disk path * @return: Is the mapping existed by given disk path */ bool EnclaveData::is_disk_exist(std::string path) { SafeLock sl(uuid_disk_path_map_mutex); sl.lock(); return this->disk_path_to_uuid.find(path) != this->disk_path_to_uuid.end(); } /** * @description: Check if related path is existed in given uuid * @param uuid -> Disk uuid * @return: Is the mapping existed by given uuid */ bool EnclaveData::is_uuid_exist(std::string uuid) { SafeLock sl(uuid_disk_path_map_mutex); sl.lock(); return this->uuid_to_disk_path.find(uuid) != this->uuid_to_disk_path.end(); }
21,135
C++
.cpp
695
25.293525
156
0.603788
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,334
EntryNetwork.cpp
crustio_crust-sworker/src/app/process/EntryNetwork.cpp
#include "EntryNetwork.h" #include "ECalls.h" namespace http = boost::beast::http; // from <boost/beast/http.hpp> extern sgx_enclave_id_t global_eid; extern bool is_ecdsa_mode; crust::Log *p_log = crust::Log::get_instance(); /** * @description: Entry network off-chain node sends quote to onchain node to verify identity, EPID mode * @return: Result status */ crust_status_t entry_network_epid() { p_log->info("Entrying network epid...\n"); sgx_quote_sign_type_t linkable = SGX_UNLINKABLE_SIGNATURE; sgx_status_t status, sgxrv; sgx_report_t report; sgx_report_t qe_report; sgx_quote_t *quote; sgx_target_info_t target_info; sgx_epid_group_id_t epid_gid; uint32_t sz = 0; uint32_t flags = IAS_FLAGS; sgx_quote_nonce_t nonce; char *b64quote = NULL; char *b64manifest = NULL; sgx_spid_t *spid = (sgx_spid_t *)malloc(sizeof(sgx_spid_t)); memset(spid, 0, sizeof(sgx_spid_t)); from_hexstring((unsigned char *)spid, IAS_SPID, strlen(IAS_SPID)); int i = 0; int common_tryout = 5; crust_status_t crust_status = CRUST_SUCCESS; // ----- get nonce ----- // for (i = 0; i < 2; ++i) { int retry = 10; unsigned char ok = 0; uint64_t *np = (uint64_t *)&nonce; while (!ok && retry) ok = _rdrand64_step(&np[i]); if (ok == 0) { p_log->err("Nonce: RDRAND underflow\n"); return CRUST_UNEXPECTED_ERROR; } } if (OPT_ISSET(flags, OPT_LINK)) { linkable = SGX_LINKABLE_SIGNATURE; } // ----- Get SGX quote ----- // memset(&report, 0, sizeof(report)); int tryout = 1; do { status = sgx_init_quote(&target_info, &epid_gid); if (SGX_SUCCESS == status) break; switch (status) { case SGX_ERROR_BUSY: p_log->info("SGX device is busy, trying again(%d time)...\n", tryout); break; case SGX_ERROR_SERVICE_TIMEOUT: p_log->info("The request to AE service timed out, trying again(%d time)...\n", tryout); break; case SGX_ERROR_NETWORK_FAILURE: p_log->info("AES network connecting or proxy setting issue is encountered, trying again(%d time)...\n", tryout); break; case SGX_ERROR_UPDATE_NEEDED: p_log->err("SGX init quote failed!You should upgrade your BIOS.Error code:%lx\n", status); return CRUST_DEVICE_ERROR; default: p_log->err("SGX init quote failed!Error code: %lx\n", status); return CRUST_INIT_QUOTE_FAILED; } if (tryout > common_tryout) { p_log->err("Initialize sgx quote tryout!\n"); return CRUST_INIT_QUOTE_FAILED; } tryout++; sleep(60); } while (true); status = Ecall_get_quote_report(global_eid, &sgxrv, &report, &target_info); if (status != SGX_SUCCESS) { p_log->err("get_report: %lx\n", status); return CRUST_UNEXPECTED_ERROR; } if (sgxrv != SGX_SUCCESS) { p_log->err("sgx_create_report: %lx\n", sgxrv); return CRUST_UNEXPECTED_ERROR; } // sgx_get_quote_size() has been deprecated, but SGX PSW may be too old // so use a wrapper function. if (!get_quote_size(&status, &sz)) { p_log->err("PSW missing sgx_get_quote_size() and sgx_calc_quote_size()\n"); return CRUST_UNEXPECTED_ERROR; } if (status != SGX_SUCCESS) { p_log->err("SGX error while getting quote size: %lx\n", status); return CRUST_UNEXPECTED_ERROR; } quote = (sgx_quote_t *)malloc(sz); if (quote == NULL) { p_log->err("out of memory\n"); return CRUST_MALLOC_FAILED; } memset(quote, 0, sz); p_log->debug("========== linkable: %d\n", linkable); p_log->debug("========== spid : %s\n", hexstring(spid, sizeof(sgx_spid_t))); p_log->debug("========== nonce : %s\n", hexstring(&nonce, sizeof(sgx_quote_nonce_t))); status = sgx_get_quote(&report, linkable, spid, &nonce, NULL, 0, &qe_report, quote, sz); if (status != SGX_SUCCESS) { p_log->err("sgx_get_quote: %lx\n", status); return CRUST_UNEXPECTED_ERROR; } // ----- Print SGX quote ----- // p_log->debug("quote report_data: %s\n", hexstring((const void *)(quote->report_body.report_data.d), sizeof(quote->report_body.report_data.d))); p_log->debug("ias quote report version :%d\n", quote->version); p_log->debug("ias quote report signtype:%d\n", quote->sign_type); p_log->debug("ias quote report epid :%d\n", *quote->epid_group_id); p_log->debug("ias quote report qe svn :%d\n", quote->qe_svn); p_log->debug("ias quote report pce svn :%d\n", quote->pce_svn); p_log->debug("ias quote report xeid :%d\n", quote->xeid); p_log->debug("ias quote report basename:%s\n", hexstring(quote->basename.name, 32)); p_log->debug("ias quote mr enclave :%s\n", hexstring(&quote->report_body.mr_enclave, 32)); // Get base64 quote b64quote = base64_encode((char *)quote, sz); if (b64quote == NULL) { p_log->err("Could not base64 encode quote\n"); return CRUST_UNEXPECTED_ERROR; } p_log->debug("{\n"); p_log->debug("\"isvEnclaveQuote\":\"%s\"", b64quote); if (OPT_ISSET(flags, OPT_NONCE)) { p_log->debug(",\n\"nonce\":\""); print_hexstring(&nonce, 16); p_log->debug("\""); } if (OPT_ISSET(flags, OPT_PSE)) { p_log->debug(",\n\"pseManifest\":\"%s\"", b64manifest); } p_log->debug("\n}\n"); // ----- Entry network process ----- // HttpClient *client = new HttpClient(); ApiHeaders headers = { {"Ocp-Apim-Subscription-Key", IAS_PRIMARY_SUBSCRIPTION_KEY} }; std::string body = "{\n\"isvEnclaveQuote\":\""; body.append(b64quote); body.append("\"\n}"); std::string resStr; http::response<http::string_body> ias_res; // Send quote to IAS service int net_tryout = IAS_TRYOUT; std::string ias_report_url(IAS_BASE_URL); ias_report_url.append(IAS_REPORT_PATH); while (net_tryout > 0) { ias_res = client->SSLPost(ias_report_url, body, "application/json", headers, HTTP_REQ_INSECURE); if ((int)ias_res.result() != 200) { p_log->err("Send to IAS failed! Trying again...(%d)\n", IAS_TRYOUT - net_tryout + 1); sleep(3); net_tryout--; continue; } break; } if ((int)ias_res.result() != 200) { p_log->err("Request IAS failed!\n"); delete client; return CRUST_UNEXPECTED_ERROR; } p_log->info("Sending quote to IAS service successfully!\n"); std::vector<const char *> ias_report; std::string ias_cer(ias_res["X-IASReport-Signing-Certificate"]); std::string ias_sig(ias_res["X-IASReport-Signature"]); std::string ias_quote_body(ias_res.body()); ias_report.push_back(ias_cer.c_str()); ias_report.push_back(ias_sig.c_str()); ias_report.push_back(ias_quote_body.c_str()); p_log->debug("\n\n----------IAS Report - JSON - Required Fields----------\n\n"); json::JSON ias_body_json = json::JSON::Load_unsafe(ias_res.body()); int version = IAS_API_DEF_VERSION; if (version >= 3) { p_log->debug("version = %ld\n", ias_body_json["version"].ToInt()); } p_log->debug("id: = %s\n", ias_body_json["id"].ToString().c_str()); p_log->debug("timestamp = %s\n", ias_body_json["timestamp"].ToString().c_str()); p_log->debug("isvEnclaveQuoteStatus = %s\n", ias_body_json["isvEnclaveQuoteStatus"].ToString().c_str()); p_log->debug("isvEnclaveQuoteBody = %s\n", ias_body_json["isvEnclaveQuoteBody"].ToString().c_str()); std::string iasQuoteStr(ias_body_json["isvEnclaveQuoteBody"].ToString()); size_t qs; char *ppp = base64_decode(iasQuoteStr.c_str(), &qs); sgx_quote_t *ias_quote = (sgx_quote_t *)malloc(qs); memset(ias_quote, 0, qs); memcpy(ias_quote, ppp, qs); p_log->debug("ias quote report data = %s\n", hexstring(ias_quote->report_body.report_data.d, sizeof(ias_quote->report_body.report_data.d))); p_log->debug("ias quote report version = %d\n", ias_quote->version); p_log->debug("ias quote report signtype = %d\n", ias_quote->sign_type); p_log->debug("ias quote report basename = %s\n", hexstring(&ias_quote->basename, sizeof(sgx_basename_t))); p_log->debug("ias quote report mr_enclave = %s\n", hexstring(&ias_quote->report_body.mr_enclave, sizeof(sgx_measurement_t))); p_log->debug("\n\n----------IAS Report - JSON - Optional Fields----------\n\n"); p_log->debug("platformInfoBlob = %s\n", std::string(ias_res["platformInfoBlob"]).c_str()); p_log->debug("revocationReason = %s\n", std::string(ias_res["revocationReason"]).c_str()); p_log->debug("pseManifestStatus = %s\n", std::string(ias_res["pseManifestStatus"]).c_str()); p_log->debug("pseManifestHash = %s\n", std::string(ias_res["pseManifestHash"]).c_str()); p_log->debug("nonce = %s\n", std::string(ias_res["nonce"]).c_str()); p_log->debug("epidPseudonym = %s\n\n", std::string(ias_res["epidPseudonym"]).c_str()); // Verify and upload IAS report sgx_status_t status_ret = Ecall_gen_upload_epid_identity(global_eid, &crust_status, const_cast<char**>(ias_report.data()), ias_report.size()); if (SGX_SUCCESS == status_ret) { switch (crust_status) { case CRUST_SUCCESS: p_log->info("Entry network application has been sent successfully!\n"); break; case CRUST_IAS_BADREQUEST: p_log->err("Verify IAS report failed! Bad request!!\n"); break; case CRUST_IAS_UNAUTHORIZED: p_log->err("Verify IAS report failed! Unauthorized!!\n"); break; case CRUST_IAS_NOT_FOUND: p_log->err("Verify IAS report failed! Not found!!\n"); break; case CRUST_IAS_SERVER_ERR: p_log->err("Verify IAS report failed! Server error!!\n"); break; case CRUST_IAS_UNAVAILABLE: p_log->err("Verify IAS report failed! Unavailable!!\n"); break; case CRUST_IAS_INTERNAL_ERROR: p_log->err("Verify IAS report failed! Internal error!!\n"); break; case CRUST_IAS_BAD_CERTIFICATE: p_log->err("Verify IAS report failed! Bad certificate!!\n"); break; case CRUST_IAS_BAD_SIGNATURE: p_log->err("Verify IAS report failed! Bad signature!!\n"); break; case CRUST_IAS_REPORTDATA_NE: p_log->err("Verify IAS report failed! Report data not equal!!\n"); break; case CRUST_IAS_GET_REPORT_FAILED: p_log->err("Verify IAS report failed! Get report in current enclave failed!!\n"); break; case CRUST_IAS_BADMEASUREMENT: p_log->err("Verify IAS report failed! Bad enclave code measurement!!\n"); break; case CRUST_IAS_UNEXPECTED_ERROR: p_log->err("Verify IAS report failed! unexpected error!!\n"); break; case CRUST_IAS_GETPUBKEY_FAILED: p_log->err("Verify IAS report failed! Get public key from certificate failed!!\n"); break; case CRUST_SIGN_PUBKEY_FAILED: p_log->err("Sign public key failed!!\n"); break; case CRUST_SWORKER_UPGRADE_NEEDED: p_log->err("Sworker upgrade needed!!\n"); break; default: p_log->err("Unknown return status!\n"); } } else { p_log->err("Invoke SGX api failed!\n"); crust_status = CRUST_UNEXPECTED_ERROR; } delete client; return crust_status; } /** * @description: Entry network with ECDSA off-chain node sends quote to onchain node to verify identity, ECDSA mode * @return: Result status */ crust_status_t entry_network_ecdsa() { p_log->info("Entrying network ecdsa...\n"); sgx_status_t sgxrv; quote3_error_t status = SGX_QL_SUCCESS; sgx_report_t report; sgx_target_info_t target_info; uint32_t quote_sz = 0; sgx_quote_nonce_t nonce; int common_tryout = 5; // ----- get nonce ----- // for (int i = 0; i < 2; ++i) { int retry = 10; unsigned char ok = 0; uint64_t *np = (uint64_t *)&nonce; while (!ok && retry) ok = _rdrand64_step(&np[i]); if (ok == 0) { p_log->err("Nonce: RDRAND underflow\n"); return CRUST_UNEXPECTED_ERROR; } } // ----- Get SGX quote ----- // memset(&report, 0, sizeof(report)); int tryout = 1; do { status = sgx_qe_get_target_info(&target_info); if (SGX_QL_SUCCESS == status) break; switch (status) { case SGX_QL_ERROR_INVALID_PARAMETER: p_log->err("p_target_info must not be NULL.\n"); break; case SGX_QL_ERROR_UNEXPECTED: p_log->err("Unexpected internal error occurred.\n"); break; case SGX_QL_ENCLAVE_LOAD_ERROR: p_log->err("Unable to load the enclaves required to initialize the attestation key. error or some other loading infrastructure errors.\n"); break; case SGX_QL_ENCLAVE_LOST: p_log->err("Enclave is lost after power transition or used in a child process created by linux:fork().\n"); break; case SGX_QL_NO_PLATFORM_CERT_DATA: p_log->err("The platform quote provider library doesn't have the platform certification data for this platform.\n"); break; case SGX_QL_NO_DEVICE: p_log->err("Can't open SGX device. This error happens only when running in out-of-process mode.\n"); break; case SGX_QL_SERVICE_UNAVAILABLE: p_log->err("Indicates AESM didn't respond or the requested service is not supported. This error happens only when running in out-of-process mode.\n"); break; case SGX_QL_NETWORK_FAILURE: p_log->err("Network connection or proxy setting issue is encountered. This error happens only when running in out-of-process mode.\n"); break; case SGX_QL_SERVICE_TIMEOUT: p_log->err("The request to out-of-process service has timed out. This error happens only when running in out- of-process mode.\n"); break; case SGX_QL_ERROR_BUSY: p_log->err("The requested service is temporarily not available. This error happens only when running in out- of-process mode.\n"); break; case SGX_QL_UNSUPPORTED_ATT_KEY_ID: p_log->err("Unsupported attestation key ID.\n"); break; case SGX_QL_UNKNOWN_MESSAGE_RESPONSE: p_log->err("Unexpected error from the attestation infrastructure while retrieving the platform data.\n"); break; case SGX_QL_ERROR_MESSAGE_PARSING_ERROR: p_log->err("Generic message parsing error from the attestation infrastructure while retrieving the platform data.\n"); break; case SGX_QL_PLATFORM_UNKNOWN: p_log->err("This platform is an unrecognized SGX platform.\n"); break; default: p_log->err("SGX init quote failed!Error code: %lx\n", status); return CRUST_INIT_QUOTE_FAILED; } if (tryout > common_tryout) { p_log->err("Initialize sgx quote tryout!\n"); return CRUST_INIT_QUOTE_FAILED; } tryout++; sleep(60); } while (true); sgx_status_t sgx_ret = Ecall_get_quote_report(global_eid, &sgxrv, &report, &target_info); if (sgx_ret != SGX_SUCCESS) { p_log->err("get_report: %lx\n", sgx_ret); return CRUST_UNEXPECTED_ERROR; } if (sgxrv != SGX_SUCCESS) { p_log->err("sgx_create_report: %lx\n", sgxrv); return CRUST_UNEXPECTED_ERROR; } // sgx_get_quote_size() has been deprecated, but SGX PSW may be too old // so use a wrapper function. //if (!get_quote_size(&status, &quote_sz)) if (SGX_QL_SUCCESS != sgx_qe_get_quote_size(&quote_sz)) { p_log->err("PSW missing sgx_get_quote_size() and sgx_calc_quote_size()\n"); return CRUST_UNEXPECTED_ERROR; } if (status != SGX_QL_SUCCESS) { p_log->err("SGX error while getting quote size: %lx\n", status); return CRUST_UNEXPECTED_ERROR; } uint8_t *p_quote_buffer = (uint8_t *)malloc(quote_sz); if (p_quote_buffer == NULL) { p_log->err("out of memory\n"); return CRUST_MALLOC_FAILED; } memset(p_quote_buffer, 0, quote_sz); status = sgx_qe_get_quote(&report, quote_sz, p_quote_buffer); if (status != SGX_QL_SUCCESS) { p_log->err("sgx_get_quote: %lx\n", status); return CRUST_UNEXPECTED_ERROR; } _sgx_quote3_t *quote = (_sgx_quote3_t*)p_quote_buffer; uint8_t *p_pub_key = reinterpret_cast<uint8_t *>(&quote->report_body.report_data); uint8_t *p_mr_enclave = reinterpret_cast<uint8_t *>(&quote->report_body.mr_enclave); // ----- Print SGX quote ----- // p_log->debug("quote info:\n"); p_log->debug("enclave public key:%s\n", hexstring_safe(p_pub_key, sizeof(sgx_ec256_public_t)).c_str()); p_log->debug("quote mrenclave :%s\n", hexstring_safe(p_mr_enclave, sizeof(sgx_measurement_t)).c_str()); // ----- Entry network process ----- // crust_status_t crust_status = CRUST_SUCCESS; // Generate the ecdsa quote inside enclave and upload the quote to Crust DCAP service if (SGX_SUCCESS != (sgx_ret = Ecall_gen_upload_ecdsa_quote(global_eid, &crust_status, p_quote_buffer, quote_sz))) { p_log->err("Generate and upload ecdsa quote to dcap service failed due to invoke SGX API failed, error code:%lx\n", sgx_ret); return CRUST_SGX_FAILED; } if (CRUST_SUCCESS != crust_status) { p_log->err("Generate and upload identity to dcap service failed, error code:%lx\n", crust_status); return crust_status; } p_log->info("Generate and upload ecdsa quote to dcap service successfully!\n"); // Get verification result from registry chain std::string res = crust::Chain::get_instance()->get_ecdsa_verify_result(); if (res.size() == 0) { p_log->err("Get ecdsa verify result failed!"); return CRUST_UNEXPECTED_ERROR; } p_log->info("Get ecdsa verify result successfully!\n%s\n", res.c_str()); // Extract the report data from the result body json::JSON dcap_body_json = json::JSON::Load_unsafe(res); std::string dcap_report = dcap_body_json["report_body"].dump(); // Upload final identity to crust chain if (SGX_SUCCESS != (sgx_ret = Ecall_gen_upload_ecdsa_identity(global_eid, &crust_status, dcap_report.c_str(), dcap_report.size()))) { p_log->err("Generate and upload identity to crust chain failed due to invoke SGX API failed, error code:%lx\n", sgx_ret); return CRUST_SGX_FAILED; } if (CRUST_SUCCESS != crust_status) { p_log->err("Generate and upload identity to crust chain failed, error code:%lx\n", crust_status); return crust_status; } p_log->info("Enter network successfully!\n"); return CRUST_SUCCESS; } /** * @description: Entry network * @return: Result status */ crust_status_t entry_network() { return is_ecdsa_mode ? entry_network_ecdsa() : entry_network_epid(); }
20,007
C++
.cpp
482
33.651452
162
0.59391
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,335
Srd.cpp
crustio_crust-sworker/src/app/process/Srd.cpp
#include "Srd.h" #include "ECalls.h" crust::Log *p_log = crust::Log::get_instance(); size_t g_running_srd_task = 0; std::mutex g_running_srd_task_mutex; extern sgx_enclave_id_t global_eid; /** * @description: Check or initilize disk * @param path -> Disk path * @return: Check or init result */ bool check_or_init_disk(std::string path) { crust_status_t crust_status = CRUST_SUCCESS; EnclaveData *ed = EnclaveData::get_instance(); Config *p_config = Config::get_instance(); // Check if given path is in the system disk if (!p_config->is_valid_or_normal_disk(path)) { return false; } // Check if uuid file exists std::string uuid_file = path + DISK_UUID_FILE; if (access(uuid_file.c_str(), R_OK) != -1) { // Check if uuid to disk path mapping existed if (!ed->is_disk_exist(path)) { uint8_t *p_data = NULL; size_t data_sz = 0; if (CRUST_SUCCESS != (crust_status = get_file(uuid_file.c_str(), &p_data, &data_sz))) { p_log->err("Get existed path:%s uuid failed! Error code:%lx\n", uuid_file.c_str(), crust_status); return false; } ed->set_uuid_disk_path_map(reinterpret_cast<const char *>(p_data), path); free(p_data); p_log->debug("Restore uuid:'%s' to runtime env successfully!\n", uuid_file.c_str()); } else { return true; } } else { if (!ed->is_disk_exist(path)) { // Create uuid file uint8_t *buf = (uint8_t *)malloc(UUID_LENGTH); Defer def_buf([&buf](void) { free(buf); }); memset(buf, 0, UUID_LENGTH); read_rand(buf, UUID_LENGTH); std::string uuid = hexstring_safe(buf, UUID_LENGTH); crust_status = save_file_ex(uuid_file.c_str(), reinterpret_cast<const uint8_t *>(uuid.c_str()), uuid.size(), 0444, SF_CREATE_DIR); if (CRUST_SUCCESS != crust_status) { p_log->err("Save uuid file to path:'%s' failed! Error code:%lx\n", path.c_str(), crust_status); return false; } // Set uuid to data path information ed->set_uuid_disk_path_map(uuid, path); p_log->debug("Save uuid:'%s' successfully!\n", uuid_file.c_str()); } else { // uuid file is deleted in runtime, create it again with the existed one std::string uuid = ed->get_uuid(path); crust_status = save_file_ex(uuid_file.c_str(), reinterpret_cast<const uint8_t *>(uuid.c_str()), uuid.size(), 0444, SF_CREATE_DIR); if (CRUST_SUCCESS != crust_status) { p_log->err("Save uuid file to path:'%s' failed! Error code:%lx\n", path.c_str(), crust_status); return false; } p_log->debug("Restore uuid:'%s' to file successfully!\n", uuid_file.c_str()); } } // Create current disk std::string srd_dir = path + DISK_SRD_DIR; if (CRUST_SUCCESS != create_directory(srd_dir)) { p_log->err("Cannot create dir:%s\n", srd_dir.c_str()); return false; } return true; } /** * @description: Get srd disks info according to configure * @param change -> Reference to changed task, will be modified to left srd task * @return: A path to assigned size map */ json::JSON get_increase_srd_info_r(long &change) { size_t true_srd_capacity = 0; // Get multi-disk info Config *p_config = Config::get_instance(); EnclaveData *ed = EnclaveData::get_instance(); json::JSON disk_info_json = json::Array(); // Create path for (auto path : p_config->get_data_paths()) { if (check_or_init_disk(path)) { std::string uuid = ed->get_uuid(path); // Calculate free disk long srd_reserved_space = get_reserved_space(); json::JSON tmp_info_json; tmp_info_json[WL_DISK_AVAILABLE] = get_avail_space_under_dir_g(path); tmp_info_json[WL_DISK_VOLUME] = get_total_space_under_dir_g(path); if (tmp_info_json[WL_DISK_AVAILABLE].ToInt() <= srd_reserved_space) { tmp_info_json[WL_DISK_AVAILABLE_FOR_SRD] = 0; } else { tmp_info_json[WL_DISK_AVAILABLE_FOR_SRD] = tmp_info_json[WL_DISK_AVAILABLE].ToInt() - srd_reserved_space; } tmp_info_json[WL_DISK_UUID] = uuid; tmp_info_json[WL_DISK_PATH] = path; true_srd_capacity += tmp_info_json[WL_DISK_AVAILABLE_FOR_SRD].ToInt(); disk_info_json.append(tmp_info_json); } } // Get to be used info bool avail = true; while (change > 0 && avail) { avail = false; for (int i = 0; i < disk_info_json.size() && change > 0; i++) { if (disk_info_json[i][WL_DISK_AVAILABLE_FOR_SRD].ToInt() - disk_info_json[i][WL_DISK_USE].ToInt() > 0) { disk_info_json[i][WL_DISK_USE].AddNum(1); change--; avail = true; } } } return disk_info_json; } /** * @description: Wrapper for get_increase_srd_info_r * @param change -> Reference to srd task, will be changed and modified to left srd task * @return: Srd info in json format */ json::JSON get_increase_srd_info(long &change) { json::JSON disk_json = get_increase_srd_info_r(change); json::JSON srd_inc_json = json::Array(); for (auto info : disk_json.ArrayRange()) { if (info[WL_DISK_USE].ToInt() > 0) { srd_inc_json.append(info); } } return srd_inc_json; } /** * @description: Wrapper for get_increase_srd_info_r * @return: Srd info in json format */ json::JSON get_disk_info() { long c = 0; return get_increase_srd_info_r(c); } /** * @description: Change SRD space * @param change -> SRD space number * @return: Srd change result */ crust_status_t srd_change(long change) { Config *p_config = Config::get_instance(); crust_status_t crust_status = CRUST_SUCCESS; if (change > 0) { long left_task = change; json::JSON inc_srd_json = get_increase_srd_info(left_task); long true_increase = change - left_task; // Add left change to next srd, if have if (left_task > 0) { p_log->warn("No enough space for %ldG srd, can only do %ldG srd.\n", change, true_increase); crust_status = CRUST_SRD_NUMBER_EXCEED; } if (true_increase <= 0) { //p_log->warn("No available space for srd!\n"); return CRUST_SRD_NUMBER_EXCEED; } set_running_srd_task(true_increase); // Print disk info for (auto info : inc_srd_json.ArrayRange()) { p_log->info("Available space is %ldG in '%s', this turn will use %ldG space\n", info[WL_DISK_AVAILABLE_FOR_SRD].ToInt(), info[WL_DISK_PATH].ToString().c_str(), info[WL_DISK_USE].ToInt()); } p_log->info("Start sealing %luG srd files (thread number: %d) ...\n", true_increase, p_config->srd_thread_num); // ----- Do srd ----- // // Use omp parallel to seal srd disk, the number of threads is equal to the number of CPU cores ctpl::thread_pool pool(p_config->srd_thread_num); std::vector<std::shared_ptr<std::future<crust_status_t>>> tasks_v; long task = true_increase; long srd_end = false; while (task > 0 && !srd_end) { srd_end = true; for (int i = 0; i < inc_srd_json.size(); i++) { if (inc_srd_json[i][WL_DISK_USE].ToInt() > 0) { // Set flags task--; srd_end = false; inc_srd_json[i][WL_DISK_USE].AddNum(-1); // Do srd sgx_enclave_id_t eid = global_eid; std::string uuid = inc_srd_json[i][WL_DISK_UUID].ToString(); tasks_v.push_back(std::make_shared<std::future<crust_status_t>>(pool.push([eid, uuid](int /*id*/){ crust_status_t inc_crust_ret = CRUST_SUCCESS; sgx_status_t inc_sgx_ret = Ecall_srd_increase(eid, &inc_crust_ret, uuid.c_str()); if (SGX_SUCCESS != inc_sgx_ret) { switch (inc_sgx_ret) { case SGX_ERROR_SERVICE_TIMEOUT: p_log->warn("Srd task release resource for higher priority task.\n"); break; default: p_log->err("Increase srd failed! Error code:%lx\n", inc_sgx_ret); } if (CRUST_SUCCESS == inc_crust_ret) { inc_crust_ret = CRUST_SGX_FAILED; } } decrease_running_srd_task(); return inc_crust_ret; }))); } } } // Wait for srd task size_t srd_success_num = 0; for (auto it : tasks_v) { try { if (CRUST_SUCCESS == it->get()) { srd_success_num++; } } catch (std::exception &e) { p_log->err("Catch exception:"); std::cout << e.what() << std::endl; } } set_running_srd_task(0); if (srd_success_num < (size_t)true_increase) { long left = true_increase - srd_success_num; p_log->info("Srd task: %dG, success: %dG, left: %dG.\n", true_increase, srd_success_num, left); // Add left srd task to next turn crust_status_t change_crust_ret = CRUST_SUCCESS; long real_change = 0; sgx_status_t change_sgx_ret = Ecall_change_srd_task(global_eid, &change_crust_ret, left, &real_change); if(SGX_SUCCESS != change_sgx_ret) { p_log->err("Add left srd task:%dG failed! Invoke Ecall_change_srd_task SGX API failed! Error code:%lx\n", left, change_sgx_ret); } else if (CRUST_SUCCESS != change_crust_ret) { switch (change_crust_ret) { case CRUST_UPGRADE_IS_UPGRADING: p_log->info("Add left srd task failed due to upgrade.\n"); break; default: p_log->err("Add left srd task failed, real add task:%dG! Error code:%lx\n", real_change, change_crust_ret); } } } else { p_log->info("Increase %dG srd files success.\n", true_increase); } } else if (change < 0) { size_t true_decrease = 0; set_running_srd_task(change); Ecall_srd_decrease(global_eid, &true_decrease, (size_t)-change); set_running_srd_task(0); p_log->info("Decrease %luG srd successfully.\n", true_decrease); } return crust_status; } /** * @description: Check if disk's available space is smaller than minimal reserved space, * if it is, delete srd space */ void srd_check_reserved(void) { Config *p_config = Config::get_instance(); sgx_status_t sgx_status = SGX_SUCCESS; size_t check_interval = 10; while (true) { if (UPGRADE_STATUS_EXIT == EnclaveData::get_instance()->get_upgrade_status()) { p_log->info("Stop srd check reserved for exit...\n"); return; } long srd_reserved_space = get_reserved_space(); // Lock srd_info EnclaveData *ed = EnclaveData::get_instance(); json::JSON srd_del_json; json::JSON srd_info_json = ed->get_srd_info(); for (auto path : p_config->get_data_paths()) { size_t avail_space = get_avail_space_under_dir_g(path); long del_space = 0; if ((long)avail_space < srd_reserved_space) { std::string uuid = ed->get_uuid(path); del_space = std::min((long)(srd_reserved_space - avail_space), (long)srd_info_json[WL_SRD_DETAIL][uuid].ToInt()); if (del_space > 0) { srd_del_json[uuid].AddNum(del_space); } } } // Do remove if (srd_del_json.size() > 0) { std::string srd_del_str = srd_del_json.dump(); remove_char(srd_del_str, ' '); remove_char(srd_del_str, '\\'); remove_char(srd_del_str, '\n'); if (SGX_SUCCESS != Ecall_srd_remove_space(global_eid, srd_del_str.c_str(), srd_del_str.size())) { p_log->err("Invoke srd metadata failed! Error code:%lx\n", sgx_status); } } // Refresh data paths p_config->refresh_data_paths(); // Wait for (size_t i = 0; i < check_interval; i++) { if (UPGRADE_STATUS_EXIT == EnclaveData::get_instance()->get_upgrade_status()) { p_log->info("Stop srd check reserved for exit...\n"); return; } sleep(1); } } } /** * @description: Get reserved space * @return: srd reserved space */ size_t get_reserved_space() { return DEFAULT_SRD_RESERVED; } /** * @description: Set running srd task number * @param srd_task -> Srd task number */ void set_running_srd_task(long srd_task) { g_running_srd_task_mutex.lock(); g_running_srd_task = srd_task; g_running_srd_task_mutex.unlock(); } /** * @description: Get running srd task number * @return: Running task number */ long get_running_srd_task() { long srd_task = 0; g_running_srd_task_mutex.lock(); srd_task = g_running_srd_task; g_running_srd_task_mutex.unlock(); return srd_task; } /** * @description: Decrease one running srd task */ void decrease_running_srd_task() { g_running_srd_task_mutex.lock(); if (g_running_srd_task > 0) { g_running_srd_task--; } g_running_srd_task_mutex.unlock(); }
14,652
C++
.cpp
408
25.980392
144
0.528952
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,336
Common.cpp
crustio_crust-sworker/src/app/utils/Common.cpp
#include "Common.h" #include "ECalls.h" crust::Log *p_log = crust::Log::get_instance(); /** * @description: Get url end point from url * @param url -> base url, like: http://127.0.0.1:56666/api/v1 * @return: Url end point */ UrlEndPoint get_url_end_point(std::string url) { UrlEndPoint url_end_point; std::string proto_type; size_t spos = 0, epos; // Get protocal tag epos = url.find("://"); if (epos != url.npos) { proto_type = url.substr(0, epos); spos = epos + std::strlen("://"); } // Get host, port and path epos = url.find(":", spos); if (epos == url.npos) { epos = url.find("/", spos); if (epos == url.npos) { url_end_point.ip = url.substr(spos, url.length()); goto parse_end; } url_end_point.ip = url.substr(spos, epos - spos); url_end_point.base = url.substr(epos, url.size()); p_log->warn("Parse url warn: Port not indicate, will assign port by protocol.\n"); if (proto_type.compare("https") == 0) { url_end_point.port = 443; } else if (proto_type.compare("http") == 0) { url_end_point.port = 80; } else { p_log->warn("Parse url warn: Cannot assign port by protocal!\n"); } p_log->info("Parse url warn: Set port to:%d\n", url_end_point.port); } else { url_end_point.ip = url.substr(spos, epos - spos); spos = epos + 1; epos = url.find("/", spos); if (epos == url.npos) { url_end_point.port = std::atoi(url.substr(spos, epos - spos).c_str()); goto parse_end; } url_end_point.port = std::atoi(url.substr(spos, epos - spos).c_str()); url_end_point.base = url.substr(epos, url.size()); } parse_end: return url_end_point; } /** * @description: Remove chars from string * @param str -> input string * @param chars_to_remove -> removed chars */ void remove_chars_from_string(std::string &str, const char *chars_to_remove) { for (unsigned int i = 0; i < strlen(chars_to_remove); ++i) { str.erase(std::remove(str.begin(), str.end(), chars_to_remove[i]), str.end()); } } /** * @description: Deserialize merkle tree from json * @param tree_json -> Merkle tree json * @return: Merkle tree root node */ MerkleTree *deserialize_merkle_tree_from_json(json::JSON tree_json) { if (tree_json.JSONType() != json::JSON::Class::Object) return NULL; MerkleTree *root = new MerkleTree(); std::string hash = tree_json["hash"].ToString(); size_t hash_len = hash.size() + 1; root->hash = (char*)malloc(hash_len); memset(root->hash, 0, hash_len); memcpy(root->hash, hash.c_str(), hash.size()); root->links_num = tree_json["links_num"].ToInt(); json::JSON children = tree_json["links"]; if (root->links_num != 0) { root->links = (MerkleTree**)malloc(root->links_num * sizeof(MerkleTree*)); for (uint32_t i = 0; i < root->links_num; i++) { MerkleTree *child = deserialize_merkle_tree_from_json(children[i]); if (child == NULL) { free(root->hash); free(root->links); return NULL; } root->links[i] = child; } } return root; } /** * @description: Serialize MerkleTree to json * @param root -> MerkleTree root node * @return: MerkleTree json structure */ json::JSON serialize_merkletree_to_json(MerkleTree *root) { if (root == NULL) return ""; json::JSON tree; tree["hash"] = std::string(root->hash); tree["links_num"] = root->links_num; for (size_t i = 0; i < root->links_num; i++) { tree["links"][i] = serialize_merkletree_to_json(root->links[i]); } return tree; } /** * @description: Free MerkleTree buffer * @param root -> Pointer to MerkleTree root */ void free_merkletree(MerkleTree *root) { if (root == NULL) return; free(root->hash); if (root->links_num > 0) { for (size_t i = 0; i < root->links_num; i++) { free_merkletree(root->links[i]); } free(root->links); } } /** * @description: Hex string to int * @param s -> Pointer to hex char array * @return: Int */ static inline int htoi(char *s) { int value; int c; c = ((unsigned char *)s)[0]; if (isupper(c)) c = tolower(c); value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = ((unsigned char *)s)[1]; if (isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return (value); } /** * @description: Decode url to flat string * @param url -> Reference to url * @return: Decoded url */ std::string flat_urlformat(std::string &url) { int len = url.size(); char *dest = (char *)malloc(url.size()); memset(dest, 0, url.size()); char *org = dest; int i = 0; while (len-- >= 0) { if (url[i] == '+') { *dest = ' '; } else if (url[i] == '%' && len >= 2 && isxdigit((int) url[i + 1]) && isxdigit((int) url[i + 2])) { *dest = (char) htoi(&url[i + 1]); i += 2; len -= 2; } else { *dest = url[i]; } i++; dest++; } *dest = '\0'; std::string ret = std::string(org, dest - org); free(dest); return ret; } /** * @description: Judge if a string is a number * @param s -> Const reference to string * @return: Number or not */ bool is_number(const std::string &s) { if (s.size() == 0) return false; for (auto c : s) { if (!isdigit(c)) { return false; } } return true; } /** * @description: Replace org_str to det_str in data * @param data -> Reference to origin data * @param org_str -> Replaced string * @param det_str -> Replaced to string */ void replace(std::string &data, std::string org_str, std::string det_str) { size_t spos, epos; spos = epos = 0; while (true) { spos = data.find(org_str, epos); if (spos == data.npos) { break; } data.replace(spos, org_str.size(), det_str); epos = spos + det_str.size(); } } /** * @description: Remove indicated character from string * @param data -> Reference to string * @param c -> Character to be removed */ void remove_char(std::string &data, char c) { data.erase(std::remove(data.begin(), data.end(), c), data.end()); } /** * @description: Use string to set srand * @param seed -> random seed */ void srand_string(std::string seed) { unsigned int seed_number = 0; for (size_t i = 0; i < seed.size(); i++) { seed_number += seed[i]*(i+1); } srand(time(NULL) + seed_number); } /** * @description: Print logo * @param logo -> Logo image * @param color -> Logo color */ void print_logo(const char *logo, const char *color) { std::string gap = std::string(PRINT_GAP, ' '); std::string logo_str(logo); replace(logo_str, "%", "\\"); replace(logo_str, "\n", "\n" + gap); logo_str = color + gap + logo_str + NC; printf("\n%s\n", logo_str.c_str()); } /** * @description: Print attention logo */ void print_attention() { std::string gap = std::string(PRINT_GAP, ' '); std::string attention(ATTENTION_LOGO); replace(attention, "%", "\\"); replace(attention, "\n", "\n" + gap); attention = HRED + gap + attention + NC; printf("\n%s\n", attention.c_str()); } /** * @description: Sleep some time(indicated by 'time') second by second * @param time -> Sleep total time(in second) * @param func -> Will be executed function * @return: Function result */ bool sleep_interval(uint32_t time, std::function<bool()> func) { for (uint32_t i = 0; i < time; i++) { if (!func()) { return false; } sleep(1); } return true; } /** * @description: Convert float to string and trim result * @param num -> Converted double value * @return: Converted result */ std::string float_to_string(double num) { std::string ans = std::to_string(num); size_t lpos = ans.find_last_not_of("0"); if (lpos != ans.npos) { if (ans[lpos] != '.') { lpos++; } ans = ans.substr(0, lpos); } return ans; } /** * @description: Fill given buffer random bytes * @param buf -> Pointer to given buffer * @param buf_size -> Buffer size */ void read_rand(uint8_t *buf, size_t buf_size) { std::random_device rd; // Will be used to obtain a seed for the random number engine std::mt19937 mt(rd()); // Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<uint8_t> dist(0, 255); // Same distribution as before, but explicit and without bias for (size_t i = 0; i < buf_size; i++) { buf[i] = dist(mt); } shuffle(buf, buf + buf_size, mt); } /** * @description: Get second since epoch * @return: Seconds */ decltype(seconds_t().count()) get_seconds_since_epoch() { // get the current time const auto now = std::chrono::system_clock::now(); // transform the time into a duration since the epoch const auto epoch = now.time_since_epoch(); // cast the duration into seconds const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(epoch); // return the number of seconds return seconds.count(); } /** * @description: Get time difference * @param sec -> Seconds * @return: Time in string */ std::string get_time_diff_humanreadable(long sec) { if (sec == 0) return "0s"; std::string ans; int mit, hor, day; day = mit = hor = 0; if (sec >= 60) { mit = sec / 60; sec = sec % 60; } if (mit >= 60) { hor = mit / 60; mit = mit % 60; } if (hor >= 24) { day = hor / 24; hor = hor % 24; } if (day > 0) ans += std::to_string(day) + "d"; if (hor > 0) ans += std::to_string(hor) + "h"; if (mit > 0) ans += std::to_string(mit) + "m"; if (sec > 0) ans += std::to_string(sec) + "s"; return ans; } /** * @description: Get file humanreadable size * @param size -> Input size * @return: Humanreadable size */ std::string get_file_size_humanreadable(size_t size) { if (size == 0) return "0K"; std::string ans; std::string tag; std::string left; size_t file_size = size; std::vector<std::string> tags = {"K", "M", "G"}; for (int i = 0; i < 3; i++) { if (file_size > 1024) { left = float_to_string((double)(file_size % 1024) / (double)1024).substr(1, 2); file_size = file_size / 1024; if (left[left.size() - 1] == '0') { left = ""; } tag = tags[i]; } else { break; } } return std::to_string(file_size) + left + tag; } /** * @description: Safe store data inside enclave * @param eid -> Enclave id * @param status -> Ecall function return status * @param t -> Ecall function type * @param u -> Pointer to data * @param s -> Data length * @return: Ocall result */ sgx_status_t safe_ecall_store2(sgx_enclave_id_t eid, crust_status_t *status, ecall_store_type_t t, const uint8_t *u, size_t s) { sgx_status_t ret = SGX_SUCCESS; size_t offset = 0; uint32_t buffer_key = 0; read_rand(reinterpret_cast<uint8_t *>(&buffer_key), sizeof(buffer_key)); while (s > offset) { size_t partial_size = std::min(s - offset, (size_t)BOUNDARY_SIZE_THRESHOLD); ret = Ecall_safe_store2(eid, status, t, u + offset, s, partial_size, offset, buffer_key); if (SGX_SUCCESS != ret) { return ret; } if (CRUST_SUCCESS != *status) { return ret; } offset += partial_size; } return ret; }
12,464
C++
.cpp
465
20.95914
126
0.547342
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,337
SafeLock.cpp
crustio_crust-sworker/src/app/utils/SafeLock.cpp
#include "SafeLock.h" SafeLock::~SafeLock() { if (this->lock_time > 0) { this->_mutex.unlock(); } } void SafeLock::lock() { if (this->lock_time == 0) { this->_mutex.lock(); this->lock_time++; } } void SafeLock::unlock() { if (this->lock_time > 0) { this->lock_time--; this->_mutex.unlock(); } }
374
C++
.cpp
24
11.291667
30
0.512968
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,338
FileUtils.cpp
crustio_crust-sworker/src/app/utils/FileUtils.cpp
#include "FileUtils.h" crust::Log *p_log = crust::Log::get_instance(); /** * @description: Get all files' name in directory * @param path -> the directory path * @return: File's name vector */ std::vector<std::string> get_files_under_path(const std::string &path) { std::vector<std::string> files; DIR *dir; struct dirent *ptr; if ((dir = opendir(path.c_str())) == NULL) { perror("Open dir error..."); exit(-1); } while ((ptr = readdir(dir)) != NULL) { if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) // current dir OR parrent dir { continue; } else if (ptr->d_type == 8) // file { files.push_back(ptr->d_name); } } closedir(dir); return files; } /** * @description: Get all folders' name in directory * @param path -> the directory path * @return: Folder's name vector */ std::vector<std::string> get_folders_under_path(const std::string &path) { std::vector<std::string> folders; DIR *dir; struct dirent *ptr; if ((dir = opendir(path.c_str())) == NULL) { perror("Open dir error..."); exit(1); } while ((ptr = readdir(dir)) != NULL) { if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) // current dir OR parrent dir { continue; } else if (ptr->d_type == 4) // folder { folders.push_back(ptr->d_name); } } closedir(dir); return folders; } /** * @description: Recursively delete all the file in the directory * @param dir_full_path -> the directory path * @return: 0 for successed, -1 for falied */ int rm_dir(const std::string &dir_full_path) { DIR *dirp = opendir(dir_full_path.c_str()); if (!dirp) { return -1; } struct dirent *dir; struct stat st; while ((dir = readdir(dirp)) != NULL) { if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) { continue; } std::string sub_path = dir_full_path + '/' + dir->d_name; if (lstat(sub_path.c_str(), &st) == -1) { continue; } if (S_ISDIR(st.st_mode)) { if (rm_dir(sub_path) == -1) { closedir(dirp); return -1; } rmdir(sub_path.c_str()); } else if (S_ISREG(st.st_mode)) { unlink(sub_path.c_str()); } else { continue; } } if (rmdir(dir_full_path.c_str()) == -1) //delete dir itself. { closedir(dirp); return -1; } closedir(dirp); return 0; } /** * @description: Recursively delete all the file in the directory or delete file * @param path -> the directory path or filepath * @return: 0 for successed, -1 for falied */ int rm(const std::string &path) { std::string file_path = path; struct stat st; if (lstat(file_path.c_str(), &st) == -1) { return -1; } if (S_ISREG(st.st_mode)) { if (unlink(file_path.c_str()) == -1) { return -1; } } else if (S_ISDIR(st.st_mode)) { if (path == "." || path == "..") { return -1; } if (rm_dir(file_path) == -1) //delete all the files in dir. { return -1; } } return 0; } /** * @description: Get free space under directory * @param path -> the directory path * @param unit -> Used to indicate KB, MB and GB * @return: Free space size (M) */ size_t get_total_space_under_dir_r(const std::string &path, uint32_t unit) { struct statfs disk_info; if (statfs(path.c_str(), &disk_info) == -1) { return 0; } size_t avail_disk = (size_t)disk_info.f_blocks * (size_t)disk_info.f_bsize; return avail_disk >> unit; } /** * @description: Get disk free space according to path * @param path -> Checked path * @return: Free space calculated as KB */ size_t get_total_space_under_dir_k(const std::string &path) { return get_total_space_under_dir_r(path, 10); } /** * @description: Get disk free space according to path * @param path -> Checked path * @return: Free space calculated as MB */ size_t get_total_space_under_dir_m(const std::string &path) { return get_total_space_under_dir_r(path, 20); } /** * @description: Get disk free space according to path * @param path -> Checked path * @return: Free space calculated as GB */ size_t get_total_space_under_dir_g(const std::string &path) { return get_total_space_under_dir_r(path, 30); } /** * @description: Get free space under directory * @param path -> the directory path * @param unit -> Used to indicate KB, MB and GB * @return: Free space size (M) */ size_t get_avail_space_under_dir_r(const std::string &path, uint32_t unit) { struct statfs disk_info; if (statfs(path.c_str(), &disk_info) == -1) { return 0; } size_t avail_disk = (size_t)disk_info.f_bavail * (size_t)disk_info.f_bsize; return avail_disk >> unit; } /** * @description: Get disk free space according to path * @param path -> Checked path * @return: Free space calculated as KB */ size_t get_avail_space_under_dir_k(const std::string &path) { return get_avail_space_under_dir_r(path, 10); } /** * @description: Get disk free space according to path * @param path -> Checked path * @return: Free space calculated as MB */ size_t get_avail_space_under_dir_m(const std::string &path) { return get_avail_space_under_dir_r(path, 20); } /** * @description: Get disk free space according to path * @param path -> Checked path * @return: Free space calculated as GB */ size_t get_avail_space_under_dir_g(const std::string &path) { return get_avail_space_under_dir_r(path, 30); } /** * @description: Get free space under directory * @param path -> the directory path * @return: Free space size (M) */ size_t get_free_space_under_directory(const std::string &path) { struct statfs disk_info; if (statfs(path.c_str(), &disk_info) == -1) { return 0; } size_t total_blocks = disk_info.f_bsize; size_t free_disk = (size_t)disk_info.f_bfree * total_blocks; return free_disk >> 20; } /** * @description: Create directory * @param path -> the directory path * @return: Create status */ crust_status_t create_directory(const std::string &path) { if (path.size() == 0) { p_log->err("Create diretory path cannot be null!\n"); return CRUST_UNEXPECTED_ERROR; } std::stack<std::string> sub_paths; sub_paths.push(path); while (!sub_paths.empty()) { if (access(sub_paths.top().c_str(), 0) != -1) { sub_paths.pop(); if (!sub_paths.empty()) { if (system((std::string("timeout 60 mkdir -p ") + sub_paths.top()).c_str()) != 0) { return CRUST_MKDIR_FAILED; } } } else { std::string stop = sub_paths.top(); std::string sub_path = stop.substr(0, stop.find_last_of("/")); if (sub_path.size() > 1) { sub_paths.push(sub_path); } } } return CRUST_SUCCESS; } /** * @description: Rename old_path to new_path * @param old_path -> Old path * @param new_path -> New path * @return: Rename result */ crust_status_t rename_dir(const std::string &old_path, const std::string &new_path) { if (access(old_path.c_str(), 0) == -1) { return CRUST_RENAME_FILE_FAILED; } if (rename(old_path.c_str(), new_path.c_str()) == -1) { p_log->err("Rename file:%s to file:%s failed!\n", old_path.c_str(), new_path.c_str()); return CRUST_RENAME_FILE_FAILED; } return CRUST_SUCCESS; } /** * @description: Get sub folders and files in indicated path * @param path -> Indicated path * @return: Array of sub folders and files */ std::vector<std::string> get_sub_folders_and_files(const char *path) { DIR *dir; struct dirent *ent; std::vector<std::string> dirs; if ((dir = opendir(path)) != NULL) { while ((ent = readdir(dir)) != NULL) { if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; dirs.push_back(std::string(ent->d_name)); } closedir(dir); } return dirs; } /** * @description: Get file content * @param path -> Pointer to file path * @param p_data -> Pointer to pointer to file data * @param data_size -> Pointer to file data size * @return: Getting result status */ crust_status_t get_file(const char *path, uint8_t **p_data, size_t *data_size) { crust_status_t crust_status = CRUST_SUCCESS; if (access(path, R_OK) == -1) { return CRUST_ACCESS_FILE_FAILED; } // Judge if given path is file struct stat s; if (stat(path, &s) == 0) { if (s.st_mode & S_IFDIR) return CRUST_OPEN_FILE_FAILED; } std::ifstream in; in.open(path, std::ios::in | std::ios::binary); if (! in) { return CRUST_OPEN_FILE_FAILED; } in.seekg(0, std::ios::end); *data_size = in.tellg(); in.seekg(0, std::ios::beg); uint8_t *p_buf = (uint8_t *)malloc(*data_size); if (CRUST_SUCCESS != crust_status) { in.close(); return crust_status; } memset(p_buf, 0, *data_size); in.read(reinterpret_cast<char *>(p_buf), *data_size); in.close(); *p_data = p_buf; return crust_status; } /** * @description: Store file to given path * @param path -> Pointer to stored path * @param data -> Pointer to stored data * @param data_size -> Stored data size * @return: Store result */ crust_status_t save_file(const char *path, const uint8_t *data, size_t data_size) { return save_file_ex(path, data, data_size, 0664, SF_NONE); } /** * @description: Store file to given path and create related directory * @param path -> Pointer to stored path * @param data -> Pointer to stored data * @param data_size -> Stored data size * @param mode -> File mode * @param type -> Safe file type * @return: Store result */ crust_status_t save_file_ex(const char *path, const uint8_t *data, size_t data_size, mode_t mode, save_file_type_t type) { if (SF_CREATE_DIR == type) { crust_status_t crust_status = CRUST_SUCCESS; std::string path_str(path); size_t last_slash = path_str.find_last_of("/"); if (last_slash != 0 && last_slash != std::string::npos) { std::string dir_path = path_str.substr(0, last_slash); if (CRUST_SUCCESS != (crust_status = create_directory(dir_path))) { return crust_status; } } } std::ofstream out; out.open(path, std::ios::out | std::ios::binary); if (! out.is_open()) { return CRUST_OPEN_FILE_FAILED; } Defer def_out([&out, &path, &mode](void) { out.close(); chmod(path, mode); }); crust_status_t crust_status = CRUST_SUCCESS; try { out.write(reinterpret_cast<const char *>(data), data_size); } catch (std::exception e) { crust_status = CRUST_WRITE_FILE_FAILED; p_log->err("Save file:%s failed! Error: %s\n", path, e.what()); } out.close(); return crust_status; } /** * @description: Get real path by type * @param path (in) -> Pointer to path * @param type -> Store type * @return: Real path */ std::string get_real_path_by_type(const char *path, store_type_t type) { switch (type) { case STORE_TYPE_SRD: break; case STORE_TYPE_FILE: break; default: return std::string(path); } EnclaveData *ed = EnclaveData::get_instance(); std::string r_path; bool valid_path = true; Defer def_r_path([&valid_path, &path](void) { if (!valid_path && std::strlen(path) != 0) { p_log->debug("Invalid path:'%s', cannot get real path.\n", path); } }); if (std::strlen(path) < UUID_LENGTH * 2) { valid_path = false; return ""; } std::string uuid(path, UUID_LENGTH * 2); std::string d_path = ed->get_disk_path(uuid); if (d_path.compare("") == 0) { p_log->debug("Cannot find path for uuid:%s\n", uuid.c_str()); valid_path = false; return ""; } switch (type) { case STORE_TYPE_SRD: { if (std::strlen(path) < UUID_LENGTH * 2 + 4) { valid_path = false; return ""; } r_path = d_path + DISK_SRD_DIR + "/" + std::string(path + UUID_LENGTH * 2, 2) + "/" + std::string(path + UUID_LENGTH * 2 + 2, 2) + "/" + std::string(path + UUID_LENGTH * 2 + 4); break; } case STORE_TYPE_FILE: { if (std::strlen(path) < UUID_LENGTH * 2 + 4) { valid_path = false; return ""; } r_path = d_path + DISK_FILE_DIR + "/" + std::string(path + UUID_LENGTH * 2 + 2, 2) + "/" + std::string(path + UUID_LENGTH * 2 + 4, 2) + "/" + std::string(path + UUID_LENGTH * 2); break; } default: r_path = std::string(path); } return r_path; } /** * @description: Get file path by given path * @param path -> Pointer to file path * @param type -> File type * @return: File size */ long get_file_size(const char *path, store_type_t type) { std::string r_path = get_real_path_by_type(path, type); struct stat stat_buf; int ret = stat(r_path.c_str(), &stat_buf); return ret == 0 ? stat_buf.st_size : 0; } /** * @description: Check if file exists by given path * @param path -> Pointer to file path * @param type -> File type * @return: Exists or not */ bool is_file_exist(const char *path, store_type_t type) { std::string r_path = get_real_path_by_type(path, type); if (access(r_path.c_str(), R_OK) != -1) { return true; } return false; } /** * @description: Get file or folder size * @param path -> File or folder path * @return: File or folder size */ size_t get_file_or_folder_size(const std::string &path) { namespace fs = std::experimental::filesystem; size_t file_size = 0; fs::path folder_path(path); if (fs::exists(folder_path)) { for (auto p : fs::directory_iterator(path)) { std::string file_path = p.path(); try { if (!fs::is_directory(p.status())) { file_size += fs::file_size(file_path); } else { file_size += get_file_or_folder_size(file_path); } } catch(std::exception& e) { p_log->debug("Get file:%s size failed! Error message:%s\n", file_path.c_str(), e.what()); } } } return file_size; } /** * @description: Get file size by cid * @param cid -> File content id * @return: File size */ size_t get_file_size_by_cid(const std::string &cid) { size_t file_size = 0; std::string path_post = std::string(DISK_FILE_DIR) + "/" + cid.substr(2,2) + "/" + cid.substr(4,2) + "/" + cid; json::JSON disk_json = get_disk_info(); std::set<size_t> searched_paths; for (size_t i = 2; i < cid.size(); i+=2) { size_t di = (cid[i] + cid[i+1]) % disk_json.size(); if (searched_paths.find(di) == searched_paths.end()) { std::string file_path = disk_json[di][WL_DISK_PATH].ToString() + path_post; file_size += get_file_or_folder_size(file_path); searched_paths.insert(di); } } return file_size; }
16,343
C++
.cpp
586
21.670648
120
0.555626
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,340
Chain.cpp
crustio_crust-sworker/src/app/chain/Chain.cpp
#include "Chain.h" crust::Log *p_log = crust::Log::get_instance(); HttpClient *pri_chain_client = NULL; extern bool offline_chain_mode; std::string dcap_quote_report = ""; namespace crust { Chain *Chain::chain = NULL; std::mutex chain_mutex; /** * @description: single instance class function to get instance * @return: chain instance */ Chain *Chain::get_instance() { if (Chain::chain == NULL) { Config *p_config = Config::get_instance(); chain_mutex.lock(); if (Chain::chain == NULL) { Chain::chain = new Chain(p_config->chain_api_base_url, p_config->chain_password, p_config->chain_backup, offline_chain_mode); } chain_mutex.unlock(); } return Chain::chain; } /** * @description: new a chain handler to access chain node * @param url -> chain API base url, like: http://127.0.0.1:56666/api/v1 * @param password_tmp -> the password of chain account id * @param backup_tmp -> the backup of chain account id * @param is_offline -> Off chain mode or not */ Chain::Chain(std::string url, std::string password_tmp, std::string backup_tmp, bool is_offline) { this->url = url; this->password = password_tmp; this->backup = backup_tmp; this->is_offline = is_offline; this->offline_block_height = 0; pri_chain_client = new HttpClient(); } /** * @description: destructor */ Chain::~Chain() { if (pri_chain_client != NULL) { delete pri_chain_client; pri_chain_client = NULL; } } /** * @description: get laster block header from chain * @param block_header -> Reference to block_header * @return: the point of block header */ bool Chain::get_block_header(BlockHeader &block_header) { if (this->is_offline) { offline_block_height_mutex.lock(); if (this->offline_block_height == 0) { this->offline_block_height = this->get_offline_block_height(); } block_header.number = this->offline_block_height; offline_block_height_mutex.unlock(); block_header.hash = "1000000000000000000000000000000000000000000000000000000000000001"; return true; } std::string path = this->url + "/block/header"; http::response<http::string_body> res = pri_chain_client->Get(path.c_str()); if ((int)res.result() == 200) { json::JSON block_header_json = json::JSON::Load_unsafe(res.body()); block_header.hash = block_header_json["hash"].ToString().erase(0,2); block_header.number = block_header_json["number"].ToInt(); return true; } if (res.body().size() != 0) { p_log->err("%s\n", res.body().c_str()); } else { p_log->err("%s\n", "Get block header:return body is null"); } return false; } /** * @description: get block hash by number * @param block_number block number * @return: block hash */ std::string Chain::get_block_hash(size_t block_number) { if (this->is_offline) { return "1000000000000000000000000000000000000000000000000000000000000001"; } std::string url = this->url + "/block/hash?blockNumber=" + std::to_string(block_number); http::response<http::string_body> res = pri_chain_client->Get(url.c_str()); std::string res_body = res.body(); if ((int)res.result() == 200) { if (res_body.size() > 3) { return res_body.substr(3, 64); } } if (res_body.size() != 0) { p_log->info("%s\n", res_body.c_str()); } else { p_log->err("%s\n", "Get block hash:return body is null"); } return ""; } /** * @description: get block hash by number * @return: swork code on chain */ std::string Chain::get_swork_code() { if (this->is_offline) { return "04579f4102301d39f68032446b63fc0cede4817cf099312a0c397a760651af98"; } std::string url = this->url + "/swork/code"; http::response<http::string_body> res = pri_chain_client->Get(url.c_str()); std::string res_body = res.body(); if ((int)res.result() == 200) { if (res_body.size() > 3) { return res_body.substr(3, 64); } } if (res_body.size() != 0) { p_log->info("%s\n", res_body.c_str()); } else { p_log->err("%s\n", "Get swork code:return body is null"); } return ""; } /** * @description: test if chian is online * @return: test result */ bool Chain::is_online(void) { if (this->is_offline) { return true; } std::string path = this->url + "/block/header"; http::response<http::string_body> res = pri_chain_client->Get(path.c_str()); if ((int)res.result() == 200) { return true; } return false; } /** * @description: test if chian is syncing * @return: test result */ bool Chain::is_syncing(void) { if (this->is_offline) { return false; } std::string path = this->url + "/system/health"; http::response<http::string_body> res = pri_chain_client->Get(path.c_str()); if ((int)res.result() == 200) { json::JSON system_health_json = json::JSON::Load_unsafe(res.body()); return system_health_json["isSyncing"].ToBool(); } if (res.body().size() != 0) { p_log->err("%s\n", res.body().c_str()); } else { p_log->err("%s\n", "Is syncing:return body is null"); } return true; } /** * @description: waiting for the crust chain to run * @return: success or not */ bool Chain::wait_for_running(void) { if (this->is_offline) { return true; } size_t start_block_height = 10; while (true) { if (this->is_online()) { break; } else { p_log->info("Waiting for chain to run...\n"); sleep(3); } } while (true) { crust::BlockHeader block_header; if (!this->get_block_header(block_header)) { p_log->info("Waiting for chain to run...\n"); sleep(3); continue; } if (block_header.number >= start_block_height) { break; } else { p_log->info("Wait for the chain to execute after %lu blocks, now is %lu ...\n", start_block_height, block_header.number); sleep(3); } } while (true) { if (!this->is_syncing() && !this->is_syncing()) { break; } else { crust::BlockHeader block_header; if (this->get_block_header(block_header)) { p_log->info("Wait for chain synchronization to complete, currently synchronized to the %lu block\n", block_header.number); } else { p_log->info("Waiting for chain to run...\n"); } sleep(6); } } return true; } /** * @description: post sworker identity to chain chain * @param identity -> sworker identity * @return: success or fail */ bool Chain::post_epid_identity(std::string identity) { if (this->is_offline) { return true; } for (int i = 0; i < 20; i++) { std::string path = this->url + "/swork/identity"; ApiHeaders headers = {{"password", this->password}, {"Content-Type", "application/json"}}; crust_status_t crust_status = CRUST_SUCCESS; json::JSON obj = json::JSON::Load(&crust_status, identity); if (CRUST_SUCCESS != crust_status) { p_log->err("Parse sworker identity failed! Error code:%lx\n", crust_status); return false; } obj["backup"] = this->backup; http::response<http::string_body> res = pri_chain_client->Post(path.c_str(), obj.dump(), "application/json", headers); if ((int)res.result() == 200) { return true; } if (res.body().size() != 0) { p_log->err("Chain result: %s, wait 10s and try again\n", res.body().c_str()); } else { p_log->err("Chain result: %s, wait 10s and try again\n", "upload identity:return body is null"); } sleep(10); } return false; } /** * @description: post sworker ecdsa quote to Crust DCAP Service * @param quote -> sworker quote * @return: success or fail */ bool Chain::post_ecdsa_quote(std::string quote) { if (this->is_offline) { return true; } p_log->info("id:%s\n", quote.c_str()); int wait_time = 10; dcap_quote_report = ""; // Clear the cached report first Config *p_config = Config::get_instance(); for (int i = 0; i < 20; i++) { std::string dcap_report_url(p_config->dcap_base_url); dcap_report_url.append(p_config->dcap_report_path); http::response<http::string_body> res; if (dcap_report_url.find("https://") == 0) { res = pri_chain_client->SSLPost(dcap_report_url.c_str(), quote, "application/json", HTTP_REQ_INSECURE); } else { res = pri_chain_client->Post(dcap_report_url.c_str(), quote, "application/json"); } if ((int)res.result() == 200) { dcap_quote_report = res.body(); return true; } if (res.body().size() != 0) { p_log->err("DCAP verification result failed: %s, wait %ds and try again\n", res.body().c_str(), wait_time); } else { p_log->err("DCAP verification result failed: return body is null, wait %ds and try again\n", wait_time); } sleep(wait_time); } return false; } /** * @description: Post sworker identity to crust chain * @param identity -> sworker identity * @return: success or fail */ bool Chain::post_ecdsa_identity(const std::string identity) { if (this->is_offline) { return true; } p_log->debug("identity:%s\n", identity.c_str()); int wait_time = 10; for (int i = 0; i < 20; i++) { std::string path = this->url + "/swork/registerWithDCAP"; ApiHeaders headers = {{"password", this->password}, {"Content-Type", "application/json"}}; crust_status_t crust_status = CRUST_SUCCESS; json::JSON obj = json::JSON::Load(&crust_status, identity); if (CRUST_SUCCESS != crust_status) { p_log->err("Parse sworker identity failed! Error code:%lx\n", crust_status); return false; } obj["backup"] = this->backup; http::response<http::string_body> res = pri_chain_client->Post(path.c_str(), obj.dump(), "application/json", headers); if ((int)res.result() == 200) { return true; } if (res.body().size() != 0) { p_log->err("Chain result: %s, wait %ds and try again\n", res.body().c_str(), wait_time); } else { p_log->err("Chain result: return body is null, wait %ds and try again\n", wait_time); } sleep(wait_time); } return false; } /** * @description: Get verification report from local cache which is set by post_ecdsa_quote() * @return: Verification report */ std::string Chain::get_ecdsa_verify_result() { if (this->is_offline) return ""; return dcap_quote_report; } /** * @description: post sworker work report to chain * @param work_report -> sworker work report * @return: success or fail */ bool Chain::post_sworker_work_report(std::string work_report) { if (this->is_offline) { return true; } for (int i = 0; i < 20; i++) { std::string path = this->url + "/swork/workreport"; ApiHeaders headers = {{"password", this->password}, {"Content-Type", "application/json"}}; crust_status_t crust_status = CRUST_SUCCESS; json::JSON obj = json::JSON::Load(&crust_status, work_report); if (CRUST_SUCCESS != crust_status) { p_log->err("Parse sworker workreport failed! Error code:%lx\n", crust_status); return false; } obj["backup"] = this->backup; http::response<http::string_body> res = pri_chain_client->Post(path.c_str(), obj.dump(), "application/json", headers); if ((int)res.result() == 200) { return true; } if (res.body().size() != 0) { json::JSON res_json = json::JSON::Load_unsafe(res.body()); std::string msg = res_json["message"].ToString(); if (msg == "swork.InvalidReportTime") { p_log->err("Chain error: %s. Please check the synchronization of the chain!\n", res.body().c_str()); return false; } else if (msg == "swork.IllegalReporter") { p_log->err("Chain error: %s. The current account does not match the original account, please stop sworker and reconfigure! SF:WRE\n", res.body().c_str()); return false; } else if (msg == "swork.OutdatedReporter") { p_log->err("Chain error: %s. The current sworker has expired, please shovel the data and run a new sworker! SF:WRE\n", res.body().c_str()); return false; } else if (msg == "swork.IllegalWorkReportSig" || msg == "swork.IllegalFilesTransition" || msg == "swork.ABUpgradeFailed") { p_log->err("Chain error: %s SF:WRE\n", res.body().c_str()); return false; } else { p_log->err("Chain error: %s, wait 10s and try again. SF:WRE\n", res.body().c_str()); } } else { p_log->err("Chain result: %s, wait 10s and try again. SF:WRE\n", "upload workreport:return body is null"); } sleep(10); } return false; } size_t Chain::get_offline_block_height(void) { std::string offline_base_height_str = ""; if (crust::DataBase::get_instance()->get("offline_block_height_key", offline_base_height_str) == CRUST_SUCCESS) { std::stringstream sstream(offline_base_height_str); size_t h = 0; sstream >> h; return h; } return 0; } void Chain::add_offline_block_height(size_t h) { offline_block_height_mutex.lock(); crust::DataBase::get_instance()->set("offline_block_height_key", std::to_string(this->offline_block_height + h)); this->offline_block_height += h; offline_block_height_mutex.unlock(); } } // namespace crust
14,707
C++
.cpp
484
23.640496
170
0.572247
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,341
Config.cpp
crustio_crust-sworker/src/app/config/Config.cpp
#include "Config.h" using namespace std; Config *Config::config = NULL; std::mutex config_mutex; crust::Log *p_log = crust::Log::get_instance(); std::string config_file_path = CRUST_INST_DIR "/etc/Config.json"; /** * @description: Single instance class function to get instance * @return: Configure instance */ Config *Config::get_instance() { SafeLock sl(config_mutex); sl.lock(); if (Config::config == NULL) { Config::config = new Config(); if (!Config::config->init(config_file_path)) { delete Config::config; return NULL; } } return Config::config; } /** * @description: Initialze config * @param path -> Configure file path * @return: Initialize result */ bool Config::init(std::string path) { crust_status_t crust_status = CRUST_SUCCESS; /* Read user configurations from file */ std::ifstream config_ifs(path); std::string config_str((std::istreambuf_iterator<char>(config_ifs)), std::istreambuf_iterator<char>()); // Fill configurations json::JSON config_value = json::JSON::Load(&crust_status, config_str); if (CRUST_SUCCESS != crust_status) { p_log->err("Parse configure json failed! Error code:%lx\n", crust_status); return false; } crust::Log *p_log = crust::Log::get_instance(); // Base configurations this->base_path = config_value["base_path"].ToString(); if (this->base_path.compare("") == 0) { p_log->err("'base path' cannot be empty! Please configure 'base_path'!\n"); return false; } this->db_path = this->base_path + "/db"; if (CRUST_SUCCESS != (crust_status = create_directory(this->db_path))) { p_log->err("Create path:'%s' failed! Error code:%lx\n", this->db_path.c_str(), crust_status); return false; } // Set data path json::JSON data_paths = config_value["data_path"]; if (data_paths.JSONType() != json::JSON::Class::Array || data_paths.size() < 0) { p_log->err("Please configure 'data_path'!\n"); return false; } for (int i = 0; i < data_paths.size(); i++) { std::string d_path = data_paths[i].ToString(); this->org_data_paths.push_back(d_path); if (CRUST_SUCCESS != (crust_status = create_directory(d_path))) { p_log->err("Create path:'%s' failed! Error code:%lx\n", d_path.c_str(), crust_status); return false; } } if (! this->unique_paths()) { p_log->warn("No valid data path is configured!\n"); } // Set base url this->base_url = config_value["base_url"].ToString(); if (this->base_url.compare("") == 0) { p_log->err("Please configure 'base_url'!\n"); return false; } // Set srd related this->srd_thread_num = std::min(omp_get_num_procs() * 2, SRD_THREAD_NUM); // Set storage configure related this->ipfs_url = config_value["ipfs_url"].ToString(); if (this->ipfs_url.compare("") == 0) { p_log->err("Please configure 'ipfs_url'!\n"); return false; } // ----- Crust chain configure ----- // // Base url this->chain_api_base_url = config_value["chain"]["base_url"].ToString(); if (this->chain_api_base_url.compare("") == 0) { p_log->err("Please configure 'chain base_url'!\n"); return false; } // Address this->chain_address = config_value["chain"]["address"].ToString(); if (this->chain_address.compare("") == 0) { p_log->err("Please configure 'chain address'!\n"); return false; } // Account id this->chain_account_id = config_value["chain"]["account_id"].ToString(); if (this->chain_account_id.compare("") == 0) { p_log->err("Please configure 'chain account_id'!\n"); return false; } if (this->chain_account_id.find("0x") != this->chain_account_id.npos) { this->chain_account_id.erase(0, 2); } // Password this->chain_password = config_value["chain"]["password"].ToString(); if (this->chain_password.compare("") == 0) { p_log->err("Please configure 'chain password'!\n"); return false; } // Backup std::string backup_temp = config_value["chain"]["backup"].ToString(); remove_chars_from_string(backup_temp, "\\"); this->chain_backup = backup_temp; if (this->chain_backup.compare("") == 0) { p_log->err("Please configure 'chain backup'!\n"); return false; } // Crust DCAP service this->dcap_base_url = config_value["dcap"]["base_url"].ToString(); if (this->dcap_base_url.compare("") == 0) { this->dcap_base_url = DCAP_BASE_URL; } this->dcap_report_path = config_value["dcap"]["report_path"].ToString(); if (this->dcap_report_path.compare("") == 0) { this->dcap_report_path = DCAP_REPORT_PATH; } return true; } /** * @description: show configurations */ void Config::show(void) { printf("Config : {\n"); printf(" 'base path' : '%s',\n", this->base_path.c_str()); printf(" 'db path' : '%s',\n", this->db_path.c_str()); printf(" 'data path' : [\n"); std::vector<std::string> d_paths = this->get_data_paths(); for (auto it = d_paths.begin(); it != d_paths.end(); ) { printf(" \"%s\"", (*it).c_str()); ++it == d_paths.end() ? printf("\n") : printf(",\n"); } printf(" ],\n"); printf(" 'base url' : '%s',\n", this->base_url.c_str()); printf(" 'ipfs url' : '%s',\n", this->ipfs_url.c_str()); printf(" 'chain config' : {\n"); printf(" 'base url' : %s,\n", this->chain_api_base_url.c_str()); printf(" 'address' : '%s',\n", this->chain_address.c_str()); printf(" 'account id' : '%s',\n", this->chain_account_id.c_str()); printf(" 'password' : 'xxxxxx',\n"); printf(" 'backup' : 'xxxxxx'\n"); printf(" },\n"); printf(" 'IAS parameters' : {\n"); //printf(" 'spid' : '%s',\n", IAS_SPID); //printf(" 'linkable' : '%s',\n", IAS_LINKABLE ? "true" : "false"); //printf(" 'random nonce' : '%s',\n", IAS_RANDOM_NONCE ? "true" : "false"); //printf(" 'primary subscription key' : '%s',\n", IAS_PRIMARY_SUBSCRIPTION_KEY); //printf(" 'secondary subscription key' : '%s',\n", IAS_SECONDARY_SUBSCRIPTION_KEY); printf(" 'base url' : '%s',\n", IAS_BASE_URL); printf(" 'report path' : '%s'\n", IAS_REPORT_PATH); //printf(" 'flags' : '%d'\n", IAS_FLAGS); printf(" 'DCAP config' : {\n"); printf(" 'base url' : %s,\n", this->dcap_base_url.c_str()); printf(" 'report path' : %s,\n", this->dcap_report_path.c_str()); printf(" },\n"); printf(" }\n"); printf("}\n"); } /** * @description: Get configure file path * @return: Configure file path */ std::string Config::get_config_path() { return config_file_path; } /** * @description: Unique data paths * @return: Has valid data path or not */ bool Config::unique_paths() { // Get system disk fsid struct statfs sys_st; if (statfs(this->base_path.c_str(), &sys_st) != -1) { this->sys_fsid = hexstring_safe(&sys_st.f_fsid, sizeof(sys_st.f_fsid)); } this->refresh_data_paths(); return 0 != this->data_paths.size(); } /** * @description: Sort data paths */ void Config::sort_data_paths() { this->data_paths_mutex.lock(); std::sort(this->data_paths.begin(), this->data_paths.end(), [](std::string s1, std::string s2) { if (s1.length() != s2.length()) { return s1.size() < s2.size(); } return s1.compare(s2) < 0; }); this->data_paths_mutex.unlock(); } /** * @description: Check if given path is in the system disk * @param path -> Const reference to given path * @return: System disk or not */ bool Config::is_valid_or_normal_disk(const std::string &path) { struct statfs st; if (statfs(path.c_str(), &st) == -1) { return false; } data_paths_mutex.lock(); size_t data_paths_size = this->data_paths.size(); data_paths_mutex.unlock(); std::string fsid = hexstring_safe(&st.f_fsid, sizeof(st.f_fsid)); return this->sys_fsid.compare(fsid) != 0 || data_paths_size == 1; } /** * @description: Refresh data paths */ void Config::refresh_data_paths() { this->org_data_paths_mutex.lock(); std::set<std::string> org_data_paths(this->org_data_paths.begin(), this->org_data_paths.end()); this->org_data_paths_mutex.unlock(); std::vector<std::string> data_paths; std::set<std::string> sids_s; std::string sys_disk_path; for (auto path : org_data_paths) { struct statfs st; if (statfs(path.c_str(), &st) != -1) { std::string fsid = hexstring_safe(&st.f_fsid, sizeof(st.f_fsid)); // Compare to check if current disk is system disk if (this->sys_fsid.compare(fsid) != 0) { // Remove duplicated disk if (sids_s.find(fsid) == sids_s.end()) { data_paths.push_back(path); sids_s.insert(fsid); } } else { if (sys_disk_path.size() == 0) { sys_disk_path = path; } } } } // If no valid data path and system disk is configured, choose sys disk if (data_paths.size() == 0 && sys_disk_path.size() != 0) { data_paths.push_back(sys_disk_path); } this->data_paths_mutex.lock(); this->data_paths = data_paths; this->data_paths_mutex.unlock(); // Sort data paths this->sort_data_paths(); } /** * @description: Get data paths * @return: Data paths */ std::vector<std::string> Config::get_data_paths() { SafeLock sl(this->data_paths_mutex); sl.lock(); return this->data_paths; } /** * @description: Check if given data path is valid * @param path -> Reference to given data path * @return: Valid or not */ bool Config::is_valid_data_path(const std::string &path) { std::map<std::string, std::string> sid_2_path; for (auto p : this->data_paths) { struct statfs st; if (statfs(p.c_str(), &st) != -1) { std::string fsid = hexstring_safe(&st.f_fsid, sizeof(st.f_fsid)); sid_2_path[fsid] = p; } } struct statfs st; if (statfs(path.c_str(), &st) != -1) { std::string fsid = hexstring_safe(&st.f_fsid, sizeof(st.f_fsid)); // Check if current disk is system disk if (this->sys_fsid.compare(fsid) == 0 ) { return false; } // Check if added path is duplicated if (sid_2_path.find(fsid) == sid_2_path.end()) { return true; } else { return false; } } return false; } /** * @description: Add data paths to config file * @param paths -> Const reference to paths * @return: Add success or not */ bool Config::config_file_add_data_paths(const json::JSON &paths) { crust_status_t crust_status = CRUST_SUCCESS; if (paths.JSONType() != json::JSON::Class::Array || paths.size() <= 0) { p_log->err("Add data path failed, Wrong paths parameter!\n"); return false; } else { uint8_t *p_data = NULL; size_t data_size = 0; if (CRUST_SUCCESS != (crust_status = get_file(config_file_path.c_str(), &p_data, &data_size))) { p_log->err("Add data path failed, read config file failed!\n"); return false; } else { json::JSON config_json = json::JSON::Load(&crust_status, p_data, data_size); if (CRUST_SUCCESS != crust_status) { p_log->err("Parse configure file json failed! Error code:%lx\n", crust_status); return false; } free(p_data); if (config_json["data_path"].JSONType() != json::JSON::Class::Array) { p_log->err("Add data path failed, invalid config file!\n"); return false; } SafeLock sl(this->data_paths_mutex); sl.lock(); std::set<std::string> paths_s(this->data_paths.begin(), this->data_paths.end()); std::vector<std::string> valid_paths; bool is_valid = false; for (auto path : paths.ArrayRange()) { std::string pstr = path.ToString(); if (this->is_valid_data_path(pstr)) { config_json["data_path"].append(path); if (paths_s.find(pstr) == paths_s.end()) { valid_paths.push_back(pstr); paths_s.insert(pstr); is_valid = true; } } } this->data_paths.insert(this->data_paths.end(), valid_paths.begin(), valid_paths.end()); sl.unlock(); // Insert valid paths to org data paths this->org_data_paths_mutex.lock(); this->org_data_paths.insert(this->org_data_paths.end(), valid_paths.begin(), valid_paths.end()); this->org_data_paths_mutex.unlock(); if (! is_valid) { return false; } this->sort_data_paths(); std::string config_str = config_json.dump(); replace(config_str, "\\\\", "\\"); crust_status = save_file(config_file_path.c_str(), reinterpret_cast<const uint8_t *>(config_str.c_str()), config_str.size()); if (CRUST_SUCCESS != crust_status) { p_log->err("Save new config file failed! Error code: %lx\n", crust_status); return false; } } } return true; }
14,115
C++
.cpp
420
26.583333
137
0.550502
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,342
Log.cpp
crustio_crust-sworker/src/app/log/Log.cpp
#include "Log.h" #include "DataBase.h" std::mutex log_mutex; namespace crust { Log *Log::log = NULL; /** * @description: single instance class function to get instance * @return: log instance */ Log *Log::get_instance() { if (Log::log == NULL) { log_mutex.lock(); if(Log::log == NULL) { Log::log = new Log(); } log_mutex.unlock(); } return Log::log; } /** * @description: constructor */ Log::Log() { this->debug_flag = false; } /** * @description: open debug mode * @param flag -> Show debug or not */ void Log::set_debug(bool flag) { this->debug_flag_mutex.lock(); this->debug_flag = flag; this->debug_flag_mutex.unlock(); } /** * @description: Restore debug flag */ void Log::restore_debug_flag() { this->debug_flag_mutex.lock(); bool flag = this->debug_flag; this->debug_flag_mutex.unlock(); if (!flag) { std::string s; DataBase *db = DataBase::get_instance(); if (CRUST_SUCCESS == db->get(DB_DEBUG, s)) { std::stringstream(s) >> flag; this->set_debug(flag); } } } /** * @description: print information * @param format -> data format */ void Log::info(const char *format, ...) { log_mutex.lock(); va_list va; va_start(va, format); int n = vsnprintf(this->log_buf, CRUST_LOG_BUF_SIZE, format, va); va_end(va); std::string log_str(this->log_buf, n); this->base_log(log_str, CRUST_LOG_INFO_TAG); log_mutex.unlock(); } /** * @description: print information * @param format -> data format */ void Log::warn(const char *format, ...) { log_mutex.lock(); va_list va; va_start(va, format); int n = vsnprintf(this->log_buf, CRUST_LOG_BUF_SIZE, format, va); va_end(va); std::string log_str(this->log_buf, n); this->base_log(log_str, CRUST_LOG_WARN_TAG); log_mutex.unlock(); } /** * @description: print information * @param format -> data format */ void Log::err(const char *format, ...) { log_mutex.lock(); va_list va; va_start(va, format); int n = vsnprintf(this->log_buf, CRUST_LOG_BUF_SIZE, format, va); va_end(va); std::string log_str(this->log_buf, n); this->base_log(log_str, CRUST_LOG_ERR_TAG); log_mutex.unlock(); } /** * @description: print information * @param format -> data format */ void Log::debug(const char *format, ...) { this->debug_flag_mutex.lock(); bool debug_flag = this->debug_flag; this->debug_flag_mutex.unlock(); if (debug_flag) { log_mutex.lock(); va_list va; va_start(va, format); int n = vsnprintf(this->log_buf, CRUST_LOG_BUF_SIZE, format, va); va_end(va); std::string log_str(this->log_buf, n); this->base_log(log_str, CRUST_LOG_DEBUG_TAG); log_mutex.unlock(); } } /** * @description: print base data * @param log_str -> data for logging * @param tag -> log tag */ void Log::base_log(std::string log_str, std::string tag) { // Get timestamp struct timeval cur_time; gettimeofday(&cur_time, NULL); int milli_sec = cur_time.tv_usec / 1000; char time_str[64]; // If you change this format, you may need to change the size of time_str if (strftime(time_str, 64, "%b %e %Y %T", localtime(&cur_time.tv_sec)) == 0) { time_str[0] = 0; } printf("[%s.%03d] [%s] %s", time_str, milli_sec, tag.c_str(), log_str.c_str()); fflush(stdout); } /** * @description: Return debug flag * @return: Debug flag */ bool Log::get_debug_flag() { return this->debug_flag; } } // namespace crust
3,665
C++
.cpp
154
19.727273
84
0.605278
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,535,343
ECalls.cpp
crustio_crust-sworker/src/app/ecalls/ECalls.cpp
#include "ECalls.h" EnclaveQueue *eq = EnclaveQueue::get_instance(); /** * @description: A wrapper function, seal one G srd files under directory, can be called from multiple threads * @param eid -> Enclave id * @param status (out) -> Pointer to restore result status * @param uuid (in) -> Pointer to disk uuid * @return: Invoking ecall return status */ sgx_status_t Ecall_srd_increase(sgx_enclave_id_t eid, crust_status_t *status, const char *uuid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_srd_increase(eid, status, uuid); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, decrease srd files under directory * @param eid -> Enclave id * @param size (out) -> Pointer to decreased srd size * @param change -> reduction * @return: Invoking ecall return status */ sgx_status_t Ecall_srd_decrease(sgx_enclave_id_t eid, size_t *size, size_t change) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_srd_decrease(eid, size, change); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, ecall main loop * @param eid -> Enclave id * @return: Invoking ecall return status */ sgx_status_t Ecall_main_loop(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_main_loop(eid); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, ecall stop all * @param eid -> Enclave id * @return: Invoking ecall return status */ sgx_status_t Ecall_stop_all(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_stop_all(eid); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, Restore enclave data from file * @param eid -> Enclave id * @param status (out) -> Pointer to restore result status * @return: Invoking ecall return status */ sgx_status_t Ecall_restore_metadata(sgx_enclave_id_t eid, crust_status_t *status) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_restore_metadata(eid, status); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, Compare chain account with enclave's * @param eid -> Enclave id * @param status (out) -> Pointer to compare result status * @param account_id (in) -> Pointer to account id * @param len -> account id length * @return: Invoking ecall return status */ sgx_status_t Ecall_cmp_chain_account_id(sgx_enclave_id_t eid, crust_status_t *status, const char *account_id, size_t len) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_cmp_chain_account_id(eid, status, account_id, len); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, Get signed validation report * @param eid -> Enclave id * @param status (out) -> Pointer to get result status * @param block_hash (in) -> block hash * @param block_height -> block height * @return: Invoking ecall return status */ sgx_status_t Ecall_gen_and_upload_work_report(sgx_enclave_id_t eid, crust_status_t *status, const char *block_hash, size_t block_height) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_and_upload_work_report(eid, status, block_hash, block_height); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, generate ecc key pair and store it in enclave * @param eid -> Enclave id * @param status (out) -> Pointer to result status * @param account_id (in) -> Pointer to account id * @param len -> Account id length * @return: Invoking ecall return status */ sgx_status_t Ecall_gen_key_pair(sgx_enclave_id_t eid, sgx_status_t *status, const char *account_id, size_t len) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_key_pair(eid, status, account_id, len); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, get sgx report, our generated public key contained * in report data * @param eid -> Enclave id * @param status (out) -> Pointer to result status * @param report (out) -> Pointer to SGX report * @param target_info (in) -> Data used to generate report * @return: Invoking ecall return status */ sgx_status_t Ecall_get_quote_report(sgx_enclave_id_t eid, sgx_status_t *status, sgx_report_t *report, sgx_target_info_t *target_info) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_get_quote_report(eid, status, report, target_info); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, generate current code measurement * @param eid -> Enclave id * @param status (out) -> Pointer to result status * @return: Invoking ecall return status */ sgx_status_t Ecall_gen_sgx_measurement(sgx_enclave_id_t eid, sgx_status_t *status) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_sgx_measurement(eid, status); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, verify IAS report * @param eid -> Enclave id * @param status (out) -> Pointer to verify result status * @param IASReport (in) -> Vector first address * @param len -> Count of Vector IASReport * @return: Invoking ecall return status */ sgx_status_t Ecall_gen_upload_epid_identity(sgx_enclave_id_t eid, crust_status_t *status, char **IASReport, size_t len) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_upload_epid_identity(eid, status, IASReport, len); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, Get ECDSA identity * @param eid -> Enclave id * @param status (out) -> Pointer to verify result status * @param p_quote (in) -> Pointer to quote buffer * @param quote_size -> Quote buffer size * @return: Invoking ecall return status */ sgx_status_t Ecall_gen_upload_ecdsa_quote(sgx_enclave_id_t eid, crust_status_t *status, uint8_t *p_quote, uint32_t quote_size) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_upload_ecdsa_quote(eid, status, p_quote, quote_size); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, Get ECDSA identity * @param eid -> Enclave id * @param status (out) -> Pointer to verify result status * @param report (in) -> Pointer to quote buffer * @param size -> Quote buffer size * @return: Invoking ecall return status */ sgx_status_t Ecall_gen_upload_ecdsa_identity(sgx_enclave_id_t eid, crust_status_t *status, const char *report, uint32_t size) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_upload_ecdsa_identity(eid, status, report, size); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, seal file start * @param eid -> Enclave id * @param status (out) -> Pointer to seal result status * @param cid (in) -> Pointer to file root cid * @param cid_b58 cid (in) -> root cid b58 format * @return: Invoking ecall return status */ sgx_status_t Ecall_seal_file_start(sgx_enclave_id_t eid, crust_status_t *status, const char *cid, const char *cid_b58) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_seal_file_start(eid, status, cid, cid_b58); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, Seal file according to given path and return new MerkleTree * @param eid -> Enclave id * @param status (out) -> Pointer to seal result status * @param cid (in) -> Ipfs content id * @param data (in) -> Pointer to raw data or link * @param data_size -> Raw data size or link size * @param is_link -> Indicate data is raw data or a link * @param path (in, out) -> Index path used to get file block * @param path_size -> Index path size * @return: Invoking ecall return status */ sgx_status_t Ecall_seal_file(sgx_enclave_id_t eid, crust_status_t *status, const char *cid, const uint8_t *data, size_t data_size, bool is_link, char *path, size_t path_size) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_seal_file(eid, status, cid, data, data_size, is_link, path, path_size); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, seal file end * @param eid -> Enclave id * @param status (out) -> Pointer to seal result status * @param cid (in) -> Pointer to file root cid * @return: Invoking ecall return status */ sgx_status_t Ecall_seal_file_end(sgx_enclave_id_t eid, crust_status_t *status, const char *cid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_seal_file_end(eid, status, cid); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: A wrapper function, Unseal file according to given path * @param eid -> Enclave id * @param status (out) -> Pointer to unseal result status * @param path (in) -> Pointer to file block stored path * @param p_decrypted_data -> Pointer to decrypted data buffer * @param decrypted_data_size -> Decrypted data buffer size * @param p_decrypted_data_size -> Pointer to decrypted data real size * @return: Invoking ecall return status */ sgx_status_t Ecall_unseal_file(sgx_enclave_id_t eid, crust_status_t *status, const char *path, uint8_t *p_decrypted_data, size_t decrypted_data_size, size_t *p_decrypted_data_size) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_unseal_file(eid, status, path, p_decrypted_data, decrypted_data_size, p_decrypted_data_size); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Change srd number * @param eid -> Enclave id * @param status (out) -> Pointer to result status * @param change -> Will be changed srd number * @param real_change (out) -> Pointer to real changed srd size * @return: Invoking ecall return status */ sgx_status_t Ecall_change_srd_task(sgx_enclave_id_t eid, crust_status_t *status, long change, long *real_change) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_change_srd_task(eid, status, change, real_change); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Update srd_g_hashs * @param eid -> Enclave id * @param data -> Pointer to deleted srd info * @param data_size -> Data size * @return: Invoking ecall return status */ sgx_status_t Ecall_srd_remove_space(sgx_enclave_id_t eid, const char *data, size_t data_size) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_srd_remove_space(eid, data, data_size); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Delete file * @param eid -> Enclave id * @param status (out) -> Pointer to delete result status * @param hash (in) -> File root hash * @return: Invoking ecall return status */ sgx_status_t Ecall_delete_file(sgx_enclave_id_t eid, crust_status_t *status, const char *hash) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_delete_file(eid, status, hash); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Generate upgrade metadata * @param eid -> Enclave id * @param status (out) -> Pointer to generate result status * @param block_height -> Chain block height * @return: Invoking ecall return status */ sgx_status_t Ecall_gen_upgrade_data(sgx_enclave_id_t eid, crust_status_t *status, size_t block_height) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_upgrade_data(eid, status, block_height); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Generate upgrade metadata * @param eid -> Enclave id * @param status (out) -> Pointer to result status * @param data (in) -> Pointer to metadata * @param data_size -> Meta length * @return: Invoking ecall return status */ sgx_status_t Ecall_restore_from_upgrade(sgx_enclave_id_t eid, crust_status_t *status, const uint8_t *data, size_t data_size) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_restore_from_upgrade(eid, status, data, data_size); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Enable upgrade * @param eid -> Enclave id * @param status (out) -> Pointer to result status * @param block_height -> Current block height * @return: Invoking ecall return status */ sgx_status_t Ecall_enable_upgrade(sgx_enclave_id_t eid, crust_status_t *status, size_t block_height) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_enable_upgrade(eid, status, block_height); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Validate meaningful files * @param eid -> Enclave id * @return: Invoking ecall return status */ sgx_status_t Ecall_validate_file(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_validate_file(eid); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Validate srd * @param eid -> Enclave id * @return: Invoking ecall return status */ sgx_status_t Ecall_validate_srd(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_validate_srd(eid); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Disable upgrade * @param eid -> Enclave id * @return: Invoking ecall return status */ sgx_status_t Ecall_disable_upgrade(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_disable_upgrade(eid); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Get enclave id information * @param eid -> Enclave id * @return: Invoking ecall return status */ sgx_status_t Ecall_id_get_info(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_id_get_info(eid); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Enable upgrade * @param eid -> Enclave id * @param status (out) -> Pointer to result status * @param data (in) -> Pointer to recover data * @param data_size -> Recover data size * @return: Invoking ecall return status */ sgx_status_t Ecall_recover_illegal_file(sgx_enclave_id_t eid, crust_status_t *status, const uint8_t *data, size_t data_size) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_recover_illegal_file(eid, status, data, data_size); eq->free_enclave(__FUNCTION__); return ret; } /** * @description: Safe store large data to enclave * @param eid -> Enclave id * @param status (out) -> Pointer to result status * @param t -> Ecall store function type * @param data (in) -> Pointer to data * @param total_size -> Total data size * @param partial_size -> Current store data size * @param offset -> Offset in total data * @param buffer_key -> Session key for this time enclave data store * @return: Invoking ecall return status */ sgx_status_t Ecall_safe_store2(sgx_enclave_id_t eid, crust_status_t *status, ecall_store_type_t t, const uint8_t *data, size_t total_size, size_t partial_size, size_t offset, uint32_t buffer_key) { sgx_status_t ret = SGX_SUCCESS; std::string func = eq->ecall_store2_func_m[t]; if (SGX_SUCCESS != (ret = eq->try_get_enclave(func.c_str()))) { return ret; } ret = ecall_safe_store2(eid, status, t, data, total_size, partial_size, offset, buffer_key); eq->free_enclave(func.c_str()); return ret; }
18,210
C++
.cpp
550
28.890909
180
0.652397
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,344
EnclaveQueue.cpp
crustio_crust-sworker/src/app/ecalls/EnclaveQueue.cpp
#include "EnclaveQueue.h" crust::Log *p_log = crust::Log::get_instance(); EnclaveQueue *EnclaveQueue::enclaveQueue = NULL; std::mutex enclaveQueue_mutex; /** * @description: Get EnclaveQueue instance * @return: Single EnclaveQueue instance */ EnclaveQueue *EnclaveQueue::get_instance() { if (EnclaveQueue::enclaveQueue == NULL) { enclaveQueue_mutex.lock(); if (EnclaveQueue::enclaveQueue == NULL) { EnclaveQueue::enclaveQueue = new EnclaveQueue(); } enclaveQueue_mutex.unlock(); } return EnclaveQueue::enclaveQueue; } /** * @description: Increase waiting queue * @param name -> Waiting task name */ void EnclaveQueue::increase_waiting_queue(std::string name) { waiting_task_um_mutex.lock(); int priority = task_priority_um[name]; waiting_task_um[priority].num++; waiting_task_um[priority].task_num_um[name]++; waiting_task_um_mutex.unlock(); } /** * @description: Decrease waiting queue * @param name -> Waiting task name */ void EnclaveQueue::decrease_waiting_queue(std::string name) { SafeLock sl(waiting_task_um_mutex); sl.lock(); int priority = task_priority_um[name]; if (waiting_task_um[priority].num == 0) { p_log->warn("Priority:%d task sum is 0.\n", priority); return; } waiting_task_um[priority].num--; waiting_task_um[priority].task_num_um[name]--; } /** * @description: Increase indicated ecall's running number * @param name -> Ecall's name */ void EnclaveQueue::increase_running_queue(std::string name) { running_ecalls_mutex.lock(); if (running_ecalls_um.count(name) == 0) { running_ecalls_um[name] = 0; } running_ecalls_um[name]++; running_ecalls_mutex.unlock(); } /** * @description: Decrease indicated ecall's running number * @param name -> Ecall's name */ void EnclaveQueue::decrease_running_queue(std::string name) { SafeLock sl(running_ecalls_mutex); sl.lock(); if (running_ecalls_um[name] == 0) { p_log->warn("Invoking ecall:%s num is 0.\n", name.c_str()); return; } running_ecalls_um[name]--; sl.unlock(); } /** * @description: Get running tasks total num * @return: Running tasks total num */ int EnclaveQueue::get_running_ecalls_sum() { running_ecalls_mutex.lock(); int res = running_task_num; running_ecalls_mutex.unlock(); return res; } /** * @description: Get running ecalls number * @param name -> Running ecall's name * @return: Running ecall's number */ int EnclaveQueue::get_running_ecalls_num(std::string name) { running_ecalls_mutex.lock(); int ans = running_ecalls_um[name]; running_ecalls_mutex.unlock(); return ans; } /** * @description: Get running tasks info * @return: Running tasks info */ std::string EnclaveQueue::get_running_ecalls_info() { running_ecalls_mutex.lock(); json::JSON info_json; for (auto item : running_ecalls_um) { if (item.second != 0) { info_json[item.first] = item.second; } } running_ecalls_mutex.unlock(); return info_json.dump(); } /** * @description: Get higher priority task number * @param name -> Current task name * @return: The higher task number */ int EnclaveQueue::get_higher_prio_waiting_task_num(std::string name) { waiting_task_um_mutex.lock(); int ret = 0; int priority = task_priority_um[name]; while (--priority >= 0) { ret += waiting_task_um[priority].num; for (auto tname : low_ignore_high_um[name]) { ret -= waiting_task_um[priority].task_num_um[tname]; } } waiting_task_um_mutex.unlock(); return ret; } /** * @description: Set task sleep by priority * @param priority -> Task priority */ void EnclaveQueue::task_sleep(int priority) { usleep(task_wait_time_v[priority]); } /** * @description: Try to get permission to enclave * @param name -> Pointer to invoke function name * @return: Get status */ sgx_status_t EnclaveQueue::try_get_enclave(const char *name) { std::string tname(name); std::thread::id tid = std::this_thread::get_id(); std::stringstream ss; ss << tid; std::string this_id = ss.str(); uint32_t timeout = 0; sgx_status_t sgx_status = SGX_SUCCESS; // Get current task priority int cur_task_prio = task_priority_um[tname]; // Increase corresponding waiting ecall increase_waiting_queue(tname); // ----- Task scheduling ----- // while (true) { // Check if current task's blocking task is running if (block_tasks_um.find(tname) != block_tasks_um.end()) { for (auto btask : block_tasks_um[tname]) { if (get_running_ecalls_num(btask) > 0) { goto loop; } } } // Following situations cannot get enclave resource: // 1. Current task number equal or larger than ENC_MAX_THREAD_NUM // 2. Current task priority lower than highest level and remaining resource less than ENC_RESERVED_THREAD_NUM // 3. There exists higher priority task waiting running_task_num_mutex.lock(); if (running_task_num >= ENC_MAX_THREAD_NUM || (cur_task_prio > ENC_HIGHEST_PRIORITY && ENC_MAX_THREAD_NUM - running_task_num <= ENC_RESERVED_THREAD_NUM) || get_higher_prio_waiting_task_num(tname) - ENC_PERMANENT_TASK_NUM > 0) { running_task_num_mutex.unlock(); goto loop; } running_task_num++; running_task_num_mutex.unlock(); // Add current task to running queue and quit increase_running_queue(tname); break; loop: // Check if current task is a tiemout task if (cur_task_prio > ENC_PRIO_TIMEOUT_THRESHOLD) { timeout++; if (timeout >= ENC_TASK_TIMEOUT) { //p_log->debug("task:%s(thread id:%s) needs to make way for other tasks.\n", name, this_id.c_str()); sgx_status = SGX_ERROR_SERVICE_TIMEOUT; break; } } task_sleep(cur_task_prio); } // Decrease corresponding waiting ecall decrease_waiting_queue(tname); return sgx_status; } /** * @description: Free enclave * @param name -> Pointer to invoke function name */ void EnclaveQueue::free_enclave(const char *name) { running_task_num_mutex.lock(); running_task_num--; running_task_num_mutex.unlock(); decrease_running_queue(name); } /** * @description: Get blocking upgrade ecalls' number * @return: Blocking ecalls' number */ int EnclaveQueue::get_upgrade_ecalls_num() { int block_task_num = 0; for (auto task : upgrade_blocked_task_us) { block_task_num += get_running_ecalls_num(task); } return block_task_num; } /** * @description: Is there stopping block task running * @return: Has or not */ bool EnclaveQueue::has_stopping_block_task() { SafeLock sl(running_ecalls_mutex); sl.lock(); for (auto task : this->stop_block_task_v) { if (running_ecalls_um[task] > 0) { return true; } } return false; }
7,289
C++
.cpp
258
23.077519
125
0.634571
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,345
DataBase.cpp
crustio_crust-sworker/src/app/database/DataBase.cpp
#include "DataBase.h" crust::Log *p_log = crust::Log::get_instance(); namespace crust { DataBase* DataBase::database = NULL; std::mutex database_mutex; /** * @description: Get single class instance * @return: The instance */ DataBase *DataBase::get_instance() { Config *p_config = Config::get_instance(); SafeLock sl(database_mutex); sl.lock(); if (database == NULL) { database = new DataBase(); bool init_success = false; Defer def([&init_success](void) { if (!init_success) { delete database; database = NULL; } }); leveldb::Options options; options.create_if_missing = true; if (CRUST_SUCCESS != create_directory(p_config->db_path)) { return NULL; } leveldb::Status s = leveldb::DB::Open(options, p_config->db_path.c_str(), &database->db); if (!s.ok()) { p_log->err("Initialize database failed!Database path:%s\n", p_config->db_path.c_str()); return NULL; } database->write_opt.sync = true; init_success = true; } return database; } /** * @description: Close leveldb */ DataBase::~DataBase() { if (this->db != NULL) delete this->db; } /** * @description: Add key value pair to db * @param key -> key * @param value -> value * @return: Add status */ crust_status_t DataBase::add(std::string key, std::string value) { std::string old_val; leveldb::Status s = this->db->Get(leveldb::ReadOptions(), key, &old_val); if (old_val.compare("") != 0) { value.append(";").append(old_val); } s = this->db->Put(this->write_opt, key, value); if (!s.ok()) { p_log->err("Insert record to DB failed!Error: %s\n", s.ToString().c_str()); return CRUST_PERSIST_ADD_FAILED; } return CRUST_SUCCESS; } /** * @description: Delete key value pair * @param key -> key * @return: Delete status */ crust_status_t DataBase::del(std::string key) { leveldb::WriteBatch batch; batch.Delete(key); leveldb::Status s = this->db->Write(this->write_opt, &batch); if (!s.ok()) { p_log->err("Delete record from DB failed!Error: %s\n", s.ToString().c_str()); return CRUST_PERSIST_DEL_FAILED; } return CRUST_SUCCESS; } /** * @description: Update key value pair * @param key -> key * @param value -> value * @return: Update status */ crust_status_t DataBase::set(std::string key, std::string value) { leveldb::Status s = this->db->Put(this->write_opt, key, value); if (!s.ok()) { p_log->err("Update record from DB failed!Error: %s\n", s.ToString().c_str()); return CRUST_PERSIST_SET_FAILED; } return CRUST_SUCCESS; } /** * @description: Get value by key * @param key -> key * @param value -> Reference to value * @return: Get status */ crust_status_t DataBase::get(std::string key, std::string &value) { leveldb::Status s = this->db->Get(leveldb::ReadOptions(), key, &value); if (!s.ok()) { //p_log->debug("Get record from DB failed!Error: %s\n", s.ToString().c_str()); return CRUST_PERSIST_GET_FAILED; } return CRUST_SUCCESS; } } // namespace crust
3,293
C++
.cpp
123
21.837398
99
0.60019
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,346
StoreOCalls.cpp
crustio_crust-sworker/src/app/ocalls/StoreOCalls.cpp
#include "StoreOCalls.h" crust::Log *p_log = crust::Log::get_instance(); /** * @description: ocall for creating directory * @param path (in) -> the path of directory * @param type -> Storage type * @return: Creating status */ crust_status_t ocall_create_dir(const char *path, store_type_t type) { std::string r_path = get_real_path_by_type(path, type); return create_directory(r_path); } /** * @description: ocall for renaming directory * @param old_path (in) -> the old path of directory * @param new_path (in) -> the new path of directory * @param type -> File storage type * @return: Renaming result status */ crust_status_t ocall_rename_dir(const char *old_path, const char *new_path, store_type_t type) { std::string r_old_path = get_real_path_by_type(old_path, type); std::string r_new_path = get_real_path_by_type(new_path, type); return rename_dir(r_old_path, r_new_path); } /** * @description: ocall for saving data into file * @param path (in) -> file path for saving * @param data (in) -> data for saving * @param data_size -> the length of data * @param type -> Storage type * @return: Saving result status */ crust_status_t ocall_save_file(const char *path, const uint8_t *data, size_t data_size, store_type_t type) { std::string r_path = get_real_path_by_type(path, type); return save_file(r_path.c_str(), data, data_size); } /** * @description: Delete folder or file * @param path (in) -> To be deleted path * @param type -> Storage type * @return: Saving result status */ crust_status_t ocall_delete_folder_or_file(const char *path, store_type_t type) { std::string r_path = get_real_path_by_type(path, type); if (access(r_path.c_str(), 0) != -1 && rm(r_path.c_str()) == -1) { p_log->err("Delete '%s' error!\n", r_path.c_str()); return CRUST_DELETE_FILE_FAILED; } return CRUST_SUCCESS; } /** * @description: ocall for getting file (ps: can't used by multithreading) * @param path (in) -> the path of file * @param p_file (out) -> Pointer to pointer file data * @param len (out) -> the length of data * @param type -> Storage type * @return file data */ crust_status_t ocall_get_file(const char *path, unsigned char **p_file, size_t *len, store_type_t type) { std::string r_path = get_real_path_by_type(path, type); return get_file(r_path.c_str(), p_file, len); } /** * @description: Set srd information * @param data (in) -> Pointer to srd info data * @param data_size -> Srd info data size */ void ocall_set_srd_info(const uint8_t *data, size_t data_size) { EnclaveData::get_instance()->set_srd_info(data, data_size); }
2,660
C++
.cpp
77
31.948052
106
0.677821
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,347
PersistOCalls.cpp
crustio_crust-sworker/src/app/ocalls/PersistOCalls.cpp
# include "PersistOCalls.h" crust::Log *p_log = crust::Log::get_instance(); /** * @description: Add record to DB * @param key (in) -> Pointer to key * @param value (in) -> Pointer to value * @param value_len -> value length * @return: Add status */ crust_status_t ocall_persist_add(const char *key, const uint8_t *value, size_t value_len) { return crust::DataBase::get_instance()->add(std::string(key), std::string((const char*)value, value_len)); } /** * @description: Delete record from DB * @param key (in) -> Pointer to key * @return: Delete status */ crust_status_t ocall_persist_del(const char *key) { return crust::DataBase::get_instance()->del(std::string(key)); } /** * @description: Update record in DB * @param key (in) -> Pointer to key * @param value (in) -> Pointer to value * @param value_len -> value length * @param total_size -> Data from enclave total size * @param total_buf (in) -> Pointer to total buffer * @param offset -> Data offset in total buffer * @return: Update status */ crust_status_t ocall_persist_set(const char *key, const uint8_t *value, size_t value_len, size_t total_size, uint8_t **total_buf, size_t offset) { std::string value_str; if (value_len < total_size) { if (*total_buf == NULL) { *total_buf = (uint8_t *)malloc(total_size); memset(*total_buf, 0, total_size); } memcpy(*total_buf + offset, value, value_len); if (offset + value_len < total_size) { return CRUST_SUCCESS; } value_str = std::string((const char *)(*total_buf), total_size); free(*total_buf); } else { value_str = std::string((const char *)value, value_len); } return crust::DataBase::get_instance()->set(std::string(key), value_str); } /** * @description: Get record from DB * @param key (in) -> Pointer to key * @param value (out) -> Pointer points to pointer to value * @param value_len (out) -> value length * @return: Get status */ crust_status_t ocall_persist_get(const char *key, uint8_t **value, size_t *value_len) { std::string val; crust_status_t crust_status = crust::DataBase::get_instance()->get(std::string(key), val); if (CRUST_SUCCESS != crust_status) { *value_len = 0; return crust_status; } *value_len = val.size(); *value = (uint8_t*)malloc(*value_len); memcpy(*value, val.c_str(), *value_len); return crust_status; }
2,499
C++
.cpp
78
27.794872
110
0.63361
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,348
IpfsOCalls.cpp
crustio_crust-sworker/src/app/ocalls/IpfsOCalls.cpp
#include "IpfsOCalls.h" crust::Log *p_log = crust::Log::get_instance(); /** * @description: Test if there is usable IPFS * @return: Test result */ bool ocall_ipfs_online() { return Ipfs::get_instance()->online(); } /** * @description: Get block from ipfs * @param cid (in) -> Ipfs content id * @param p_data (out) -> Pointer to pointer to ipfs data * @param data_size (out) -> Pointer to ipfs data size * @return: Status */ crust_status_t ocall_ipfs_get_block(const char *cid, uint8_t **p_data, size_t *data_size) { *data_size = Ipfs::get_instance()->block_get(cid, p_data); if (*data_size == 0) { if (!Ipfs::get_instance()->online()) { return CRUST_SERVICE_UNAVAILABLE; } return CRUST_STORAGE_IPFS_BLOCK_GET_ERROR; } return CRUST_SUCCESS; } /** * @description: Save IPFS file block * @param path (in) -> Pointer to block path * @param data (in) -> Pointer to block data * @param data_size -> Block data size * @param uuid (in) -> Buffer used to store uuid * @param uuid_len -> UUID length * @return: Save result */ crust_status_t ocall_save_ipfs_block(const char *path, const uint8_t *data, size_t data_size, char *uuid, size_t /*uuid_len*/) { json::JSON disk_json = get_disk_info(); std::string path_str(path); const int choose_len = 40; const int cid_len = path_str.find_last_of('/'); std::string cid(path, cid_len); if (disk_json.JSONType() != json::JSON::Class::Array || disk_json.size() <= 0 || path_str.length() <= choose_len) { return CRUST_UNEXPECTED_ERROR; } EnclaveData *ed = EnclaveData::get_instance(); // Choose a string of length 40 std::string for_choose = ""; if (cid_len > choose_len) { for_choose = path_str.substr(cid_len - choose_len, choose_len); } else { for_choose = path_str.substr(0, choose_len); } uint32_t start_index = 0; read_rand(reinterpret_cast<uint8_t *>(&start_index), sizeof(start_index)); start_index = start_index % FILE_DISK_LIMIT; uint32_t ci = start_index; // Current index // Choose disk for (size_t i = 0; i < choose_len/FILE_DISK_LIMIT;) { uint32_t ii = ci + i*FILE_DISK_LIMIT; uint32_t di = (for_choose[ii%choose_len] + for_choose[(ii+1)%choose_len] + for_choose[(ii+2)%choose_len] + for_choose[(ii+3)%choose_len]) % disk_json.size(); // Check if there is enough space size_t reserved = disk_json[di][WL_DISK_AVAILABLE].ToInt() * 1024 * 1024 * 1024; if (reserved > data_size * 4) { std::string disk_path = disk_json[di][WL_DISK_PATH].ToString(); std::string uuid_str = EnclaveData::get_instance()->get_uuid(disk_path); if (uuid_str.size() == UUID_LENGTH * 2) { memcpy(uuid, uuid_str.c_str(), uuid_str.size()); std::string tmp_path = uuid_str + path; std::string file_path = get_real_path_by_type(tmp_path.c_str(), STORE_TYPE_FILE); if (CRUST_SUCCESS == save_file_ex(file_path.c_str(), data, data_size, mode_t(0664), SF_CREATE_DIR)) { ed->add_pending_file_size(cid, data_size); return CRUST_SUCCESS; } } } ci = (ci + 1) % FILE_DISK_LIMIT; if (ci == start_index) { i++; } } return CRUST_STORAGE_NO_ENOUGH_SPACE; } /** * @description: Cat file * @param cid (in) -> Ipfs content id * @param p_data (out) -> Pointer to pointer to ipfs data * @param data_size (out) -> Pointer to ipfs data size * @return: Status */ crust_status_t ocall_ipfs_cat(const char *cid, uint8_t **p_data, size_t *data_size) { if (!Ipfs::get_instance()->online()) { return CRUST_SERVICE_UNAVAILABLE; } *data_size = Ipfs::get_instance()->cat(cid, p_data); if (*data_size == 0) { return CRUST_STORAGE_IPFS_CAT_ERROR; } return CRUST_SUCCESS; } /** * @description: Add file to ipfs * @param p_data (in) -> Pointer to be added data * @param len -> Added data length * @param cid (in) -> Pointer to returned ipfs content id * @param cid_len -> File content id length * @return: Status */ crust_status_t ocall_ipfs_add(uint8_t *p_data, size_t len, char *cid, size_t /*cid_len*/) { std::string cid_str = Ipfs::get_instance()->add(p_data, len); if (cid_str.size() == 0) { return CRUST_STORAGE_IPFS_ADD_ERROR; } memcpy(cid, cid_str.c_str(), cid_str.size()); return CRUST_SUCCESS; } /** * @description: Delete ipfs block file by cid * @param cid (in) -> File root cid * @return: Delete result */ crust_status_t ocall_delete_ipfs_file(const char *cid) { json::JSON disk_json = get_disk_info(); if (disk_json.JSONType() != json::JSON::Class::Array || disk_json.size() <= 0) { p_log->err("Cannot find disk information! Please check your disk!\n"); return CRUST_UNEXPECTED_ERROR; } for (int i = 0; i < disk_json.size(); i++) { std::string path = disk_json[i][WL_DISK_UUID].ToString() + cid; path = get_real_path_by_type(path.c_str(), STORE_TYPE_FILE); rm_dir(path); } return CRUST_SUCCESS; } /** * @description: Delete file * @param cid (in) -> To be deleted file cid * @return: Status */ crust_status_t ocall_ipfs_del(const char *cid) { if (!Ipfs::get_instance()->del(cid)) { p_log->warn("Invoke IPFS pin rm file(cid:%s) failed! Please check your IPFS.\n", cid); return CRUST_UNEXPECTED_ERROR; } return CRUST_SUCCESS; } /** * @description: Delete file's all related data * @param cid (in) -> To be deleted file cid * @return: Status */ crust_status_t ocall_ipfs_del_all(const char *cid) { // Delete ipfs file Ipfs::get_instance()->del(cid); // Delete file data ocall_delete_ipfs_file(cid); // Delete sealed tree crust::DataBase::get_instance()->del(cid); // Delete statistics information EnclaveData::get_instance()->del_file_info(cid); return CRUST_SUCCESS; }
6,160
C++
.cpp
186
27.827957
165
0.61113
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,349
OCalls.cpp
crustio_crust-sworker/src/app/ocalls/OCalls.cpp
#include "OCalls.h" crust::Log *p_log = crust::Log::get_instance(); std::map<uint32_t, uint8_t *> g_ocall_buffer_pool; std::mutex g_ocall_buffer_pool_mutex; std::map<ocall_store_type_t, ocall_store2_f> g_ocall_store2_func_m = { {OCALL_FILE_INFO_ALL, ocall_store_file_info_all}, {OCALL_STORE_WORKREPORT, ocall_store_workreport}, {OCALL_STORE_UPGRADE_DATA, ocall_store_upgrade_data}, }; // Used to store ocall file data uint8_t *ocall_file_data = NULL; size_t ocall_file_data_len = 0; // Used to validation websocket client WebsocketClient *wssclient = NULL; /** * @description: ocall for printing string * @param str (in) -> string for printing */ void ocall_print_info(const char *str) { printf("%s", str); } /** * @description: ocall for printing string * @param str (in) -> string for printing */ void ocall_print_debug(const char *str) { if (p_log->get_debug_flag()) { printf("%s", str); } } /** * @description: ocall for log information * @param str (in) -> string for printing */ void ocall_log_info(const char *str) { p_log->info("[Enclave] %s", str); } /** * @description: ocall for log warnings * @param str (in) -> string for printing */ void ocall_log_warn(const char *str) { p_log->warn("[Enclave] %s", str); } /** * @description: ocall for log errors * @param str (in) -> string for printing */ void ocall_log_err(const char *str) { p_log->err("[Enclave] %s", str); } /** * @description: ocall for log debugs * @param str (in) -> string for printing */ void ocall_log_debug(const char *str) { p_log->debug("[Enclave] %s", str); } /** * @description: ocall for wait * @param u -> microsecond */ void ocall_usleep(int u) { usleep(u); } /** * @description: Free app buffer * @param value (in) -> Pointer points to pointer to value * @return: Get status */ crust_status_t ocall_free_outer_buffer(uint8_t **value) { if(*value != NULL) { free(*value); *value = NULL; } return CRUST_SUCCESS; } /** * @description: Get block hash by height * @param block_height -> Block height from enclave * @param block_hash (in) -> Pointer to got block hash * @param hash_size -> Block hash size * @return: Get result */ crust_status_t ocall_get_block_hash(size_t block_height, char *block_hash, size_t hash_size) { std::string hash = crust::Chain::get_instance()->get_block_hash(block_height); if (hash.compare("") == 0) { return CRUST_UPGRADE_GET_BLOCK_HASH_FAILED; } memcpy(block_hash, hash.c_str(), hash_size); return CRUST_SUCCESS; } /** * @description: For upgrade, send work report * @return: Send result */ crust_status_t ocall_upload_workreport() { std::string work_str = EnclaveData::get_instance()->get_workreport(); remove_char(work_str, '\\'); remove_char(work_str, '\n'); remove_char(work_str, ' '); p_log->info("Sending work report:%s\n", work_str.c_str()); if (!crust::Chain::get_instance()->post_sworker_work_report(work_str)) { p_log->err("Send work report to crust chain failed!\n"); return CRUST_UPGRADE_SEND_WORKREPORT_FAILED; } p_log->info("Send work report to crust chain successfully!\n"); return CRUST_SUCCESS; } /** * @description: Entry network * @return: Entry result */ crust_status_t ocall_entry_network() { return entry_network(); } /** * @description: Do srd in this function * @param change -> The change number will be committed this turn * @return: Srd change return status */ crust_status_t ocall_srd_change(long change) { return srd_change(change); } /** * @description: Store sworker identity * @param id (in) -> Pointer to identity * @return: Upload result */ crust_status_t ocall_upload_epid_identity(const char *id) { crust_status_t crust_status = CRUST_SUCCESS; json::JSON entrance_info = json::JSON::Load(&crust_status, std::string(id)); if (CRUST_SUCCESS != crust_status) { p_log->err("Parse identity failed! Error code:%lx\n", crust_status); return crust_status; } entrance_info["account_id"] = Config::get_instance()->chain_address; std::string sworker_identity = entrance_info.dump(); p_log->info("Generate identity successfully! Sworker identity: %s\n", sworker_identity.c_str()); // Send identity to crust chain if (!crust::Chain::get_instance()->wait_for_running()) { return CRUST_UNEXPECTED_ERROR; } if (!crust::Chain::get_instance()->post_epid_identity(sworker_identity)) { p_log->err("Send identity to crust chain failed!\n"); return CRUST_UNEXPECTED_ERROR; } p_log->info("Send identity to crust chain successfully!\n"); return CRUST_SUCCESS; } /** * @description: Store sworker identity * @param id (in) -> Pointer to identity * @return: Upload result */ crust_status_t ocall_upload_ecdsa_quote(const char *id) { crust_status_t crust_status = CRUST_SUCCESS; // Send identity to registry chain if (!crust::Chain::get_instance()->wait_for_running()) { return CRUST_UNEXPECTED_ERROR; } crust::Chain *chain = crust::Chain::get_instance(); if (!chain->post_ecdsa_quote(std::string(id))) { p_log->err("DCAP quote upload failed!\n"); return CRUST_UNEXPECTED_ERROR; } p_log->info("DCAP quote upload success!\n"); return crust_status; } /** * @description: Upload sworker identity to crust chain * @param id (in) -> Pointer to identity * @return: Upload result */ crust_status_t ocall_upload_ecdsa_identity(const char *id) { if (!crust::Chain::get_instance()->post_ecdsa_identity(std::string(id))) { p_log->err("Upload sworker identity to crust chain failed!\n"); return CRUST_UNEXPECTED_ERROR; } return CRUST_SUCCESS; } /** * @description: Store enclave id information * @param info (in) -> Pointer to enclave id information */ void ocall_store_enclave_id_info(const char *info) { EnclaveData::get_instance()->set_enclave_id_info(info); } /** * @description: Store upgrade data * @param data (in) -> Upgrade data * @param data_size -> Upgrade data size * @return: Store status */ crust_status_t ocall_store_upgrade_data(const uint8_t *data, size_t data_size) { EnclaveData::get_instance()->set_upgrade_data(std::string(reinterpret_cast<const char *>(data), data_size)); return CRUST_SUCCESS; } /** * @description: Get chain block information * @param data (in, out) -> Pointer to file block information * @param data_size -> Pointer to file block data size * @param real_size (out) -> Pointer to real file size * @return: Get result */ crust_status_t ocall_chain_get_block_info(uint8_t *data, size_t data_size, size_t *real_size) { crust::BlockHeader block_header; if (!crust::Chain::get_instance()->get_block_header(block_header)) { return CRUST_UNEXPECTED_ERROR; } json::JSON bh_json; bh_json[CHAIN_BLOCK_NUMBER] = block_header.number; bh_json[CHAIN_BLOCK_HASH] = block_header.hash; std::string bh_str = bh_json.dump(); remove_char(bh_str, '\n'); remove_char(bh_str, '\\'); remove_char(bh_str, ' '); *real_size = bh_str.size(); if (*real_size > data_size) { return CRUST_OCALL_NO_ENOUGH_BUFFER; } memcpy(data, bh_str.c_str(), bh_str.size()); return CRUST_SUCCESS; } /** * @description: Store file information * @param cid (in) -> File content identity * @param data (in) -> File information data * @param type (in) -> File information type */ void ocall_store_file_info(const char* cid, const char *data, const char *type) { EnclaveData::get_instance()->add_file_info(cid, type, data); } /** * @description: Restore sealed file information * @param data (in) -> All file information * @param data_size -> All file information size * @return: Store status */ crust_status_t ocall_store_file_info_all(const uint8_t *data, size_t data_size) { EnclaveData::get_instance()->restore_file_info(data, data_size); return CRUST_SUCCESS; } /** * @description: Store workreport * @param data (in) -> Pointer to workreport data * @param data_size -> Workreport data size * @return: Store status */ crust_status_t ocall_store_workreport(const uint8_t *data, size_t data_size) { EnclaveData::get_instance()->set_workreport(data, data_size); return CRUST_SUCCESS; } /** * @description: Ocall save big data * @param t -> Store function type * @param data (in) -> Pointer to data * @param total_size -> Total data size * @param partial_size -> Current store data size * @param offset -> Offset in total data * @param buffer_key -> Session key for this time enclave data store * @return: Store result */ crust_status_t ocall_safe_store2(ocall_store_type_t t, const uint8_t *data, size_t total_size, size_t partial_size, size_t offset, uint32_t buffer_key) { SafeLock sl(g_ocall_buffer_pool_mutex); sl.lock(); crust_status_t crust_status = CRUST_SUCCESS; bool is_end = true; if (offset < total_size) { uint8_t *buffer = NULL; if (g_ocall_buffer_pool.find(buffer_key) != g_ocall_buffer_pool.end()) { buffer = g_ocall_buffer_pool[buffer_key]; } if (buffer == NULL) { buffer = (uint8_t *)malloc(total_size); if (buffer == NULL) { crust_status = CRUST_MALLOC_FAILED; goto cleanup; } memset(buffer, 0, total_size); g_ocall_buffer_pool[buffer_key] = buffer; } memcpy(buffer + offset, data, partial_size); if (offset + partial_size < total_size) { is_end = false; } } if (!is_end) { return CRUST_SUCCESS; } crust_status = (g_ocall_store2_func_m[t])(g_ocall_buffer_pool[buffer_key], total_size); cleanup: if (g_ocall_buffer_pool.find(buffer_key) != g_ocall_buffer_pool.end()) { free(g_ocall_buffer_pool[buffer_key]); g_ocall_buffer_pool.erase(buffer_key); } return crust_status; } /** * @description: Recall validate meaningful files */ void ocall_recall_validate_file() { Validator::get_instance()->validate_file(); } /** * @description: Recall validate srd */ void ocall_recall_validate_srd() { Validator::get_instance()->validate_srd(); } /** * @description: Change sealed file info from old type to new type * @param cid (in) -> File root cid * @param old_type (in) -> Old file type * @param new_type (in) -> New file type */ void ocall_change_file_type(const char *cid, const char *old_type, const char *new_type) { EnclaveData::get_instance()->change_file_type(cid, old_type, new_type); } /** * @description: Delete cid by type * @param cid (in) -> File root cid * @param type (in) -> File type */ void ocall_delete_file_info(const char *cid, const char *type) { EnclaveData::get_instance()->del_file_info(cid, type); }
11,026
C++
.cpp
372
25.981183
151
0.663583
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,350
MainTest.h
crustio_crust-sworker/test/unit/MainTest.h
#ifndef _CRUST_MAIN_TEST_H_ #define _CRUST_MAIN_TEST_H_ #include <stdlib.h> #include <stdio.h> #include <string> #include <sgx_urts.h> #include <sgx_error.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include "Enclave_u.h" #define ENCLAVE_TEST_FILE_PATH "src/enclave.signed.so" #if defined(__cplusplus) extern "C" { #endif int test_enclave(); #if defined(__cplusplus) } #endif #endif /* !_CRUST_MAIN_TEST_H_ */
461
C++
.h
21
20.666667
56
0.725806
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,351
EncalveTestEntrance.h
crustio_crust-sworker/test/unit/enclave/EncalveTestEntrance.h
#ifndef _CRUST_ENLCAVE_TEST_ENTRANCE_H_ #define _CRUST_ENLCAVE_TEST_ENTRANCE_H_ #include "UtilsTest.h" #include "StorageTest.h" #if defined(__cplusplus) extern "C" { #endif bool test_enclave_unit(); #if defined(__cplusplus) } #endif #endif /* !_CRUST_ENLCAVE_TEST_ENTRANCE_H_ */
284
C++
.h
13
20.461538
45
0.75188
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,352
UtilsTest.h
crustio_crust-sworker/test/unit/enclave/utilsTest/UtilsTest.h
#ifndef _CRUST_UTILS_TEST_H_ #define _CRUST_UTILS_TEST_H_ #include "EUtils.h" #include "stdbool.h" #if defined(__cplusplus) extern "C" { #endif bool test_char_to_int(); bool test_hexstring(); bool test_hexstring_safe(); bool test_hex_string_to_bytes(); bool test_seal_data_mrenclave(); bool test_remove_char(); bool test_base58_encode(); bool test_hash_to_cid(); #if defined(__cplusplus) } #endif #endif /* !_CRUST_UTILS_TEST_H_ */
438
C++
.h
20
20.6
34
0.735437
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,353
StorageTest.h
crustio_crust-sworker/test/unit/enclave/storageTest/StorageTest.h
#ifndef _CRUST_STORAGE_TEST_H_ #define _CRUST_STORAGE_TEST_H_ #include "Storage.h" #include "stdbool.h" #if defined(__cplusplus) extern "C" { #endif bool test_get_hashs_from_block(); #if defined(__cplusplus) } #endif #endif /* !_CRUST_STORAGE_TEST_H_ */
260
C++
.h
13
18.538462
36
0.73029
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,354
SrdTest.h
crustio_crust-sworker/test/src/enclave/srd/SrdTest.h
#ifndef _CRUST_SRD_TEST_H_ #define _CRUST_SRD_TEST_H_ #include <vector> #include <string> #include <unordered_map> #include <unordered_set> #include <algorithm> #include "sgx_trts.h" #include "sgx_thread.h" #include "Workload.h" #include "EUtils.h" #include "PathHelper.h" #include "SafeLock.h" #include "Parameter.h" void srd_change_test(long change, bool real); size_t srd_decrease_test(size_t change); crust_status_t srd_increase_test(const char *uuid); #endif /* !_CRUST_SRD_TEST_H_ */
495
C++
.h
18
26.222222
51
0.752119
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,355
WorkloadTest.h
crustio_crust-sworker/test/src/enclave/workload/WorkloadTest.h
#ifndef _CRUST_WORKLOAD_TEST_H_ #define _CRUST_WORKLOAD_TEST_H_ #include <utility> #include <vector> #include <list> #include <string> #include <map> #include <unordered_map> #include <set> #include "sgx_trts.h" #include "sgx_thread.h" #include "EUtils.h" #include "Enclave_t.h" #include "Persistence.h" #include "Identity.h" #include "Srd.h" #include "Parameter.h" class WorkloadTest { public: void test_add_file(long file_num); void test_delete_file(uint32_t file_num); void test_delete_file_unsafe(uint32_t file_num); static WorkloadTest *workloadTest; static WorkloadTest *get_instance(); private: WorkloadTest() {} }; #endif /* !_CRUST_WORKLOAD_TEST_H_ */
691
C++
.h
29
21.793103
52
0.73628
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,356
ValidatorTest.h
crustio_crust-sworker/test/src/enclave/validator/ValidatorTest.h
#ifndef _CRUST_VALIDATOR_TEST_H_ #define _CRUST_VALIDATOR_TEST_H_ #include <vector> #include <unordered_set> #include <unordered_map> #include <set> #include "sgx_thread.h" #include "sgx_trts.h" #include "MerkleTree.h" #include "Workload.h" #include "PathHelper.h" #include "Persistence.h" #include "EUtils.h" #include "Parameter.h" #include "SafeLock.h" #include "Storage.h" void validate_meaningful_file_bench(); void validate_meaningful_file_bench_real(); void validate_srd_bench(); void validate_srd_bench_real(); #endif /* !_CRUST_VALIDATOR_TEST_H_ */
562
C++
.h
21
25.52381
43
0.764925
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,357
IdentityTest.h
crustio_crust-sworker/test/src/enclave/identity/IdentityTest.h
#ifndef _CRUST_IDENTITY_TEST_H_ #define _CRUST_IDENTITY_TEST_H_ #include <string> #include <map> #include <set> #include <vector> #include <sgx_utils.h> #include <sgx_tkey_exchange.h> #include <sgx_tcrypto.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include <sgx_ecp_types.h> #include <sgx_report.h> #include "sgx_spinlock.h" #include "sgx_thread.h" #include "Enclave_t.h" #include "IASReport.h" #include "tSgxSSL_api.h" #include "EUtils.h" #include "Persistence.h" #include "ReportTest.h" #include "Parameter.h" using namespace std; crust_status_t id_gen_upgrade_data_test(size_t block_height); #endif
652
C++
.h
26
23.884615
61
0.758454
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,358
ReportTest.h
crustio_crust-sworker/test/src/enclave/report/ReportTest.h
#ifndef _CRUST_REPORT_TEST_H_ #define _CRUST_REPORT_TEST_H_ #include <string> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/cmac.h> #include <openssl/conf.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #include "Workload.h" #include "Report.h" #include "EUtils.h" crust_status_t gen_and_upload_work_report_test(const char *block_hash, size_t block_height, long wait_time, bool is_upgrading, bool locked =true); #endif /* !_CRUST_REPORT_TEST_H_ */
558
C++
.h
17
31.588235
146
0.750466
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,359
AppTest.h
crustio_crust-sworker/test/src/app/AppTest.h
#ifndef _CRUST_APP_TEST_H_ #define _CRUST_APP_TEST_H_ #include <sgx_key_exchange.h> #include <sgx_report.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include <sgx_urts.h> #include <stdlib.h> #include <stdio.h> #include <limits.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <unistd.h> #include "Config.h" #include "ProcessTest.h" #include "Log.h" #include "Srd.h" #include "Resource.h" int main_daemon(void); #endif /* !_CRUST_APP_TEST_H_ */
517
C++
.h
22
22.318182
32
0.725051
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,360
ApiHandlerTest.h
crustio_crust-sworker/test/src/app/http/ApiHandlerTest.h
#ifndef _CRUST_API_HANDLER_TEST_H_ #define _CRUST_API_HANDLER_TEST_H_ #include <stdio.h> #include <algorithm> #include <mutex> #include <set> #include <exception> #include <algorithm> #include <cstdlib> #include <functional> #include <iostream> #include <memory> #include <string> #include <thread> #include <vector> #include <sgx_report.h> #include <sgx_key_exchange.h> #include <sgx_error.h> #include "sgx_eid.h" #include "sgx_tcrypto.h" #include "Common.h" #include "Config.h" #include "FormatUtils.h" #include "IASReport.h" #include "SgxSupport.h" #include "Resource.h" #include "HttpClient.h" #include "FileUtils.h" #include "Log.h" #include "sgx_tseal.h" #include "Config.h" #include "Common.h" #include "DataBase.h" #include "Srd.h" #include "SrdTest.h" #include "AsyncTest.h" #include "EnclaveData.h" #include "EnclaveDataTest.h" #include "Chain.h" json::JSON http_handler_test(UrlEndPoint urlendpoint, json::JSON req); #endif /* !_CRUST_API_HANDLER_TEST_H_ */
974
C++
.h
41
22.634146
70
0.757543
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,361
ProcessTest.h
crustio_crust-sworker/test/src/app/process/ProcessTest.h
#ifndef _CRUST_PROCESS_TEST_H_ #define _CRUST_PROCESS_TEST_H_ #include <stdlib.h> #include <stdio.h> #include <limits.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <unistd.h> #include <algorithm> #include <mutex> #include <map> #include <fstream> #include <sgx_key_exchange.h> #include <sgx_report.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include <sgx_error.h> #include <sgx_eid.h> #include <sgx_urts.h> #include <sgx_capable.h> #include "SgxSupport.h" #include "ECalls.h" #include "ECallsTest.h" #include "Config.h" #include "FormatUtils.h" #include "Common.h" #include "Resource.h" #include "FileUtils.h" #include "Log.h" #include "WorkReport.h" #include "Srd.h" #include "Process.h" typedef void (*task_func_t)(void); int process_run_test(); #endif /* !_CRUST_PROCESS_TEST_H_ */
864
C++
.h
37
22.189189
36
0.738124
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,362
ValidateTest.h
crustio_crust-sworker/test/src/app/process/ValidateTest.h
#ifndef _APP_VALIDATE_TEST_H_ #define _APP_VALIDATE_TEST_H_ #include <vector> #include "Config.h" #include "Ctpl.h" #if defined(__cplusplus) extern "C" { #endif void validate_file_test(); void validate_srd_test(); #if defined(__cplusplus) } #endif #endif /* ! _APP_VALIDATE_TEST_H_ */
291
C++
.h
15
18
36
0.725926
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,363
AsyncTest.h
crustio_crust-sworker/test/src/app/process/AsyncTest.h
#ifndef _APP_ASYNC_TEST_H_ #define _APP_ASYNC_TEST_H_ #include <string> #include <future> #include "Log.h" #include "Chain.h" #if defined(__cplusplus) extern "C" { #endif void report_add_callback(); #if defined(__cplusplus) } #endif #endif /* !_APP_ASYNC_TEST_H_ */
272
C++
.h
15
16.733333
32
0.717131
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,364
SrdTest.h
crustio_crust-sworker/test/src/app/process/SrdTest.h
#ifndef _APP_SRD_TEST_H_ #define _APP_SRD_TEST_H_ #include <sys/types.h> #include <sys/stat.h> #include <sys/vfs.h> #include <string> #include <vector> #include <unordered_set> #include "Config.h" #include "FileUtils.h" #include "FormatUtils.h" #include "DataBase.h" #include "Log.h" #include "EnclaveData.h" #if defined(__cplusplus) extern "C" { #endif bool srd_change_test(long change); #if defined(__cplusplus) } #endif #endif /* !_APP_SRD_TEST_H_*/
459
C++
.h
23
18.695652
34
0.734884
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,365
EnclaveDataTest.h
crustio_crust-sworker/test/src/app/process/EnclaveDataTest.h
#ifndef _APP_ENCLAVE_DATA_TEST_H_ #define _APP_ENCLAVE_DATA_TEST_H_ #include <stdio.h> #include <string> #include "EnclaveData.h" class EnclaveDataTest { public: static EnclaveDataTest *enclavedataTest; static EnclaveDataTest *get_instance(); void set_file_info(std::string file_info); std::string get_file_info(); std::string g_file_info = ""; std::string enclave_workreport = ""; private: EnclaveDataTest() {} }; #endif /* !_APP_ENCLAVE_DATA_TEST_H_ */
489
C++
.h
18
24.277778
46
0.711828
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,366
ECallsTest.h
crustio_crust-sworker/test/src/app/ecalls/ECallsTest.h
#ifndef _ECALLS_TEST_H_ #define _ECALLS_TEST_H_ #include "EnclaveQueue.h" #if defined(__cplusplus) extern "C" { #endif sgx_status_t Ecall_add_validate_proof(sgx_enclave_id_t eid); sgx_status_t Ecall_validate_srd_test(sgx_enclave_id_t eid); sgx_status_t Ecall_validate_srd_bench(sgx_enclave_id_t eid); sgx_status_t Ecall_validate_file_test(sgx_enclave_id_t eid); sgx_status_t Ecall_validate_file_bench(sgx_enclave_id_t eid); sgx_status_t Ecall_store_metadata(sgx_enclave_id_t eid); sgx_status_t Ecall_srd_increase_test(sgx_enclave_id_t eid, crust_status_t *status, const char *uuid); sgx_status_t Ecall_srd_decrease_test(sgx_enclave_id_t eid, size_t *size, size_t change); sgx_status_t Ecall_handle_report_result(sgx_enclave_id_t eid); sgx_status_t Ecall_test_add_file(sgx_enclave_id_t eid, long file_num); sgx_status_t Ecall_test_delete_file(sgx_enclave_id_t eid, uint32_t file_num); sgx_status_t Ecall_test_delete_file_unsafe(sgx_enclave_id_t eid, uint32_t file_num); sgx_status_t Ecall_clean_file(sgx_enclave_id_t eid); sgx_status_t Ecall_get_file_info(sgx_enclave_id_t eid, crust_status_t *status, const char *data); sgx_status_t Ecall_gen_upgrade_data_test(sgx_enclave_id_t eid, crust_status_t *status, size_t block_height); sgx_status_t Ecall_gen_and_upload_work_report_test(sgx_enclave_id_t eid, crust_status_t *status, const char *block_hash, size_t block_height); sgx_status_t Ecall_srd_change_test(sgx_enclave_id_t eid, long change, bool real); sgx_status_t Ecall_validate_file_bench_real(sgx_enclave_id_t eid); sgx_status_t Ecall_validate_srd_bench_real(sgx_enclave_id_t eid); #if defined(__cplusplus) } #endif #endif /* !_ECALLS_TEST_H_ */
1,656
C++
.h
30
54.033333
142
0.765577
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,367
OCallsTest.h
crustio_crust-sworker/test/src/app/ocalls/OCallsTest.h
#ifndef _CRUST_OCALLS_TEST_H_ #define _CRUST_OCALLS_TEST_H_ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <boost/algorithm/string.hpp> #include <exception> #include "CrustStatus.h" #include "FileUtils.h" #include "FormatUtils.h" #include "Config.h" #include "Common.h" #include "Log.h" #include "EnclaveData.h" #include "WebsocketClient.h" #include "Srd.h" #include "SrdTest.h" #include "DataBase.h" #include "Chain.h" #include "EntryNetwork.h" #include "Chain.h" #include "EnclaveDataTest.h" #include "ValidateTest.h" #if defined(__cplusplus) extern "C" { #endif void ocall_store_file_info_test(const char *info); crust_status_t ocall_get_file_bench(const char *file_path, unsigned char **p_file, size_t *len); crust_status_t ocall_get_file_block(const char *file_path, unsigned char **p_file, size_t *len); crust_status_t ocall_srd_change_test(long change); void ocall_recall_validate_file_bench(); void ocall_recall_validate_srd_bench(); #if defined(__cplusplus) } #endif #endif /* !_CRUST_OCALLS_TEST_H_ */
1,175
C++
.h
44
25.568182
96
0.759111
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,368
Enclave.h
crustio_crust-sworker/src/enclave/Enclave.h
#ifndef _CRUST_ENCLAVE_H_ #define _CRUST_ENCLAVE_H_ #include <string> #include <vector> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/cmac.h> #include <openssl/conf.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #include <sgx_utils.h> #include <sgx_tkey_exchange.h> #include <sgx_tcrypto.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include <sgx_ecp_types.h> #include "sgx_spinlock.h" #include "tSgxSSL_api.h" #include "Enclave_t.h" #include "EUtils.h" #include "Validator.h" #include "Srd.h" #include "Report.h" #include "Storage.h" #include "Persistence.h" #include "Identity.h" #include "Workload.h" #endif /* !_CRUST_ENCLAVE_H_ */
790
C++
.h
32
23.53125
31
0.743692
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,369
Srd.h
crustio_crust-sworker/src/enclave/srd/Srd.h
#ifndef _CRUST_SRD_H_ #define _CRUST_SRD_H_ #include <vector> #include <string> #include <unordered_map> #include <unordered_set> #include <algorithm> #include "sgx_trts.h" #include "sgx_thread.h" #include "Workload.h" #include "EUtils.h" #include "PathHelper.h" #include "SafeLock.h" #include "Parameter.h" void srd_change(); crust_status_t srd_increase(const char *uuid); size_t srd_decrease(size_t change); void srd_remove_space(const char *data, size_t data_size); long get_srd_task(); crust_status_t change_srd_task(long change, long *real_change); crust_status_t srd_get_file(const char *path, uint8_t **p_data, size_t *data_size); #endif /* !_CRUST_SRD_H_ */
671
C++
.h
22
29.272727
83
0.743789
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,370
Storage.h
crustio_crust-sworker/src/enclave/storage/Storage.h
#ifndef _CRUST_STORAGE_H_ #define _CRUST_STORAGE_H_ #include <vector> #include <set> #include <tuple> #include "sgx_trts.h" #include "MerkleTree.h" #include "Workload.h" #include "Parameter.h" #include "EUtils.h" #include "Persistence.h" #include "Identity.h" #define FILE_DELETE_TIMEOUT 50 using namespace std; #if defined(__cplusplus) extern "C" { #endif crust_status_t storage_seal_file_start(const char *root, const char *root_b58); crust_status_t storage_seal_file_end(const char *root); crust_status_t storage_seal_file(const char *root, const uint8_t *data, size_t data_size, bool is_link, char *path, size_t path_size); crust_status_t storage_unseal_file(const char *path, uint8_t *p_unsealed_data, size_t unseal_data_size, size_t *p_decrypted_data_size); crust_status_t storage_delete_file(const char *hash); crust_status_t get_hashs_from_block(const uint8_t *block_data, size_t block_size, std::vector<uint8_t*> &hashs); crust_status_t storage_ipfs_get_block(const char *cid, uint8_t **p_data, size_t *data_size); crust_status_t storage_ipfs_cat(const char *cid, uint8_t **p_data, size_t *data_size); crust_status_t storage_ipfs_add(uint8_t *p_data, size_t data_size, char **cid); crust_status_t storage_get_file(const char *path, uint8_t **p_data, size_t *data_size); #if defined(__cplusplus) } #endif #endif /* !_CRUST_STORAGE_H_ */
1,364
C++
.h
32
41.03125
135
0.747144
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,371
Workload.h
crustio_crust-sworker/src/enclave/workload/Workload.h
#ifndef _CRUST_WORKLOAD_H_ #define _CRUST_WORKLOAD_H_ #include <utility> #include <vector> #include <list> #include <string> #include <map> #include <unordered_map> #include <set> #include "sgx_trts.h" #include "sgx_thread.h" #include "EUtils.h" #include "Enclave_t.h" #include "Persistence.h" #include "Json.h" #include "Identity.h" #include "Srd.h" #include "Parameter.h" #define VALIDATE_PROOF_MAX_NUM 2 std::map<char, std::string> file_status_2_name = { {FILE_STATUS_PENDING, FILE_TYPE_PENDING}, {FILE_STATUS_UNVERIFIED, FILE_TYPE_UNVERIFIED}, {FILE_STATUS_VALID, FILE_TYPE_VALID}, {FILE_STATUS_LOST, FILE_TYPE_LOST}, {FILE_STATUS_DELETED, FILE_TYPE_DELETED}, }; // Show information std::map<char, std::string> g_file_spec_status = { {FILE_STATUS_PENDING, FILE_TYPE_PENDING}, {FILE_STATUS_VALID, FILE_TYPE_VALID}, {FILE_STATUS_LOST, FILE_TYPE_LOST}, }; class Workload { public: std::vector<uint8_t*> srd_hashs; // used to store all G srd file collection' hashs std::vector<json::JSON> sealed_files; // Files have been added into checked queue std::set<std::string> reported_files_idx; // File indexes reported this turn of workreport sgx_ec256_public_t pre_pub_key; // Old version's public key std::unordered_map<std::string, json::JSON> pending_files_um; // Pending files // Basic static Workload *workload; static Workload *get_instance(); ~Workload(); void set_srd_remaining_task(long num); void set_srd_info(const char *uuid, long change); json::JSON get_srd_info(); json::JSON gen_workload_info(crust_status_t *status); crust_status_t restore_pre_pub_key(json::JSON &meta); void clean_all(); // For persistence json::JSON serialize_srd(); json::JSON serialize_file(); json::JSON get_upgrade_srd_info(crust_status_t *status); json::JSON get_upgrade_file_info(crust_status_t *status); crust_status_t restore_srd(json::JSON &g_hashs); crust_status_t restore_file(json::JSON &file_json); crust_status_t restore_file_info(); // For report void report_add_validated_srd_proof(); void report_add_validated_file_proof(); void report_reset_validated_proof(); bool report_has_validated_proof(); void set_report_file_flag(bool flag); bool get_report_file_flag(); void set_restart_flag(); void reduce_restart_flag(); bool get_restart_flag(); void handle_report_result(); crust_status_t can_report_work(size_t block_height); // For upgrade void set_upgrade(sgx_ec256_public_t pub_key); void unset_upgrade(); bool is_upgrade(); void set_upgrade_status(enc_upgrade_status_t status); enc_upgrade_status_t get_upgrade_status(); // For workload spec void set_file_spec(char file_status, long long change); const json::JSON &get_file_spec(); // For identity void set_account_id(std::string account_id); std::string get_account_id(); // Key pair bool try_get_key_pair(); const sgx_ec256_public_t& get_pub_key(); const sgx_ec256_private_t& get_pri_key(); void set_key_pair(ecc_key_pair id_key_pair); void unset_key_pair(); const ecc_key_pair& get_key_pair(); // MR enclave void set_mr_enclave(sgx_measurement_t mr); const sgx_measurement_t& get_mr_enclave(); // Report height void set_report_height(size_t height); size_t get_report_height(); // Srd related void clean_srd(); bool add_srd_to_deleted_buffer(uint32_t index); template <class InputIterator> void add_srd_to_deleted_buffer(InputIterator begin, InputIterator end) { sgx_thread_mutex_lock(&this->srd_del_idx_mutex); this->srd_del_idx_s.insert(begin, end); sgx_thread_mutex_unlock(&this->srd_del_idx_mutex); } template <class InputContainer> long delete_srd_meta(InputContainer &indexes) { if (indexes.size() == 0) { return 0; } long del_num = 0; for (auto rit = indexes.rbegin(); rit != indexes.rend(); rit++) { if (*rit < this->srd_hashs.size()) { uint8_t *hash = this->srd_hashs[*rit]; if (hash != NULL) { std::string uuid = hexstring_safe(hash, UUID_LENGTH); this->set_srd_info(uuid.c_str(), -1); free(hash); } this->srd_hashs.erase(this->srd_hashs.begin() + *rit); del_num++; } } // Update srd info std::string srd_info_str = this->get_srd_info().dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); return del_num; } bool is_srd_in_deleted_buffer(uint32_t index); void deal_deleted_srd(); void deal_deleted_srd_nolock(); void _deal_deleted_srd(bool locked); // File related void clean_file(); bool add_to_deleted_file_buffer(std::string cid); bool is_in_deleted_file_buffer(std::string cid); void recover_from_deleted_file_buffer(std::string cid); void deal_deleted_file(); bool is_file_dup_nolock(std::string cid); bool is_file_dup_nolock(std::string cid, size_t &pos); void add_file_nolock(json::JSON file); void add_file_nolock(json::JSON file, size_t pos); void del_file_nolock(std::string cid); void del_file_nolock(size_t pos); crust_status_t recover_illegal_file(const uint8_t *data, size_t data_size); #ifdef _CRUST_TEST_FLAG_ void clean_wl_file_spec() { sgx_thread_mutex_lock(&wl_file_spec_mutex); this->wl_file_spec = json::JSON(); sgx_thread_mutex_unlock(&wl_file_spec_mutex); } #endif sgx_thread_mutex_t ocall_wr_mutex = SGX_THREAD_MUTEX_INITIALIZER; // Workreport mutex sgx_thread_mutex_t ocall_wl_mutex = SGX_THREAD_MUTEX_INITIALIZER; // Workload mutex sgx_thread_mutex_t ocall_upgrade_mutex = SGX_THREAD_MUTEX_INITIALIZER; // Upgrade mutex sgx_thread_mutex_t srd_mutex = SGX_THREAD_MUTEX_INITIALIZER; sgx_thread_mutex_t file_mutex = SGX_THREAD_MUTEX_INITIALIZER; sgx_thread_mutex_t pending_files_um_mutex = SGX_THREAD_MUTEX_INITIALIZER; private: Workload(); std::string account_id; // Chain account id ecc_key_pair id_key_pair; // Identity key pair bool is_set_key_pair = false; // Check if key pair has been generated sgx_measurement_t mr_enclave; // Enclave code measurement size_t report_height = 0; // Identity report height, Used to check current block head out-of-date sgx_thread_mutex_t report_height_mutex = SGX_THREAD_MUTEX_INITIALIZER; int restart_flag = 0;// Used to indicate whether it is the first report after restart int validated_srd_proof = 0; // Generating workreport will decrease this value, while validating will increase it sgx_thread_mutex_t validated_srd_mutex = SGX_THREAD_MUTEX_INITIALIZER; int validated_file_proof = 0; // Generating workreport will decrease this value, while validating will increase it sgx_thread_mutex_t validated_file_mutex = SGX_THREAD_MUTEX_INITIALIZER; bool report_files; // True indicates reporting files this turn, false means not report json::JSON srd_info_json; // Srd info sgx_thread_mutex_t srd_info_mutex = SGX_THREAD_MUTEX_INITIALIZER; bool upgrade = false; // True indicates workreport should contain previous public key enc_upgrade_status_t upgrade_status = ENC_UPGRADE_STATUS_NONE; // Initial value indicates no upgrade json::JSON wl_file_spec; // For workload statistics sgx_thread_mutex_t wl_file_spec_mutex = SGX_THREAD_MUTEX_INITIALIZER; // Deleted srd index in metadata while the value indicates whether // this srd metadata has been deleted by other thread std::set<uint32_t> srd_del_idx_s; sgx_thread_mutex_t srd_del_idx_mutex = SGX_THREAD_MUTEX_INITIALIZER; // Deleted srd mutex // file_del_cid_s stores deleted file cid, if this file has been validated to lost, ignore this message std::set<std::string> file_del_cid_s; sgx_thread_mutex_t file_del_idx_mutex = SGX_THREAD_MUTEX_INITIALIZER; // Deleted srd mutex }; #endif /* !_CRUST_WORKLOAD_H_ */
8,236
C++
.h
193
37.031088
118
0.678442
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,372
SafeLock.h
crustio_crust-sworker/src/enclave/utils/SafeLock.h
#ifndef _CRUST_SAFELOCK_H_ #define _CRUST_SAFELOCK_H_ #include "sgx_thread.h" class SafeLock { public: SafeLock(sgx_thread_mutex_t &mutex): _mutex(mutex), lock_time(0) {} ~SafeLock(); void lock(); void unlock(); private: sgx_thread_mutex_t &_mutex; int lock_time; }; #endif /* !_CRUST_SAFELOCK_H_ */
329
C++
.h
15
19
71
0.666667
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,373
Defer.h
crustio_crust-sworker/src/enclave/utils/Defer.h
#ifndef _CRUST_DEFER_H_ #define _CRUST_DEFER_H_ #include <functional> class Defer { public: Defer(std::function<void()> f): _f(f) {} ~Defer() { this->_f(); } private: std::function<void()> _f; }; #endif /* !_CRUST_DEFER_H_ */
242
C++
.h
12
17.833333
44
0.615044
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,374
PathHelper.h
crustio_crust-sworker/src/enclave/utils/PathHelper.h
#ifndef _CRUST_PATH_HELPER_H_ #define _CRUST_PATH_HELPER_H_ #include <string> #include "EUtils.h" std::string get_g_path(const char *dir_path, const size_t now_index); std::string get_leaf_path(const char *g_path, const size_t now_index, const unsigned char *hash); std::string get_g_path_with_hash(const char *dir_path, const unsigned char *hash); std::string get_m_hashs_file_path(const char *g_path); #endif /* !_CRUST_PATH_HELPER_H_ */
444
C++
.h
9
47.888889
97
0.737819
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,375
Json.h
crustio_crust-sworker/src/enclave/utils/Json.h
/********************************************************************************** * Obtained from https://github.com/nbsdx/SimpleJSON , under the terms of the WTFPL. ***********************************************************************************/ #pragma once #include <cstdint> #include <cmath> #include <cctype> #include <string> #include <deque> #include <vector> #include <map> #include <type_traits> #include <initializer_list> #include <exception> #ifdef _CRUST_RESOURCE_H_ #include <ostream> #include <iostream> #include <string.h> #include "Log.h" #include "FormatUtils.h" #else #include "EUtils.h" #endif #define HASH_TAG "$&JT&$" namespace json { using std::deque; using std::vector; using std::enable_if; using std::initializer_list; using std::is_convertible; using std::is_floating_point; using std::is_integral; using std::is_same; using std::map; using std::string; const uint32_t _hash_length = 32; const string FIO_SEPARATER = "-"; namespace { #ifdef _CRUST_RESOURCE_H_ crust::Log *p_log = crust::Log::get_instance(); #endif string json_escape_pad(const string &str, string pad) { string output; for (unsigned i = 0; i < str.length(); ++i) switch (str[i]) { case '\"': output += "\\\""; break; case '\\': output += "\\\\"; break; case '\b': output += "\\b"; break; case '\f': output += "\\f"; break; case '\n': if (pad.size() > 2 && i + 1 == str.length() - 1 && str[i+1] == '}') { output += "\\n" + pad.substr(2, pad.length()); } else { output += "\\n" + pad; } break; case '\r': output += "\\r"; break; case '\t': output += "\\t"; break; default: output += str[i]; break; } return std::move(output); } string json_escape(const string &str) { string output; for (unsigned i = 0; i < str.length(); ++i) switch (str[i]) { case '\"': output += "\\\""; break; case '\\': output += "\\\\"; break; case '\b': output += "\\b"; break; case '\f': output += "\\f"; break; case '\n': output += "\\n"; break; case '\r': output += "\\r"; break; case '\t': output += "\\t"; break; default: output += str[i]; break; } return std::move(output); } std::string _hexstring(const void *vsrc, size_t len) { size_t i; const uint8_t *src = (const uint8_t *)vsrc; char *hex_buffer = (char*)malloc(len * 2); if (hex_buffer == NULL) { return ""; } memset(hex_buffer, 0, len * 2); char *bp; const char _hextable[] = "0123456789abcdef"; for (i = 0, bp = hex_buffer; i < len; ++i) { *bp = _hextable[src[i] >> 4]; ++bp; *bp = _hextable[src[i] & 0xf]; ++bp; } std::string ans(hex_buffer, len * 2); free(hex_buffer); return ans; } bool is_number(const string &s) { if (s.size() == 0) return false; for (auto c : s) { if (!isdigit(c)) { return false; } } return true; } template <typename... T> void print_info(T... args) { #ifdef _CRUST_RESOURCE_H_ p_log->info(args...); #else log_info(args...); #endif } template <typename... T> void print_debug(T... args) { #ifdef _CRUST_RESOURCE_H_ p_log->debug(args...); #else log_debug(args...); #endif } template <typename... T> void print_err(T... args) { #ifdef _CRUST_RESOURCE_H_ p_log->err(args...); #else log_err(args...); #endif } } // namespace class JSON { union BackingData { BackingData(double d) : Float(d) {} BackingData(long l) : Int(l) {} BackingData(bool b) : Bool(b) {} BackingData(string s) : String(new string(s)) {} BackingData() : Int(0) {} deque<JSON> *List; uint8_t *HashList; vector<uint8_t> *BufferList; map<string, JSON> *Map; string *String; double Float; long Int; bool Bool; } Internal; public: enum class Class { Null, Object, FIOObject, Array, Hash, Buffer, String, Floating, Integral, Boolean }; template <typename Container> class JSONWrapper { Container *object; public: JSONWrapper(Container *val) : object(val) {} JSONWrapper(std::nullptr_t) : object(nullptr) {} typename Container::iterator begin() { return object ? object->begin() : typename Container::iterator(); } typename Container::iterator end() { return object ? object->end() : typename Container::iterator(); } typename Container::const_iterator begin() const { return object ? object->begin() : typename Container::iterator(); } typename Container::const_iterator end() const { return object ? object->end() : typename Container::iterator(); } }; template <typename Container> class JSONConstWrapper { const Container *object; public: JSONConstWrapper(const Container *val) : object(val) {} JSONConstWrapper(std::nullptr_t) : object(nullptr) {} typename Container::const_iterator begin() const { return object ? object->begin() : typename Container::const_iterator(); } typename Container::const_iterator end() const { return object ? object->end() : typename Container::const_iterator(); } }; JSON() : Internal(), Type(Class::Null) {} JSON(initializer_list<JSON> list) : JSON() { SetType(Class::Object); for (auto i = list.begin(), e = list.end(); i != e; ++i, ++i) operator[](i->ToString()) = *std::next(i); } JSON(JSON &&other) : Internal(other.Internal), Type(other.Type) { other.Type = Class::Null; other.Internal.Map = nullptr; } JSON &operator=(JSON &&other) { ClearInternal(); Internal = other.Internal; Type = other.Type; other.Internal.Map = nullptr; other.Type = Class::Null; return *this; } JSON(const JSON &other) { switch (other.Type) { case Class::Object: Internal.Map = new map<string, JSON>(other.Internal.Map->begin(), other.Internal.Map->end()); break; case Class::FIOObject: Internal.Map = new map<string, JSON>(other.Internal.Map->begin(), other.Internal.Map->end()); break; case Class::Array: Internal.List = new deque<JSON>(other.Internal.List->begin(), other.Internal.List->end()); break; case Class::Hash: Internal.HashList = new uint8_t[_hash_length]; memcpy(Internal.HashList, other.Internal.HashList, _hash_length); break; case Class::Buffer: Internal.BufferList = new vector<uint8_t>(other.Internal.BufferList->begin(), other.Internal.BufferList->end()); break; case Class::String: Internal.String = new string(*other.Internal.String); break; default: Internal = other.Internal; } Type = other.Type; } JSON &operator=(const JSON &other) { ClearInternal(); switch (other.Type) { case Class::Object: Internal.Map = new map<string, JSON>(other.Internal.Map->begin(), other.Internal.Map->end()); break; case Class::FIOObject: Internal.Map = new map<string, JSON>(other.Internal.Map->begin(), other.Internal.Map->end()); break; case Class::Array: Internal.List = new deque<JSON>(other.Internal.List->begin(), other.Internal.List->end()); break; case Class::Hash: Internal.HashList = new uint8_t[_hash_length]; memcpy(Internal.HashList, other.Internal.HashList, _hash_length); break; case Class::Buffer: Internal.BufferList = new vector<uint8_t>(other.Internal.BufferList->begin(), other.Internal.BufferList->end()); break; case Class::String: Internal.String = new string(*other.Internal.String); break; default: Internal = other.Internal; } Type = other.Type; return *this; } ~JSON() { switch (Type) { case Class::Array: delete Internal.List; break; case Class::Hash: delete[] Internal.HashList; break; case Class::Buffer: delete Internal.BufferList; break; case Class::Object: delete Internal.Map; break; case Class::FIOObject: delete Internal.Map; break; case Class::String: delete Internal.String; break; default:; } } template <typename T> JSON(T b, typename enable_if<is_same<T, bool>::value>::type * = 0) : Internal(b), Type(Class::Boolean) {} template <typename T> JSON(T i, typename enable_if<is_integral<T>::value && !is_same<T, bool>::value>::type * = 0) : Internal((long)i), Type(Class::Integral) {} template <typename T> JSON(T f, typename enable_if<is_floating_point<T>::value>::type * = 0) : Internal((double)f), Type(Class::Floating) {} template <typename T> JSON(T s, typename enable_if<is_convertible<T, string>::value>::type * = 0) : Internal(string(s)), Type(Class::String) {} JSON(std::nullptr_t) : Internal(), Type(Class::Null) {} static JSON Make(Class type) { JSON ret; ret.SetType(type); return ret; } static JSON Load_unsafe(const string &); static JSON Load_unsafe(const uint8_t *p_data, size_t data_size); static JSON Load(crust_status_t *status, const string &); static JSON Load(crust_status_t *status, const uint8_t *p_data, size_t data_size); template <typename T> void append(T arg) { SetType(Class::Array); Internal.List->emplace_back(arg); } template <typename T, typename... U> void append(T arg, U... args) { append(arg); append(args...); } template <typename T> typename enable_if<is_same<T, bool>::value, JSON &>::type operator=(T b) { SetType(Class::Boolean); Internal.Bool = b; return *this; } template <typename T> typename enable_if<is_integral<T>::value && !is_same<T, bool>::value, JSON &>::type operator=(T i) { SetType(Class::Integral); Internal.Int = (long)i; return *this; } template <typename T> typename enable_if<is_floating_point<T>::value, JSON &>::type operator=(T f) { SetType(Class::Floating); Internal.Float = f; return *this; } template <typename T> typename enable_if<is_convertible<T, string>::value, JSON &>::type operator=(T s) { SetType(Class::String); *Internal.String = string(s); return *this; } template <typename T> typename enable_if<is_same<T, uint8_t*>::value, JSON &>::type operator=(T v) { SetType(Class::Hash); Internal.HashList = new uint8_t[_hash_length]; memcpy(Internal.HashList, v, _hash_length); return *this; } JSON &operator[](const string &key) { if (!(Type == Class::Object || Type == Class::FIOObject)) SetType(Class::Object); // FIXME: key map and value map should be independent, but there is error when using two maps if (Type == Class::FIOObject) { string rkey; if (Internal.Map->find(key) != Internal.Map->end()) { rkey = Internal.Map->operator[](key).ToString(); } else { rkey = "0" + FIO_SEPARATER + key; for (auto rit = Internal.Map->rbegin(); rit != Internal.Map->rend(); rit++) { string tkey = rit->first; size_t spos = tkey.find_first_of(FIO_SEPARATER); if (spos != tkey.npos) { string tag = tkey.substr(0, spos); if (is_number(tag)) { size_t lpos = tag.length() - 1; if (tag[lpos] >= '9') { tag.append("0"); } else { tag[lpos] = tag[lpos] + 1; } rkey = tag + FIO_SEPARATER + key; break; } } } Internal.Map->operator[](key) = rkey; } return Internal.Map->operator[](rkey); } return Internal.Map->operator[](key); } JSON &operator[](unsigned index) { SetType(Class::Array); if (index >= Internal.List->size()) Internal.List->resize(index + 1); return Internal.List->operator[](index); } char get_char(size_t index) { if (Type != Class::String || index >= Internal.String->size()) return '\0'; return Internal.String->operator[](index); } void set_char(size_t index, char c) { if (Type != Class::String || index > Internal.String->size()) return; if (index == Internal.String->size()) Internal.String->push_back(c); else Internal.String->operator[](index) = c; } void AppendBuffer(const uint8_t *data, size_t data_size) { if (Type == Class::Null) { SetType(Class::Buffer); } if (Type == Class::Buffer) { Internal.BufferList->insert(Internal.BufferList->end(), data, data + data_size); } } void FreeBuffer() { if (Type == Class::Buffer) { Internal.BufferList->clear(); } } JSON &AppendStr(std::string str) { if (Type == Class::Null) { SetType(Class::String); } if (Type == Class::String) { Internal.String->append(str); } return *this; } JSON &AppendStr(const char *str, size_t size) { if (Type == Class::Null) { SetType(Class::String); } if (Type == Class::String) { Internal.String->append(str, size); } return *this; } JSON &AppendChar(const char c) { if (Type == Class::Null) { SetType(Class::String); } if (Type == Class::String) { Internal.String->append(1, c); } return *this; } JSON &at(const string &key) { return operator[](key); } const JSON &at(const string &key) const { return Internal.Map->at(key); } JSON &at(unsigned index) { return operator[](index); } const JSON &at(unsigned index) const { return Internal.List->at(index); } long length() const { if (Type == Class::Array) return (long)Internal.List->size(); else if (Type == Class::Hash) return _hash_length; else return -1; } bool hasKey(const string &key) const { if (Type == Class::Object) return Internal.Map->find(key) != Internal.Map->end(); else if (Type == Class::FIOObject) return Internal.Map->find(key) != Internal.Map->end(); return false; } void erase(const string &key) { if (Type == Class::Object) { Internal.Map->erase(key); } else if (Type == Class::FIOObject) { if (Internal.Map->find(key) != Internal.Map->end()) { string rkey = Internal.Map->operator[](key).ToString(); Internal.Map->erase(key); Internal.Map->erase(rkey); } } } long size() const { if (Type == Class::Object) return (long)Internal.Map->size(); else if (Type == Class::FIOObject) return (long)Internal.Map->size(); else if (Type == Class::Array) return (long)Internal.List->size(); else if (Type == Class::Hash) return _hash_length; else if (Type == Class::Buffer) return Internal.BufferList->size(); else if (Type == Class::String) return Internal.String->size(); else return -1; } void AddNum(long num) { if (Type == Class::Null) { SetType(Class::Integral); } if (Type == Class::Integral) { Internal.Int += num; } } Class JSONType() const { return Type; } /// Functions for getting primitives from the JSON object. bool IsNull() const { return Type == Class::Null; } string ToString() const { bool b; return std::move(ToString(b)); } string ToString(bool &ok) const { ok = (Type == Class::String); if (Type == Class::String) return std::move(json_escape(*Internal.String)); else if (Type == Class::Hash) return _hexstring(Internal.HashList, _hash_length); else if (Type == Class::Buffer) return _hexstring(Internal.BufferList->data(), Internal.BufferList->size()); else if (Type == Class::Integral) return std::to_string(Internal.Int); else return string(""); } const char *ToCStr() { if (Type == Class::String) { return Internal.String->c_str(); } return NULL; } const uint8_t *ToBytes() { if (Type == Class::Hash) return Internal.HashList; else if (Type == Class::Buffer) return Internal.BufferList->data(); else return NULL; } double ToFloat() const { bool b; return ToFloat(b); } double ToFloat(bool &ok) const { ok = (Type == Class::Floating); return ok ? Internal.Float : 0.0; } long ToInt() const { bool b; return ToInt(b); } long ToInt(bool &ok) const { ok = (Type == Class::Integral); return ok ? Internal.Int : 0; } bool ToBool() const { bool b; return ToBool(b); } bool ToBool(bool &ok) const { ok = (Type == Class::Boolean); return ok ? Internal.Bool : false; } JSONWrapper<map<string, JSON>> ObjectRange() { if (Type == Class::Object) return JSONWrapper<map<string, JSON>>(Internal.Map); return JSONWrapper<map<string, JSON>>(nullptr); } JSONWrapper<deque<JSON>> ArrayRange() { if (Type == Class::Array) return JSONWrapper<deque<JSON>>(Internal.List); return JSONWrapper<deque<JSON>>(nullptr); } JSONConstWrapper<map<string, JSON>> ObjectRange() const { if (Type == Class::Object) return JSONConstWrapper<map<string, JSON>>(Internal.Map); return JSONConstWrapper<map<string, JSON>>(nullptr); } JSONConstWrapper<deque<JSON>> ArrayRange() const { if (Type == Class::Array) return JSONConstWrapper<deque<JSON>>(Internal.List); return JSONConstWrapper<deque<JSON>>(nullptr); } crust_status_t Insert(vector<uint8_t> &v, string s) { try { v.insert(v.end(), s.c_str(), s.c_str() + s.size()); } catch (std::exception &e) { return CRUST_MALLOC_FAILED; } return CRUST_SUCCESS; } crust_status_t Insert(vector<uint8_t> &v, vector<uint8_t> &s) { try { v.insert(v.end(), s.begin(), s.end()); } catch (std::exception &e) { return CRUST_MALLOC_FAILED; } return CRUST_SUCCESS; } crust_status_t Insert(vector<uint8_t> &v, const uint8_t *data, size_t data_size) { try { v.insert(v.end(), data, data + data_size); } catch (std::exception &e) { return CRUST_MALLOC_FAILED; } return CRUST_SUCCESS; } vector<uint8_t> dump_vector_unsafe() { crust_status_t ret = CRUST_SUCCESS; return dump_vector(&ret); } vector<uint8_t> dump_vector(crust_status_t *status) { vector<uint8_t> v; switch (Type) { case Class::Null: { string s = "null"; *status = Insert(v, s); return v; } case Class::Object: { v.push_back('{'); bool skip = true; for (auto &p : *Internal.Map) { if (!skip) v.push_back(','); string s("\"" + p.first + "\":"); *status = Insert(v, s); vector<uint8_t> sv = p.second.dump_vector(status); if (CRUST_SUCCESS != *status) { return v; } *status = Insert(v, sv); skip = false; } v.push_back('}'); return v; } case Class::FIOObject: { v.push_back('{'); bool skip = true; for (auto &p : *Internal.Map) { string key = p.first; size_t pos = key.find_first_of(FIO_SEPARATER); string tag; if (pos != key.npos && pos + 1 < key.size()) { tag = key.substr(0, pos); key = key.substr(pos + 1, key.size()); } if (!is_number(tag)) continue; if (!skip) v.push_back(','); string s("\"" + key + "\":"); *status = Insert(v, s); vector<uint8_t> sv = p.second.dump_vector(status); if (CRUST_SUCCESS != *status) { return v; } *status = Insert(v, sv); skip = false; } v.push_back('}'); return v; } case Class::Array: { v.push_back('['); bool skip = true; for (auto &p : *Internal.List) { if (!skip) v.push_back(','); vector<uint8_t> sv = p.dump_vector(status); if (CRUST_SUCCESS != *status) { return v; } *status = Insert(v, sv); skip = false; } v.push_back(']'); return v; } case Class::Hash: { *status = Insert(v, "\"" HASH_TAG + _hexstring(Internal.HashList, _hash_length) + "\""); return v; } case Class::Buffer: { string s("\"" HASH_TAG); *status = Insert(v, s); *status = Insert(v, *Internal.BufferList); v.push_back('"'); return v; } case Class::String: { string s = "\"" + json_escape(*Internal.String) + "\""; *status = Insert(v, s); return v; } case Class::Floating: { *status = Insert(v, std::to_string(Internal.Float)); return v; } case Class::Integral: { *status = Insert(v, std::to_string(Internal.Int)); return v; } case Class::Boolean: { *status = Insert(v, Internal.Bool ? "true" : "false"); return v; } default: { return v; } } return v; } string dump(int depth = 1, string tab = " ") const { string pad = ""; for (int i = 0; i < depth; ++i, pad += tab) ; switch (Type) { case Class::Null: return "null"; case Class::Object: { string s = "{\n"; bool skip = true; for (auto &p : *Internal.Map) { if (!skip) s += ",\n"; s += (pad + "\"" + p.first + "\" : " + p.second.dump(depth + 1, tab)); skip = false; } s += ("\n" + pad.erase(0, 2) + "}"); return s; } case Class::FIOObject: { string s = "{\n"; bool skip = true; for (auto &p : *Internal.Map) { string key = p.first; size_t pos = key.find_first_of(FIO_SEPARATER); string tag; if (pos != key.npos && pos + 1 < key.size()) { tag = key.substr(0, pos); key = key.substr(pos + 1, key.size()); } if (!is_number(tag)) continue; if (!skip) s += ",\n"; s += (pad + "\"" + key + "\" : " + p.second.dump(depth + 1, tab)); skip = false; } s += ("\n" + pad.erase(0, 2) + "}"); return s; } case Class::Array: { string s = "[\n" + pad; bool skip = true; for (auto &p : *Internal.List) { if (!skip) s += ", \n" + pad; s += p.dump(depth + 1, tab); skip = false; } s += "\n" + pad.erase(0, 2) + "]"; return s; } case Class::Hash: { return "\"" HASH_TAG + _hexstring(Internal.HashList, _hash_length) + "\""; } case Class::Buffer: { return "\"" HASH_TAG + _hexstring(Internal.BufferList->data(), Internal.BufferList->size()) + "\""; } case Class::String: return "\"" + json_escape_pad(*Internal.String, pad) + "\""; case Class::Floating: return std::to_string(Internal.Float); case Class::Integral: return std::to_string(Internal.Int); case Class::Boolean: return Internal.Bool ? "true" : "false"; default: return ""; } return ""; } //friend std::ostream &operator<<(std::ostream &, const JSON &); private: void SetType(Class type) { if (type == Type) return; ClearInternal(); switch (type) { case Class::Null: Internal.Map = nullptr; break; case Class::Object: Internal.Map = new map<string, JSON>(); break; case Class::FIOObject: Internal.Map = new map<string, JSON>(); break; case Class::Array: Internal.List = new deque<JSON>(); break; case Class::Hash: Internal.HashList = new uint8_t[_hash_length]; break; case Class::Buffer: Internal.BufferList = new vector<uint8_t>(); break; case Class::String: Internal.String = new string(); break; case Class::Floating: Internal.Float = 0.0; break; case Class::Integral: Internal.Int = 0; break; case Class::Boolean: Internal.Bool = false; break; } Type = type; } private: /* beware: only call if YOU know that Internal is allocated. No checks performed here. This function should be called in a constructed JSON just before you are going to overwrite Internal... */ void ClearInternal() { switch (Type) { case Class::Object: delete Internal.Map; break; case Class::FIOObject: delete Internal.Map; break; case Class::Array: delete Internal.List; break; case Class::Hash: delete[] Internal.HashList; break; case Class::Buffer: delete Internal.BufferList; break; case Class::String: delete Internal.String; break; default:; } } private: Class Type = Class::Null; }; JSON Array() { return std::move(JSON::Make(JSON::Class::Array)); } template <typename... T> JSON Array(T... args) { JSON arr = JSON::Make(JSON::Class::Array); arr.append(args...); return std::move(arr); } JSON Object() { return std::move(JSON::Make(JSON::Class::Object)); } // First in order map JSON FIOObject() { return std::move(JSON::Make(JSON::Class::FIOObject)); } /* std::ostream &operator<<(std::ostream &os, const JSON &json) { os << json.dump(); return os; } */ namespace { JSON parse_next(crust_status_t *status, const string &, size_t &); JSON parse_next(crust_status_t *status, const uint8_t *p_data, size_t &offset); void consume_ws(const string &str, size_t &offset) { while (isspace(str[offset])) ++offset; } void consume_ws(const uint8_t *p_data, size_t &offset) { while (isspace(p_data[offset])) ++offset; } JSON parse_object(crust_status_t *status, const string &str, size_t &offset) { JSON Object = JSON::Make(JSON::Class::Object); ++offset; consume_ws(str, offset); if (str[offset] == '}') { ++offset; return std::move(Object); } while (true) { JSON Key = parse_next(status, str, offset); consume_ws(str, offset); if (str[offset] != ':') { print_err("Error: Object: Expected colon, found %c\n", str[offset]); *status = CRUST_JSON_OBJECT_ERROR; break; } consume_ws(str, ++offset); JSON Value = parse_next(status, str, offset); Object[Key.ToString()] = Value; consume_ws(str, offset); if (str[offset] == ',') { ++offset; continue; } else if (str[offset] == '}') { ++offset; break; } else { print_err("Error: Object: Expected comma, found %c\n", str[offset]); *status = CRUST_JSON_OBJECT_ERROR; break; } } return std::move(Object); } JSON parse_object(crust_status_t *status, const uint8_t *p_data, size_t &offset) { JSON Object = JSON::Make(JSON::Class::Object); ++offset; consume_ws(p_data, offset); if (p_data[offset] == '}') { ++offset; return std::move(Object); } while (true) { JSON Key = parse_next(status, p_data, offset); consume_ws(p_data, offset); if (p_data[offset] != ':') { print_err("Error: Object: Expected colon, found %c\n", p_data[offset]); *status = CRUST_JSON_OBJECT_ERROR; break; } consume_ws(p_data, ++offset); JSON Value = parse_next(status, p_data, offset); Object[Key.ToString()] = Value; consume_ws(p_data, offset); if (p_data[offset] == ',') { ++offset; continue; } else if (p_data[offset] == '}') { ++offset; break; } else { print_err("Error: Object: Expected comma, found %c\n", p_data[offset]); *status = CRUST_JSON_OBJECT_ERROR; break; } } return std::move(Object); } JSON parse_array(crust_status_t *status, const string &str, size_t &offset) { JSON Array = JSON::Make(JSON::Class::Array); unsigned index = 0; ++offset; consume_ws(str, offset); if (str[offset] == ']') { ++offset; return std::move(Array); } while (true) { Array[index++] = parse_next(status, str, offset); consume_ws(str, offset); if (str[offset] == ',') { ++offset; continue; } else if (str[offset] == ']') { ++offset; break; } else { print_err("Error: Array: Expected ',' or ']', found %c\n", str[offset]); *status = CRUST_JSON_ARRAY_ERROR; return std::move(JSON::Make(JSON::Class::Array)); } } return std::move(Array); } JSON parse_array(crust_status_t *status, const uint8_t *p_data, size_t &offset) { JSON Array = JSON::Make(JSON::Class::Array); unsigned index = 0; ++offset; consume_ws(p_data, offset); if (p_data[offset] == ']') { ++offset; return std::move(Array); } while (true) { Array[index++] = parse_next(status, p_data, offset); consume_ws(p_data, offset); if (p_data[offset] == ',') { ++offset; continue; } else if (p_data[offset] == ']') { ++offset; break; } else { print_err("Error: Array: Expected ',' or ']', found %c\n", p_data[offset]); *status = CRUST_JSON_ARRAY_ERROR; return std::move(JSON::Make(JSON::Class::Array)); } } return std::move(Array); } JSON parse_string(crust_status_t *status, const string &str, size_t &offset) { JSON ans; string val; for (char c = str[++offset]; c != '\"'; c = str[++offset]) { if (c == '\\') { switch (str[++offset]) { case '\"': val += '\"'; break; case '\\': val += '\\'; break; case '/': val += '/'; break; case 'b': val += '\b'; break; case 'f': val += '\f'; break; case 'n': val += '\n'; break; case 'r': val += '\r'; break; case 't': val += '\t'; break; case 'u': { val += "\\u"; for (unsigned i = 1; i <= 4; ++i) { c = str[offset + i]; if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) val += c; else { print_err("Error: String: Expected hex character in unicode escape, found %c\n", c); *status = CRUST_JSON_STRING_ERROR; return std::move(JSON::Make(JSON::Class::String)); } } offset += 4; } break; default: val += '\\'; break; } } else val += c; } ++offset; if (memcmp(val.c_str(), HASH_TAG, strlen(HASH_TAG)) == 0) { val = val.substr(strlen(HASH_TAG), val.size()); uint8_t *p_hash = hex_string_to_bytes(val.c_str(), val.size()); if (p_hash != NULL) { ans = p_hash; free(p_hash); return std::move(ans); } } ans = val; return std::move(ans); } JSON parse_string(crust_status_t *status, const uint8_t *p_data, size_t &offset) { JSON ans; string val; for (char c = p_data[++offset]; c != '\"'; c = p_data[++offset]) { if (c == '\\') { switch (p_data[++offset]) { case '\"': val += '\"'; break; case '\\': val += '\\'; break; case '/': val += '/'; break; case 'b': val += '\b'; break; case 'f': val += '\f'; break; case 'n': val += '\n'; break; case 'r': val += '\r'; break; case 't': val += '\t'; break; case 'u': { val += "\\u"; for (unsigned i = 1; i <= 4; ++i) { c = p_data[offset + i]; if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) val += c; else { print_err("Error: String: Expected hex character in unicode escape, found %c\n", c); *status = CRUST_JSON_STRING_ERROR; return std::move(JSON::Make(JSON::Class::String)); } } offset += 4; } break; default: val += '\\'; break; } } else val += c; } ++offset; if (memcmp(val.c_str(), HASH_TAG, strlen(HASH_TAG)) == 0) { val = val.substr(strlen(HASH_TAG), val.size()); uint8_t *p_hash = hex_string_to_bytes(val.c_str(), val.size()); if (p_hash != NULL) { ans = p_hash; free(p_hash); return std::move(ans); } } ans = val; return std::move(ans); } JSON parse_number(crust_status_t *status, const string &str, size_t &offset) { JSON Number; string val, exp_str; char c; bool isDouble = false; long exp = 0; while (true) { c = str[offset++]; if ((c == '-') || (c >= '0' && c <= '9')) val += c; else if (c == '.') { val += c; isDouble = true; } else break; } if (c == 'E' || c == 'e') { c = str[offset++]; if (c == '-') { ++offset; exp_str += '-'; } while (true) { c = str[offset++]; if (c >= '0' && c <= '9') exp_str += c; else if (!isspace(c) && c != ',' && c != ']' && c != '}') { print_err("Error: Number: Expected a number for exponent, found %c\n", c); *status = CRUST_JSON_NUMBER_ERROR; return std::move(JSON::Make(JSON::Class::Null)); } else break; } exp = std::stol(exp_str); } else if (!isspace(c) && c != ',' && c != ']' && c != '}') { print_err("Error: Number: unexpected character %c\n", c); *status = CRUST_JSON_NUMBER_ERROR; return std::move(JSON::Make(JSON::Class::Null)); } --offset; if (isDouble) Number = std::stod(val) * std::pow(10, exp); else { if (!exp_str.empty()) Number = (double)std::stol(val) * (double)std::pow(10, exp); else Number = std::stol(val); } return std::move(Number); } JSON parse_number(crust_status_t *status, const uint8_t *p_data, size_t &offset) { JSON Number; string val, exp_str; char c; bool isDouble = false; long exp = 0; while (true) { c = p_data[offset++]; if ((c == '-') || (c >= '0' && c <= '9')) val += c; else if (c == '.') { val += c; isDouble = true; } else break; } if (c == 'E' || c == 'e') { c = p_data[offset++]; if (c == '-') { ++offset; exp_str += '-'; } while (true) { c = p_data[offset++]; if (c >= '0' && c <= '9') exp_str += c; else if (!isspace(c) && c != ',' && c != ']' && c != '}') { print_err("Error: Number: Expected a number for exponent, found %c\n", c); *status = CRUST_JSON_NUMBER_ERROR; return std::move(JSON::Make(JSON::Class::Null)); } else break; } exp = std::stol(exp_str); } else if (!isspace(c) && c != ',' && c != ']' && c != '}') { print_err("Error: Number: unexpected character %c\n", c); *status = CRUST_JSON_NUMBER_ERROR; return std::move(JSON::Make(JSON::Class::Null)); } --offset; if (isDouble) Number = std::stod(val) * std::pow(10, exp); else { if (!exp_str.empty()) Number = (double)std::stol(val) * (double)std::pow(10, exp); else Number = std::stol(val); } return std::move(Number); } JSON parse_bool(crust_status_t *status, const string &str, size_t &offset) { JSON Bool; if (str.substr(offset, 4) == "true") Bool = true; else if (str.substr(offset, 5) == "false") Bool = false; else { print_err("Error: Bool: Expected 'true' or 'false', found %s\n", str.substr(offset, 5)); *status = CRUST_JSON_BOOL_ERROR; return std::move(JSON::Make(JSON::Class::Null)); } offset += (Bool.ToBool() ? 4 : 5); return std::move(Bool); } JSON parse_bool(crust_status_t *status, const uint8_t *p_data, size_t &offset) { JSON Bool; if (memcmp(p_data + offset, "true", 4) == 0) Bool = true; else if (memcmp(p_data + offset, "false", 5) == 0) Bool = false; else { print_err("Error: Bool: Expected 'true' or 'false', found error\n"); *status = CRUST_JSON_BOOL_ERROR; return std::move(JSON::Make(JSON::Class::Null)); } offset += (Bool.ToBool() ? 4 : 5); return std::move(Bool); } JSON parse_null(crust_status_t *status, const string &str, size_t &offset) { JSON Null; if (str.substr(offset, 4) != "null") { print_err("Error: Null: Expected 'null', found %s\n", str.substr(offset, 4)); *status = CRUST_JSON_NULL_ERROR; return std::move(JSON::Make(JSON::Class::Null)); } offset += 4; return std::move(Null); } JSON parse_null(crust_status_t *status, const uint8_t *p_data, size_t &offset) { JSON Null; if (memcmp(p_data + offset, "null", 4) != 0) { print_err("Error: Null: Expected 'null', found error\n"); *status = CRUST_JSON_NULL_ERROR; return std::move(JSON::Make(JSON::Class::Null)); } offset += 4; return std::move(Null); } JSON parse_next(crust_status_t *status, const string &str, size_t &offset) { char value; consume_ws(str, offset); value = str[offset]; switch (value) { case '[': return std::move(parse_array(status, str, offset)); case '{': return std::move(parse_object(status, str, offset)); case '\"': return std::move(parse_string(status, str, offset)); case 't': case 'f': return std::move(parse_bool(status, str, offset)); case 'n': return std::move(parse_null(status, str, offset)); default: if ((value <= '9' && value >= '0') || value == '-') return std::move(parse_number(status, str, offset)); } print_err("Error: Parse: Unknown starting character %c\n", value); *status = CRUST_JSON_STARTING_ERROR; return JSON(); } JSON parse_next(crust_status_t *status, const uint8_t *p_data, size_t &offset) { char value; consume_ws(p_data, offset); value = p_data[offset]; switch (value) { case '[': return std::move(parse_array(status, p_data, offset)); case '{': return std::move(parse_object(status, p_data, offset)); case '\"': return std::move(parse_string(status, p_data, offset)); case 't': case 'f': return std::move(parse_bool(status, p_data, offset)); case 'n': return std::move(parse_null(status, p_data, offset)); default: if ((value <= '9' && value >= '0') || value == '-') return std::move(parse_number(status, p_data, offset)); } print_err("Error: Parse: Unknown starting character %c\n", value); *status = CRUST_JSON_STARTING_ERROR; return JSON(); } } // namespace JSON JSON::Load_unsafe(const string &str) { crust_status_t crust_status = CRUST_SUCCESS; return Load(&crust_status, str); } JSON JSON::Load_unsafe(const uint8_t *p_data, size_t data_size) { crust_status_t crust_status = CRUST_SUCCESS; return Load(&crust_status, p_data, data_size); } JSON JSON::Load(crust_status_t *status, const string &str) { if (str.size() == 0) return json::JSON(); size_t offset = 0; return std::move(parse_next(status, str, offset)); } JSON JSON::Load(crust_status_t *status, const uint8_t *p_data, size_t data_size) { if (data_size == 0) return json::JSON(); size_t offset = 0; return std::move(parse_next(status, p_data, offset)); } } // End Namespace json
46,577
C++
.h
1,636
19.156479
142
0.477107
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,376
EUtils.h
crustio_crust-sworker/src/enclave/utils/EUtils.h
#ifndef _CRUST_E_UTILS_H_ #define _CRUST_E_UTILS_H_ #include <assert.h> #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <string> #include <vector> #include <exception> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/cmac.h> #include <openssl/conf.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #include "sgx_thread.h" #include "sgx_trts.h" #include "Parameter.h" #include "CrustStatus.h" #include "Enclave_t.h" #include "Defer.h" namespace json { class JSON; } // Data tag to enclave only data #define SWORKER_PRIVATE_TAG "&+CRUSTSWORKERPRIVATE+&" /* The size of a srd disk leaf file */ #define SRD_RAND_DATA_LENGTH 1048576 //#define SRD_RAND_DATA_LENGTH 2097152 /* The number of srd disk leaf files under a G path */ #define SRD_RAND_DATA_NUM 1024 /* Used to store all M hashs under G path */ #define SRD_M_HASHS "m-hashs.bin" /* Main loop waiting time (s) */ #define MAIN_LOOP_WAIT_TIME 10 #define LOG_BUF_SIZE 32768 /* 32*1024 */ /* The length of hash */ #define HASH_LENGTH 32 const char *const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; const double base58_ifactor = 1.36565823730976103695740418120764243208481439700722980119458355862779176747360903943915516885072037696111192757109; typedef sgx_status_t (*p_ocall_store)(const char *data, size_t data_size, bool cover); #if defined(__cplusplus) extern "C" { #endif int eprint_info(const char* fmt, ...); int eprint_debug(const char* fmt, ...); int log_info(const char* fmt, ...); int log_warn(const char* fmt, ...); int log_err(const char* fmt, ...); int log_debug(const char* fmt, ...); int char_to_int(char input); char *hexstring(const void *vsrc, size_t len); std::string hexstring_safe(const void *vsrc, size_t len); uint8_t *hex_string_to_bytes(const void *src, size_t len); std::string unsigned_char_array_to_hex_string(const unsigned char *in, size_t size); std::vector<unsigned char> unsigned_char_array_to_unsigned_char_vector(const unsigned char *in, size_t size); char* unsigned_char_to_hex(unsigned char in); std::string byte_vec_to_string(std::vector<uint8_t> bytes); sgx_status_t Sgx_seal_data(const uint32_t additional_MACtext_length, const uint8_t *p_additional_MACtext, const uint32_t text2encrypt_length, const uint8_t *p_text2encrypt, const uint32_t sealed_data_size, sgx_sealed_data_t *p_sealed_data); sgx_status_t Sgx_seal_data_ex(const uint16_t key_policy, const sgx_attributes_t attribute_mask, const sgx_misc_select_t misc_mask, const uint32_t additional_MACtext_length, const uint8_t *p_additional_MACtext, const uint32_t text2encrypt_length, const uint8_t *p_text2encrypt, const uint32_t sealed_data_size, sgx_sealed_data_t *p_sealed_data); crust_status_t seal_data_mrenclave(const uint8_t *p_src, size_t src_len, sgx_sealed_data_t **p_sealed_data, size_t *sealed_data_size); crust_status_t seal_data_mrsigner(const uint8_t *p_src, size_t src_len, sgx_sealed_data_t **p_sealed_data, size_t *sealed_data_size); crust_status_t unseal_data_mrsigner(const sgx_sealed_data_t *data, uint32_t data_size, uint8_t **p_decrypted_data, uint32_t *decrypted_data_len); crust_status_t validate_merkletree_json(json::JSON tree); void *enc_malloc(size_t size); void *enc_realloc(void *p, size_t size); void *enc_crealloc(void *p, size_t old_size, size_t new_size); void remove_char(std::string &data, char c); void replace(std::string &data, std::string org_str, std::string det_str); char *base64_decode(const char *msg, size_t *sz); std::string base58_encode(const uint8_t *input, size_t len); std::string hash_to_cid(const uint8_t *hash); crust_status_t safe_ocall_store2(ocall_store_type_t t, const uint8_t *u, size_t s); crust_status_t safe_ocall_get2(ocall_get2_f f, uint8_t *u, size_t *s); #if defined(__cplusplus) } #endif template <class T> /** * @description: Insert data to vector end * @param v -> Reference to vector * @param data -> Pointer to data * @param data_size -> Data size * @return: Insert result */ crust_status_t vector_end_insert(std::vector<T> &v, const T *data, size_t data_size) { try { v.insert(v.end(), data, data + data_size); } catch (std::exception &e) { return CRUST_MALLOC_FAILED; } return CRUST_SUCCESS; } template <class T> /** * @description: Insert data to vector end * @param v -> Reference to destination vector * @param s -> Reference to added vector * @return: Insert result */ crust_status_t vector_end_insert(std::vector<T> &v, std::vector<T> &s) { try { v.insert(v.end(), s.begin(), s.end()); } catch (std::exception &e) { return CRUST_MALLOC_FAILED; } return CRUST_SUCCESS; } template <class T> /** * @description: Insert data to vector end * @param v -> Reference to vector * @param str -> String data * @return: Insert result */ crust_status_t vector_end_insert(std::vector<T> &v, std::string str) { try { v.insert(v.end(), str.c_str(), str.c_str() + str.size()); } catch (std::exception &e) { return CRUST_MALLOC_FAILED; } return CRUST_SUCCESS; } #endif /* !_CRUST_E_UTILS_H_ */
5,502
C++
.h
151
32.509934
146
0.687758
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,377
Validator.h
crustio_crust-sworker/src/enclave/validator/Validator.h
#ifndef _CRUST_VALIDATOR_H_ #define _CRUST_VALIDATOR_H_ #include <vector> #include <unordered_set> #include <unordered_map> #include <set> #include <algorithm> #include "sgx_thread.h" #include "sgx_trts.h" #include "Identity.h" #include "Srd.h" #include "MerkleTree.h" #include "Workload.h" #include "PathHelper.h" #include "Persistence.h" #include "EUtils.h" #include "Parameter.h" #include "SafeLock.h" #include "Storage.h" void validate_srd(); void validate_srd_real(); void validate_meaningful_file(); void validate_meaningful_file_real(); #endif /* !_CRUST_VALIDATOR_H_ */
583
C++
.h
24
23.083333
37
0.759928
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,378
IASReport.h
crustio_crust-sworker/src/enclave/include/IASReport.h
#ifndef _CRUST_IASREPORTE_H_ #define _CRUST_IASREPORTE_H_ #define ENCLAVE_PUB_KEY_SIZE 64 #define ACCOUNT_SIZE 48 #define SIGNER_ID_SIZE (SGX_ECP256_KEY_SIZE*2) #define IAS_TRYOUT 6 #define IAS_TIMEOUT 10 #define CLIENT_TIMEOUT 30 #define IAS_API_DEF_VERSION 3 typedef struct _entry_network_signature { uint8_t pub_key[ENCLAVE_PUB_KEY_SIZE]; uint8_t validator_pub_key[ENCLAVE_PUB_KEY_SIZE]; sgx_ec256_signature_t signature; } entry_network_signature; typedef struct _ecc_key_pair { sgx_ec256_public_t pub_key; sgx_ec256_private_t pri_key; } ecc_key_pair; #endif /* !_CRUST_IASREPORTE_H_ */
677
C++
.h
21
30
55
0.687692
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,379
MerkleTree.h
crustio_crust-sworker/src/enclave/include/MerkleTree.h
#ifndef _CRUST_MERKLE_TREE_H_ #define _CRUST_MERKLE_TREE_H_ #include <stddef.h> typedef struct MerkleTreeStruct { char* hash; size_t size; size_t links_num; struct MerkleTreeStruct** links; } MerkleTree; #endif /* !_CRUST_MERKLE_TREE_H_ */
259
C++
.h
11
20.818182
36
0.714286
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,380
Parameter.h
crustio_crust-sworker/src/enclave/include/Parameter.h
#ifndef _ENCLAVE_RESOURCE_H_ #define _ENCLAVE_RESOURCE_H_ #include "CrustStatus.h" #include "sgx_error.h" // For ocall store typedef crust_status_t (*ocall_store2_f)(const uint8_t *u, size_t s); typedef crust_status_t (*ecall_store2_f)(const uint8_t *u, size_t s); typedef sgx_status_t (*ocall_get2_f)(crust_status_t *status, uint8_t *u, size_t s, size_t *rs); // For all #define SWORKER_VERSION "2.0.1" #define LEAF_SEPARATOR "+leaf+" #define EMPTY_BLOCK_CID "QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n" #define EMPTY_BLOCK_FLAG "empty" // For enclave metadata #define ID_METADATA "metadata" #define ID_FILE "files" #define ID_SRD "srd" #define ID_KEY_PAIR "id_key_pair" #define ID_PRE_PUB_KEY "pre_pub_key" #define ID_REPORT_HEIGHT "report_height" #define ID_CHAIN_ACCOUNT_ID "chain_account_id" // For meaningful file // File meta info #define FILE_META "f_meta" #define FILE_CID "cid" #define FILE_HASH "hash" #define FILE_SIZE "size" #define FILE_SEALED_SIZE "s_size" #define FILE_BLOCK_NUM "block_num" #define FILE_CHAIN_BLOCK_NUM "c_block_num" #define FILE_LOST_INDEX "l_idx" #define FILE_STATUS "status" #define FILE_STATUS_UNVERIFIED '0' #define FILE_STATUS_VALID '1' #define FILE_STATUS_LOST '2' #define FILE_STATUS_DELETED '3' #define FILE_STATUS_PENDING '4' // File seal info #define FILE_BLOCKS "blocks" // IPFS file #define IPFS_META "sbs" #define IPFS_META_PATH "path" // Current status #define CURRENT_STATUS 0 // Wait to sync status #define WAITING_STATUS 1 // Old status #define ORIGIN_STATUS 2 #define FILE_NUMBER_UPPER_LIMIT 400000 #define FILE_CAL_BUFFER_SIZE 7340032 #define FILE_TYPE_PENDING "pending" #define FILE_TYPE_UNVERIFIED "unverified" #define FILE_TYPE_VALID "valid" #define FILE_TYPE_LOST "lost" #define FILE_TYPE_DELETED "deleted" // File limit #define FILE_PENDING_LIMIT 500 #define FILE_PENDING_STIME "start_second" #define FILE_PENDING_DOWNLOAD_TIME "used_time" #define FILE_PENDING_SIZE "sealed_size" // For chain data #define CHAIN_BLOCK_NUMBER "c_block_num" #define CHAIN_BLOCK_HASH "c_block_hash" // For Merkle tree #define MT_CID "cid" #define MT_HASH "hash" #define MT_DATA_HASH "d_hash" #define MT_LINKS "links" #define MT_LINKS_NUM "l_num" // For IAS report #define IAS_CERT "ias_cert" #define IAS_SIG "ias_sig" #define IAS_ISV_BODY "isv_body" #define IAS_CHAIN_ACCOUNT_ID "account_id" #define IAS_REPORT_SIG "sig" #define IAS_ISV_BODY_TAG "isvEnclaveQuoteBody" // For work report #define WORKREPORT_PUB_KEY "pub_key" #define WORKREPORT_PRE_PUB_KEY "pre_pub_key" #define WORKREPORT_BLOCK_HEIGHT "block_height" #define WORKREPORT_BLOCK_HASH "block_hash" #define WORKREPORT_RESERVED "reserved" #define WORKREPORT_FILES_SIZE "files_size" #define WORKREPORT_RESERVED_ROOT "reserved_root" #define WORKREPORT_FILES_ROOT "files_root" #define WORKREPORT_FILES_ADDED "added_files" #define WORKREPORT_FILES_DELETED "deleted_files" #define WORKREPORT_SIG "sig" #define WORKREPORT_FILE_LIMIT 300 #define REPORT_SLOT 600 #define BLOCK_INTERVAL 6 // REPORT_INTERVAL_BLCOK_NUMBER_UPPER_LIMIT < REPORT_SLOT // REPORT_INTERVAL_BLCOK_NUMBER_UPPER_LIMIT > REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT #define REPORT_INTERVAL_BLCOK_NUMBER_UPPER_LIMIT 400 // REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT > 0 #define REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT 10 // For workload #define WL_SRD "srd" #define WL_SRD_COMPLETE "srd_complete" #define WL_SRD_ROOT_HASH "root_hash" #define WL_SRD_SPACE "space" #define WL_SRD_REMAINING_TASK "srd_remaining_task" #define WL_SRD_DETAIL "srd_detail" #define WL_FILES "files" #define WL_FILE_SEALED_SIZE "sealed_size" #define WL_FILE_STATUS "status" #define WL_FILE_ROOT_HASH "file_root_hash" #define WL_FILE_SPEC_INFO "file_spec" // For srd #define SRD_MAX_INC_PER_TURN 64 #define SRD_MAX_DEC_PER_TURN 5000 #define SRD_NUMBER_UPPER_LIMIT 512000 /* 500x1024G */ // For validator #define SRD_VALIDATE_RATE 0.005 #define SRD_VALIDATE_MIN_NUM 64 /* Meaningful disk file verification ratio */ #define MEANINGFUL_VALIDATE_RATE 0.005 #define MEANINGFUL_VALIDATE_MIN_NUM 64 #define MEANINGFUL_VALIDATE_MIN_BLOCK_NUM 1 #define MAX_BLOCK_SIZE 1048576 /* 1024*1024 */ #define SEALED_BLOCK_TAG_SIZE 4 // For ocalls #define PERSIST_SUM "persist_sum" #define PERSIST_SIZE "persist_size" #define BOUNDARY_SIZE_THRESHOLD 4194304 /* 4*1024*1024 */ // Basic parameters #define HASH_LENGTH 32 #define CID_LENGTH 46 #define UUID_LENGTH 8 #define FILE_DISK_LIMIT 8 #define LAYER_LENGTH 2 #define ENCLAVE_MALLOC_TRYOUT 3 const int SRD_LENGTH = UUID_LENGTH + LAYER_LENGTH + HASH_LENGTH; const int FILE_ITEM_LENGTH = UUID_LENGTH + HASH_LENGTH; // For upgrade #define UPGRADE_PUBLIC_KEY "pub_key" #define UPGRADE_BLOCK_HEIGHT "block_height" #define UPGRADE_BLOCK_HASH "block_hash" #define UPGRADE_SRD "upgrade_srd" #define UPGRADE_SRD_ROOT "upgrade_srd_root" #define UPGRADE_FILE "upgrade_file" #define UPGRADE_FILE_ROOT "upgrade_file_root" #define UPGRADE_MRENCLAVE "upgrade_mrenclave" #define UPGRADE_SIG "upgrade_sig" #define UPGRADE_WAIT_BLOCK_MAX 50 #define UPGRADE_WAIT_BLOCK_MIN 10 typedef enum _enc_upgrade_status_t { ENC_UPGRADE_STATUS_NONE, ENC_UPGRADE_STATUS_PROCESS, ENC_UPGRADE_STATUS_SUCCESS, } enc_upgrade_status_t; typedef enum _store_type_t { STORE_TYPE_REG, STORE_TYPE_SRD, STORE_TYPE_FILE, } store_type_t; typedef enum _ocall_store_type_t { OCALL_FILE_INFO_ALL, OCALL_STORE_WORKREPORT, OCALL_STORE_UPGRADE_DATA, } ocall_store_type_t; typedef enum _ecall_store_type_t { ECALL_RESTORE_FROM_UPGRADE, } ecall_store_type_t; #endif /* !_ENCLAVE_RESOURCE_H_ */
5,566
C++
.h
165
32.369697
95
0.773648
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,381
CrustStatus.h
crustio_crust-sworker/src/enclave/include/CrustStatus.h
#ifndef _CRUST_CRUST_STATUS_H_ #define _CRUST_CRUST_STATUS_H_ #define CRUST_SEPARATOR "$crust_separator$" #define CRUST_MK_ERROR(x) (0x00000000 | (x)) typedef enum _crust_status_t { // Successed CRUST_SUCCESS = CRUST_MK_ERROR(0), // Work report CRUST_BLOCK_HEIGHT_EXPIRED = CRUST_MK_ERROR(0x2000), CRUST_FIRST_WORK_REPORT_AFTER_REPORT = CRUST_MK_ERROR(0x2001), CRUST_WORK_REPORT_NOT_VALIDATED = CRUST_MK_ERROR(0x2002), CRUST_SERVICE_UNAVAILABLE = CRUST_MK_ERROR(0x2003), // Failed CRUST_MALLOC_FAILED = CRUST_MK_ERROR(0x4000), CRUST_SEAL_DATA_FAILED = CRUST_MK_ERROR(0x4001), CRUST_UNSEAL_DATA_FAILED = CRUST_MK_ERROR(0x4002), CRUST_BAD_SEAL_DATA = CRUST_MK_ERROR(0x4003), CRUST_SGX_FAILED = CRUST_MK_ERROR(0x4004), CRUST_NOT_EQUAL = CRUST_MK_ERROR(0x4005), CRUST_SGX_SIGN_FAILED = CRUST_MK_ERROR(0x4006), CRUST_SGX_VERIFY_SIG_FAILED = CRUST_MK_ERROR(0x4007), CRUST_UNEXPECTED_ERROR = CRUST_MK_ERROR(0x4008), CRUST_INVALID_MERKLETREE = CRUST_MK_ERROR(0x4009), CRUST_MALWARE_DATA_BLOCK = CRUST_MK_ERROR(0x4010), CRUST_OPEN_FILE_FAILED = CRUST_MK_ERROR(0x4011), CRUST_WRITE_FILE_FAILED = CRUST_MK_ERROR(0x4012), CRUST_DELETE_FILE_FAILED = CRUST_MK_ERROR(0x4013), CRUST_RENAME_FILE_FAILED = CRUST_MK_ERROR(0x4014), CRUST_MKDIR_FAILED = CRUST_MK_ERROR(0x4015), CRUST_ACCESS_FILE_FAILED = CRUST_MK_ERROR(0x4016), CRUST_INVALID_META_DATA = CRUST_MK_ERROR(0x4017), CRUST_INIT_QUOTE_FAILED = CRUST_MK_ERROR(0x4018), CRUST_SRD_NUMBER_EXCEED = CRUST_MK_ERROR(0x4019), CRUST_FILE_NUMBER_EXCEED = CRUST_MK_ERROR(0x4020), CRUST_DEVICE_ERROR = CRUST_MK_ERROR(0x4021), CRUST_OCALL_NO_ENOUGH_BUFFER = CRUST_MK_ERROR(0x4022), // Json error CRUST_JSON_ARRAY_ERROR = CRUST_MK_ERROR(0x5001), CRUST_JSON_OBJECT_ERROR = CRUST_MK_ERROR(0x5002), CRUST_JSON_STRING_ERROR = CRUST_MK_ERROR(0x5003), CRUST_JSON_BOOL_ERROR = CRUST_MK_ERROR(0x5004), CRUST_JSON_NULL_ERROR = CRUST_MK_ERROR(0x5005), CRUST_JSON_NUMBER_ERROR = CRUST_MK_ERROR(0x5006), CRUST_JSON_STARTING_ERROR = CRUST_MK_ERROR(0x5007), // Persistence related CRUST_PERSIST_ADD_FAILED = CRUST_MK_ERROR(0x6001), CRUST_PERSIST_DEL_FAILED = CRUST_MK_ERROR(0x6002), CRUST_PERSIST_SET_FAILED = CRUST_MK_ERROR(0x6003), CRUST_PERSIST_GET_FAILED = CRUST_MK_ERROR(0x6004), // IAS report related CRUST_IAS_QUERY_FAILED = CRUST_MK_ERROR(0x7001), CRUST_IAS_OK = CRUST_MK_ERROR(0x7002), CRUST_IAS_VERIFY_FAILED = CRUST_MK_ERROR(0x7003), CRUST_IAS_BADREQUEST = CRUST_MK_ERROR(0x7004), CRUST_IAS_UNAUTHORIZED = CRUST_MK_ERROR(0x7005), CRUST_IAS_NOT_FOUND = CRUST_MK_ERROR(0x7006), CRUST_IAS_UNEXPECTED_ERROR = CRUST_MK_ERROR(0x7007), CRUST_IAS_SERVER_ERR = CRUST_MK_ERROR(0x7008), CRUST_IAS_UNAVAILABLE = CRUST_MK_ERROR(0x7009), CRUST_IAS_INTERNAL_ERROR = CRUST_MK_ERROR(0x7010), CRUST_IAS_BAD_CERTIFICATE = CRUST_MK_ERROR(0x7011), CRUST_IAS_BAD_SIGNATURE = CRUST_MK_ERROR(0x7012), CRUST_IAS_BAD_BODY = CRUST_MK_ERROR(0x7013), CRUST_IAS_REPORTDATA_NE = CRUST_MK_ERROR(0x7014), CRUST_IAS_GET_REPORT_FAILED = CRUST_MK_ERROR(0x7015), CRUST_IAS_BADMEASUREMENT = CRUST_MK_ERROR(0x7016), CRUST_IAS_GETPUBKEY_FAILED = CRUST_MK_ERROR(0x7017), CRUST_SIGN_PUBKEY_FAILED = CRUST_MK_ERROR(0x7018), CRUST_GET_ACCOUNT_ID_BYTE_FAILED = CRUST_MK_ERROR(0x7019), CRUST_SWORKER_UPGRADE_NEEDED = CRUST_MK_ERROR(0x7020), // Storage related CRUST_STORAGE_SER_MERKLETREE_FAILED = CRUST_MK_ERROR(0x8001), CRUST_STORAGE_UPDATE_FILE_FAILED = CRUST_MK_ERROR(0x8002), CRUST_STORAGE_UNSEAL_FILE_FAILED = CRUST_MK_ERROR(0x8003), CRUST_STORAGE_UNEXPECTED_FILE_BLOCK = CRUST_MK_ERROR(0x8004), CRUST_STORAGE_NEW_FILE_NOTFOUND = CRUST_MK_ERROR(0x8005), CRUST_STORAGE_NEW_FILE_SIZE_ERROR = CRUST_MK_ERROR(0x8006), CRUST_STORAGE_EMPTY_BLOCK = CRUST_MK_ERROR(0x8007), CRUST_STORAGE_IPFS_BLOCK_GET_ERROR = CRUST_MK_ERROR(0x8008), CRUST_STORAGE_IPFS_CAT_ERROR = CRUST_MK_ERROR(0x8009), CRUST_STORAGE_IPFS_ADD_ERROR = CRUST_MK_ERROR(0x8010), CRUST_STORAGE_IPFS_DEL_ERROR = CRUST_MK_ERROR(0x8011), CRUST_STORAGE_FILE_DUP = CRUST_MK_ERROR(0x8012), CRUST_STORAGE_FILE_SEALING = CRUST_MK_ERROR(0x8013), CRUST_STORAGE_FILE_DELETING = CRUST_MK_ERROR(0x8014), CRUST_STORAGE_FILE_BLOCK_NOTFOUND = CRUST_MK_ERROR(0x8015), CRUST_STORAGE_NO_ENOUGH_SPACE = CRUST_MK_ERROR(0x8016), CRUST_STORAGE_INCOMPLETE_BLOCK = CRUST_MK_ERROR(0x8017), // Validation related CRUST_VALIDATE_GET_REQUEST_FAILED = CRUST_MK_ERROR(0x9001), CRUST_VALIDATE_HIGH_PRIORITY = CRUST_MK_ERROR(0x9002), // Upgrade related CRUST_UPGRADE_RESTORE_SRD_FAILED = CRUST_MK_ERROR(0x10001), CRUST_UPGRADE_RESTORE_FILE_FAILED = CRUST_MK_ERROR(0x10002), CRUST_UPGRADE_SEND_WORKREPORT_FAILED = CRUST_MK_ERROR(0x10003), CRUST_UPGRADE_INVALID_WORKREPORT = CRUST_MK_ERROR(0x10004), CRUST_UPGRADE_GET_BLOCK_HASH_FAILED = CRUST_MK_ERROR(0x10005), CRUST_UPGRADE_GEN_WORKREPORT_FAILED = CRUST_MK_ERROR(0x10006), CRUST_UPGRADE_WAIT_FOR_NEXT_ERA = CRUST_MK_ERROR(0x10007), CRUST_UPGRADE_BAD_SRD = CRUST_MK_ERROR(0x10008), CRUST_UPGRADE_BAD_FILE = CRUST_MK_ERROR(0x10009), CRUST_UPGRADE_IS_UPGRADING = CRUST_MK_ERROR(0x10010), CRUST_UPGRADE_NEED_LEFT_DATA = CRUST_MK_ERROR(0x10011), CRUST_UPGRADE_BLOCK_EXPIRE = CRUST_MK_ERROR(0x10012), CRUST_UPGRADE_NO_VALIDATE = CRUST_MK_ERROR(0x10013), CRUST_UPGRADE_RESTART = CRUST_MK_ERROR(0x10014), CRUST_UPGRADE_NO_FILE = CRUST_MK_ERROR(0x10015), // For http CRUST_HTTP_INVALID_INPUT = CRUST_MK_ERROR(0x11001), } crust_status_t; #endif /* !_CRUST_CRUST_STATUS_H_ */
5,767
C++
.h
112
46.526786
67
0.721521
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,382
Persistence.h
crustio_crust-sworker/src/enclave/persistence/Persistence.h
#ifndef _CRUST_PERSISTENCE_H_ #define _CRUST_PERSISTENCE_H_ #include <string> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "sgx_tseal.h" #include "EUtils.h" #include "CrustStatus.h" #if defined(__cplusplus) extern "C" { #endif crust_status_t persist_add(std::string key, const uint8_t *value, size_t value_len); crust_status_t persist_del(std::string key); crust_status_t persist_set(std::string key, const uint8_t *value, size_t value_len); crust_status_t persist_set_unsafe(std::string key, const uint8_t *value, size_t value_len); crust_status_t persist_get(std::string key, uint8_t **value, size_t *value_len); crust_status_t persist_get_unsafe(std::string key, uint8_t **value, size_t *value_len); #if defined(__cplusplus) } #endif #endif /* !_CRUST_PERSISTENCE_H_ */
803
C++
.h
23
33.608696
91
0.743855
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,383
Identity.h
crustio_crust-sworker/src/enclave/identity/Identity.h
#ifndef _CRUST_IDENTITY_H_ #define _CRUST_IDENTITY_H_ #include <string> #include <map> #include <set> #include <vector> #include <sgx_utils.h> #include <sgx_tkey_exchange.h> #include <sgx_tcrypto.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include <sgx_ecp_types.h> #include <sgx_report.h> #include "sgx_thread.h" #include "sgx_spinlock.h" #include "tSgxSSL_api.h" #include "Workload.h" #include "Report.h" #include "Enclave_t.h" #include "IASReport.h" #include "EUtils.h" #include "Persistence.h" #include "Parameter.h" #include "Defer.h" #define PSE_RETRIES 5 /* Arbitrary. Not too long, not too short. */ enum metadata_op_e { ID_APPEND, ID_UPDATE }; using namespace std; extern sgx_thread_mutex_t g_metadata_mutex; string url_decode(string str); int cert_load_size (X509 **cert, const char *pemdata, size_t sz); int cert_load (X509 **cert, const char *pemdata); STACK_OF(X509) * cert_stack_build (X509 **certs); int cert_verify (X509_STORE *store, STACK_OF(X509) *chain); void cert_stack_free (STACK_OF(X509) *chain); int sha256_verify(const unsigned char *msg, size_t mlen, unsigned char *sig, size_t sigsz, EVP_PKEY *pkey, int *result); X509_STORE * cert_init_ca(X509 *cert); crust_status_t id_verify_upload_epid_identity(char ** IASReport, size_t size); crust_status_t id_gen_upload_ecdsa_quote(uint8_t *p_quote, uint32_t quote_size); crust_status_t id_gen_upload_ecdsa_identity(const char *report, uint32_t size); sgx_status_t id_gen_key_pair(const char *account_id, size_t len); sgx_status_t id_get_quote_report(sgx_report_t *report, sgx_target_info_t *target_info); sgx_status_t id_gen_sgx_measurement(); crust_status_t id_cmp_chain_account_id(const char *account_id, size_t len); void id_get_info(); crust_status_t id_store_metadata(); crust_status_t id_restore_metadata(); crust_status_t id_gen_upgrade_data(size_t block_height); crust_status_t id_restore_from_upgrade(const uint8_t *data, size_t data_size); #endif
2,000
C++
.h
55
34.945455
87
0.744571
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,384
Report.h
crustio_crust-sworker/src/enclave/report/Report.h
#ifndef _CRUST_REPORT_H_ #define _CRUST_REPORT_H_ #include <string> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/cmac.h> #include <openssl/conf.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #include "Workload.h" #include "Identity.h" #include "EUtils.h" crust_status_t gen_and_upload_work_report(const char *block_hash, size_t block_height, long wait_time, bool is_upgrading, bool locked); crust_status_t gen_work_report(const char *block_hash, size_t block_height, bool is_upgrading); #endif /* !_CRUST_REPORT_H_ */
631
C++
.h
18
33.777778
135
0.754934
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,385
App.h
crustio_crust-sworker/src/app/App.h
#ifndef _CRUST_APP_H_ #define _CRUST_APP_H_ #include <stdlib.h> #include <stdio.h> #include <limits.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <unistd.h> #include <sgx_key_exchange.h> #include <sgx_report.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include <sgx_urts.h> #include "Config.h" #include "Process.h" #include "Log.h" #include "Srd.h" #include "Resource.h" int main_daemon(void); #endif /* !_CRUST_APP_H_ */
499
C++
.h
22
21.454545
29
0.720339
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,386
Ipfs.h
crustio_crust-sworker/src/app/ipfs/Ipfs.h
#ifndef _CRUST_IPFS_H_ #define _CRUST_IPFS_H_ #include <time.h> #include "Config.h" #include "Log.h" #include "FormatUtils.h" #include "HttpClient.h" class Ipfs { private: static Ipfs *ipfs; Ipfs(std::string url); ~Ipfs(); std::string url; std::string form_boundary; public: static Ipfs *get_instance(); bool online(); size_t block_get(const char *cid, unsigned char **p_data_out); size_t cat(const char *cid, unsigned char **p_data_out); std::string add(unsigned char *p_data_in, size_t size); bool del(std::string cid); }; #endif /* !_CRUST_IPFS_H_ */
602
C++
.h
24
22.083333
66
0.670732
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,388
WebServer.h
crustio_crust-sworker/src/app/http/WebServer.h
#ifndef _CRUST_WEBSERVER_H_ #define _CRUST_WEBSERVER_H_ #include <stdio.h> #include <mutex> #include <exception> #include <algorithm> #include <cstdlib> #include <functional> #include <iostream> #include <memory> #include <string> #include <thread> #include <vector> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/ssl.hpp> #include <boost/beast/websocket.hpp> #include <boost/beast/version.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/strand.hpp> #include <boost/asio/ssl/error.hpp> #include <boost/asio/ssl/stream.hpp> #include <boost/make_unique.hpp> #include <boost/optional.hpp> #include <boost/function.hpp> #include <boost/make_shared.hpp> #include <sgx_report.h> #include <sgx_key_exchange.h> #include <sgx_error.h> #include "sgx_eid.h" #include "sgx_tseal.h" #include "ECalls.h" #include "Common.h" #include "Config.h" #include "FormatUtils.h" #include "SgxSupport.h" #include "Resource.h" #include "FileUtils.h" #include "Log.h" #include "ApiHandler.h" #define WEBSOCKET_THREAD_NUM 3 namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp> namespace net = boost::asio; // from <boost/asio.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> // Accepts incoming connections and launches the sessions class WebServer : public std::enable_shared_from_this<WebServer> { net::io_context& ioc_; ssl::context& ctx_; tcp::acceptor acceptor_; std::shared_ptr<std::string const> doc_root_; tcp::endpoint endpoint_; public: WebServer( net::io_context& ioc, ssl::context& ctx, tcp::endpoint endpoint, std::shared_ptr<std::string const> const& doc_root); // Start accepting incoming connections bool run(); void stop(); void set_api_handler(ApiHandler *api_handler); private: void do_accept(); void on_accept(beast::error_code ec, tcp::socket socket); ApiHandler *api_handler; }; void start_webservice(void); void stop_webservice(void); /* Load a signed certificate into the ssl context, and configure the context for use with a WebServer. For this to work with the browser or operating system, it is necessary to import the "Beast Test CA" certificate into the local certificate store, browser, or operating system depending on your environment Please see the documentation accompanying the Beast certificate for more details. */ inline void load_server_certificate(boost::asio::ssl::context& ctx) { /* The certificate was generated from CMD.EXE on Windows 10 using: winpty openssl dhparam -out dh.pem 2048 winpty openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 10000 -out cert.pem -subj "//C=US\ST=CA\L=Los Angeles\O=Beast\CN=www.example.com" */ std::string const cert = "-----BEGIN CERTIFICATE-----\n" "MIIDaDCCAlCgAwIBAgIJAO8vBu8i8exWMA0GCSqGSIb3DQEBCwUAMEkxCzAJBgNV\n" "BAYTAlVTMQswCQYDVQQIDAJDQTEtMCsGA1UEBwwkTG9zIEFuZ2VsZXNPPUJlYXN0\n" "Q049d3d3LmV4YW1wbGUuY29tMB4XDTE3MDUwMzE4MzkxMloXDTQ0MDkxODE4Mzkx\n" "MlowSTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMS0wKwYDVQQHDCRMb3MgQW5n\n" "ZWxlc089QmVhc3RDTj13d3cuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUA\n" "A4IBDwAwggEKAoIBAQDJ7BRKFO8fqmsEXw8v9YOVXyrQVsVbjSSGEs4Vzs4cJgcF\n" "xqGitbnLIrOgiJpRAPLy5MNcAXE1strVGfdEf7xMYSZ/4wOrxUyVw/Ltgsft8m7b\n" "Fu8TsCzO6XrxpnVtWk506YZ7ToTa5UjHfBi2+pWTxbpN12UhiZNUcrRsqTFW+6fO\n" "9d7xm5wlaZG8cMdg0cO1bhkz45JSl3wWKIES7t3EfKePZbNlQ5hPy7Pd5JTmdGBp\n" "yY8anC8u4LPbmgW0/U31PH0rRVfGcBbZsAoQw5Tc5dnb6N2GEIbq3ehSfdDHGnrv\n" "enu2tOK9Qx6GEzXh3sekZkxcgh+NlIxCNxu//Dk9AgMBAAGjUzBRMB0GA1UdDgQW\n" "BBTZh0N9Ne1OD7GBGJYz4PNESHuXezAfBgNVHSMEGDAWgBTZh0N9Ne1OD7GBGJYz\n" "4PNESHuXezAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCmTJVT\n" "LH5Cru1vXtzb3N9dyolcVH82xFVwPewArchgq+CEkajOU9bnzCqvhM4CryBb4cUs\n" "gqXWp85hAh55uBOqXb2yyESEleMCJEiVTwm/m26FdONvEGptsiCmF5Gxi0YRtn8N\n" "V+KhrQaAyLrLdPYI7TrwAOisq2I1cD0mt+xgwuv/654Rl3IhOMx+fKWKJ9qLAiaE\n" "fQyshjlPP9mYVxWOxqctUdQ8UnsUKKGEUcVrA08i1OAnVKlPFjKBvk+r7jpsTPcr\n" "9pWXTO9JrYMML7d+XRSZA1n3856OqZDX4403+9FnXCvfcLZLLKTBvwwFgEFGpzjK\n" "UEVbkhd5qstF6qWK\n" "-----END CERTIFICATE-----\n"; std::string const key = "-----BEGIN PRIVATE KEY-----\n" "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJ7BRKFO8fqmsE\n" "Xw8v9YOVXyrQVsVbjSSGEs4Vzs4cJgcFxqGitbnLIrOgiJpRAPLy5MNcAXE1strV\n" "GfdEf7xMYSZ/4wOrxUyVw/Ltgsft8m7bFu8TsCzO6XrxpnVtWk506YZ7ToTa5UjH\n" "fBi2+pWTxbpN12UhiZNUcrRsqTFW+6fO9d7xm5wlaZG8cMdg0cO1bhkz45JSl3wW\n" "KIES7t3EfKePZbNlQ5hPy7Pd5JTmdGBpyY8anC8u4LPbmgW0/U31PH0rRVfGcBbZ\n" "sAoQw5Tc5dnb6N2GEIbq3ehSfdDHGnrvenu2tOK9Qx6GEzXh3sekZkxcgh+NlIxC\n" "Nxu//Dk9AgMBAAECggEBAK1gV8uETg4SdfE67f9v/5uyK0DYQH1ro4C7hNiUycTB\n" "oiYDd6YOA4m4MiQVJuuGtRR5+IR3eI1zFRMFSJs4UqYChNwqQGys7CVsKpplQOW+\n" "1BCqkH2HN/Ix5662Dv3mHJemLCKUON77IJKoq0/xuZ04mc9csykox6grFWB3pjXY\n" "OEn9U8pt5KNldWfpfAZ7xu9WfyvthGXlhfwKEetOuHfAQv7FF6s25UIEU6Hmnwp9\n" "VmYp2twfMGdztz/gfFjKOGxf92RG+FMSkyAPq/vhyB7oQWxa+vdBn6BSdsfn27Qs\n" "bTvXrGe4FYcbuw4WkAKTljZX7TUegkXiwFoSps0jegECgYEA7o5AcRTZVUmmSs8W\n" "PUHn89UEuDAMFVk7grG1bg8exLQSpugCykcqXt1WNrqB7x6nB+dbVANWNhSmhgCg\n" "VrV941vbx8ketqZ9YInSbGPWIU/tss3r8Yx2Ct3mQpvpGC6iGHzEc/NHJP8Efvh/\n" "CcUWmLjLGJYYeP5oNu5cncC3fXUCgYEA2LANATm0A6sFVGe3sSLO9un1brA4zlZE\n" "Hjd3KOZnMPt73B426qUOcw5B2wIS8GJsUES0P94pKg83oyzmoUV9vJpJLjHA4qmL\n" "CDAd6CjAmE5ea4dFdZwDDS8F9FntJMdPQJA9vq+JaeS+k7ds3+7oiNe+RUIHR1Sz\n" "VEAKh3Xw66kCgYB7KO/2Mchesu5qku2tZJhHF4QfP5cNcos511uO3bmJ3ln+16uR\n" "GRqz7Vu0V6f7dvzPJM/O2QYqV5D9f9dHzN2YgvU9+QSlUeFK9PyxPv3vJt/WP1//\n" "zf+nbpaRbwLxnCnNsKSQJFpnrE166/pSZfFbmZQpNlyeIuJU8czZGQTifQKBgHXe\n" "/pQGEZhVNab+bHwdFTxXdDzr+1qyrodJYLaM7uFES9InVXQ6qSuJO+WosSi2QXlA\n" "hlSfwwCwGnHXAPYFWSp5Owm34tbpp0mi8wHQ+UNgjhgsE2qwnTBUvgZ3zHpPORtD\n" "23KZBkTmO40bIEyIJ1IZGdWO32q79nkEBTY+v/lRAoGBAI1rbouFYPBrTYQ9kcjt\n" "1yfu4JF5MvO9JrHQ9tOwkqDmNCWx9xWXbgydsn/eFtuUMULWsG3lNjfst/Esb8ch\n" "k5cZd6pdJZa4/vhEwrYYSuEjMCnRb0lUsm7TsHxQrUd6Fi/mUuFU/haC0o0chLq7\n" "pVOUFq5mW8p0zbtfHbjkgxyF\n" "-----END PRIVATE KEY-----\n"; std::string const dh = "-----BEGIN DH PARAMETERS-----\n" "MIIBCAKCAQEArzQc5mpm0Fs8yahDeySj31JZlwEphUdZ9StM2D8+Fo7TMduGtSi+\n" "/HRWVwHcTFAgrxVdm+dl474mOUqqaz4MpzIb6+6OVfWHbQJmXPepZKyu4LgUPvY/\n" "4q3/iDMjIS0fLOu/bLuObwU5ccZmDgfhmz1GanRlTQOiYRty3FiOATWZBRh6uv4u\n" "tff4A9Bm3V9tLx9S6djq31w31Gl7OQhryodW28kc16t9TvO1BzcV3HjRPwpe701X\n" "oEEZdnZWANkkpR/m/pfgdmGPU66S2sXMHgsliViQWpDCYeehrvFRHEdR9NV+XJfC\n" "QMUk26jPTIVTLfXmmwU0u8vUkpR7LQKkwwIBAg==\n" "-----END DH PARAMETERS-----\n"; ctx.set_password_callback( [](std::size_t, boost::asio::ssl::context_base::password_purpose) { return "test"; }); ctx.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); ctx.use_certificate_chain( boost::asio::buffer(cert.data(), cert.size())); ctx.use_private_key( boost::asio::buffer(key.data(), key.size()), boost::asio::ssl::context::file_format::pem); ctx.use_tmp_dh( boost::asio::buffer(dh.data(), dh.size())); } inline void load_root_certificates(ssl::context& ctx, boost::system::error_code& ec) { std::string const cert = "-----BEGIN CERTIFICATE-----\n" "MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" "QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" "b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" "9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" "CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" "nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" "43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" "T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" "gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" "BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" "TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" "DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" "hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" "06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" "PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" "YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" "CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" "-----END CERTIFICATE-----\n" "-----BEGIN CERTIFICATE-----\n" "MIIDaDCCAlCgAwIBAgIJAO8vBu8i8exWMA0GCSqGSIb3DQEBCwUAMEkxCzAJBgNV\n" "BAYTAlVTMQswCQYDVQQIDAJDQTEtMCsGA1UEBwwkTG9zIEFuZ2VsZXNPPUJlYXN0\n" "Q049d3d3LmV4YW1wbGUuY29tMB4XDTE3MDUwMzE4MzkxMloXDTQ0MDkxODE4Mzkx\n" "MlowSTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMS0wKwYDVQQHDCRMb3MgQW5n\n" "ZWxlc089QmVhc3RDTj13d3cuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUA\n" "A4IBDwAwggEKAoIBAQDJ7BRKFO8fqmsEXw8v9YOVXyrQVsVbjSSGEs4Vzs4cJgcF\n" "xqGitbnLIrOgiJpRAPLy5MNcAXE1strVGfdEf7xMYSZ/4wOrxUyVw/Ltgsft8m7b\n" "Fu8TsCzO6XrxpnVtWk506YZ7ToTa5UjHfBi2+pWTxbpN12UhiZNUcrRsqTFW+6fO\n" "9d7xm5wlaZG8cMdg0cO1bhkz45JSl3wWKIES7t3EfKePZbNlQ5hPy7Pd5JTmdGBp\n" "yY8anC8u4LPbmgW0/U31PH0rRVfGcBbZsAoQw5Tc5dnb6N2GEIbq3ehSfdDHGnrv\n" "enu2tOK9Qx6GEzXh3sekZkxcgh+NlIxCNxu//Dk9AgMBAAGjUzBRMB0GA1UdDgQW\n" "BBTZh0N9Ne1OD7GBGJYz4PNESHuXezAfBgNVHSMEGDAWgBTZh0N9Ne1OD7GBGJYz\n" "4PNESHuXezAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCmTJVT\n" "LH5Cru1vXtzb3N9dyolcVH82xFVwPewArchgq+CEkajOU9bnzCqvhM4CryBb4cUs\n" "gqXWp85hAh55uBOqXb2yyESEleMCJEiVTwm/m26FdONvEGptsiCmF5Gxi0YRtn8N\n" "V+KhrQaAyLrLdPYI7TrwAOisq2I1cD0mt+xgwuv/654Rl3IhOMx+fKWKJ9qLAiaE\n" "fQyshjlPP9mYVxWOxqctUdQ8UnsUKKGEUcVrA08i1OAnVKlPFjKBvk+r7jpsTPcr\n" "9pWXTO9JrYMML7d+XRSZA1n3856OqZDX4403+9FnXCvfcLZLLKTBvwwFgEFGpzjK\n" "UEVbkhd5qstF6qWK\n" "-----END CERTIFICATE-----\n"; ; ctx.add_certificate_authority( boost::asio::buffer(cert.data(), cert.size()), ec); if(ec) return; } // Load the root certificates into an ssl::context inline void load_root_certificates(ssl::context& ctx) { boost::system::error_code ec; load_root_certificates(ctx, ec); if(ec) throw boost::system::system_error{ec}; } #endif /* !_CRUST_WEBSERVER_H_ */
11,492
C++
.h
229
44.100437
160
0.768142
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,390
ApiHandler.h
crustio_crust-sworker/src/app/http/ApiHandler.h
#ifndef _CRUST_API_HANDLER_H_ #define _CRUST_API_HANDLER_H_ #include <stdio.h> #include <mutex> #include <set> #include <vector> #include <exception> #include <algorithm> #include <cstdlib> #include <functional> #include <iostream> #include <memory> #include <string> #include <thread> #include <boost/beast/core.hpp> #include <boost/beast/ssl.hpp> #include <boost/beast/websocket.hpp> #include <boost/beast/websocket/ssl.hpp> #include <boost/asio/strand.hpp> #include <sgx_report.h> #include <sgx_key_exchange.h> #include <sgx_error.h> #include "sgx_eid.h" #include "sgx_tcrypto.h" #include "sgx_tseal.h" #include "ECalls.h" #include "FormatUtils.h" #include "IASReport.h" #include "SgxSupport.h" #include "Resource.h" #include "HttpClient.h" #include "FileUtils.h" #include "Log.h" #include "Config.h" #include "Common.h" #include "DataBase.h" #include "Srd.h" #include "EnclaveData.h" #include "Chain.h" #include "../../enclave/utils/Defer.h" #ifdef _CRUST_TEST_FLAG_ #include "ApiHandlerTest.h" extern size_t g_block_height; #endif #define WS_SEPARATOR "$crust_ws_separator$" #define IPFS_INDEX_LENGTH 512 namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> class WebServer; class ApiHandler { public: std::string websocket_handler(std::string &path, std::string &data, bool &close_connection); template<class Body, class Allocator, class Send> void http_handler(beast::string_view doc_root, http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send, bool is_ssl); //void ApiHandler::http_handler(beast::string_view doc_root, // http::request<http::basic_fields<http::string_body>>&& req, Queue&& send, bool is_ssl) private: std::shared_ptr<WebServer> server = NULL; std::vector<uint8_t> root_hash_v; bool unseal_check_backup = false; MerkleTree *tree_root = NULL; // Upgrade block service set const std::set<std::string> upgrade_block_s = { "/srd/change", "/storage/delete", "/storage/seal_start", }; const std::set<std::string> http_mute_req_s = { "/workload", "/enclave/id_info", "/storage/seal", "/storage/unseal", "/file/info", "/file/info_by_type", }; const std::set<std::string> sealed_file_types = { "all", FILE_TYPE_PENDING, FILE_TYPE_VALID, FILE_TYPE_LOST, }; }; std::string path_cat(beast::string_view base, beast::string_view path); std::map<std::string, std::string> get_params(std::string &url); extern sgx_enclave_id_t global_eid; // Used to show validation status long change_srd_num = 0; extern bool is_ecdsa_mode; /** * @description: Start rest service * @return: Start status */ template<class Body, class Allocator, class Send> void ApiHandler::http_handler(beast::string_view /*doc_root*/, http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send, bool /*is_ssl*/) { Config *p_config = Config::get_instance(); crust::Log *p_log = crust::Log::get_instance(); UrlEndPoint urlendpoint = get_url_end_point(p_config->base_url); EnclaveData *ed = EnclaveData::get_instance(); EnclaveQueue *eq = EnclaveQueue::get_instance(); std::string cur_path; // Returns a bad request response auto const bad_request = [&req](beast::string_view why) { http::response<http::string_body> res{http::status::bad_request, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "text/html"); res.keep_alive(req.keep_alive()); res.body() = std::string(why); res.prepare_payload(); return res; }; // Make sure we can handle the method if( req.method() != http::verb::get && req.method() != http::verb::post && req.method() != http::verb::head) return send(bad_request("Unknown HTTP-method")); // Request path must be absolute and not contain "..". if( req.target().empty() || req.target()[0] != '/' || req.target().find("..") != beast::string_view::npos) return send(bad_request("Illegal request-target")); // Build the path to the requested file std::string req_route = std::string(req.target().data(), req.target().size()); if (memcmp(req_route.c_str(), urlendpoint.base.c_str(), urlendpoint.base.size()) != 0) { return send(bad_request("Illegal request-target")); } // Get request real route std::map<std::string, std::string> params_m = get_params(req_route); req_route = params_m["req_route"]; std::string route_tag = req_route.substr(req_route.find(urlendpoint.base) + urlendpoint.base.size(), req_route.size()); if (http_mute_req_s.find(route_tag) == http_mute_req_s.end()) { p_log->info("Http request:%s\n", req_route.c_str()); } // Choose service according to upgrade status if (UPGRADE_STATUS_EXIT == ed->get_upgrade_status()) { p_log->warn("This process will exit!\n"); http::response<http::string_body> res{ std::piecewise_construct, std::make_tuple("Stop service!"), std::make_tuple(http::status::forbidden, req.version())}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "application/text"); json::JSON ret_body; ret_body[HTTP_STATUS_CODE] = 501; ret_body[HTTP_MESSAGE] = "No service will be provided because of upgrade!"; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); return send(std::move(res)); } if (UPGRADE_STATUS_NONE != ed->get_upgrade_status() && UPGRADE_STATUS_STOP_WORKREPORT != ed->get_upgrade_status() && upgrade_block_s.find(route_tag) != upgrade_block_s.end()) { p_log->warn("Upgrade is doing, %s request cannot be applied!\n", route_tag.c_str()); http::response<http::string_body> res{ std::piecewise_construct, std::make_tuple("Current service is closed due to upgrade!"), std::make_tuple(http::status::forbidden, req.version())}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "application/text"); json::JSON ret_body; ret_body[HTTP_STATUS_CODE] = 501; ret_body[HTTP_MESSAGE] = "Current service is closed due to upgrade!"; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); return send(std::move(res)); } // ----- Respond to HEAD request ----- // if(req.method() == http::verb::head) { http::response<http::empty_body> res{http::status::ok, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "application/text"); res.keep_alive(req.keep_alive()); return send(std::move(res)); } http::response<http::string_body> res{ std::piecewise_construct, std::make_tuple("Unknown request target"), std::make_tuple(http::status::bad_request, req.version())}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "application/text"); #ifdef _CRUST_TEST_FLAG_ json::JSON req_json; req_json["target"] = req_route; req_json["method"] = req.method() == http::verb::get ? "GET" : "POST"; req_json["body"] = std::string(reinterpret_cast<const char *>(req.body().data()), req.body().size()); json::JSON test_res = http_handler_test(urlendpoint, req_json); if (test_res.size() > 0) { res.result(test_res[HTTP_STATUS_CODE].ToInt()); std::string res_body = test_res[HTTP_MESSAGE].ToString(); remove_char(res_body, '\\'); res.body() = res_body; res.content_length(res.body().size()); return send(std::move(res)); } #endif // ----- Respond to GET request ----- // if(req.method() == http::verb::get) { // ----- Get workload ----- // cur_path = urlendpoint.base + "/workload"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { res.result(200); res.body() = EnclaveData::get_instance()->gen_workload_str(); goto getcleanup; } // ----- Stop sworker ----- // cur_path = urlendpoint.base + "/stop"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON ret_body; std::string ret_info; int ret_code = 400; if (SGX_SUCCESS != Ecall_stop_all(global_eid)) { ret_info = "Stop enclave failed! Invoke SGX API failed!"; ret_code = 500; p_log->err("%s\n", ret_info.c_str()); } else { ret_info = "Stop sworker successfully."; ret_code = 200; // We just need to wait workreport and storing metadata, and then can stop while (eq->has_stopping_block_task()) { sleep(1); } ed->set_upgrade_status(UPGRADE_STATUS_EXIT); p_log->info("%s\n", ret_info.c_str()); } ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.body() = ret_body.dump(); goto getcleanup; } // ----- Get enclave thread information ----- // cur_path = urlendpoint.base + "/enclave/thread_info"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { res.result(200); res.body() = eq->get_running_ecalls_info(); goto getcleanup; } // ----- Get enclave id information ----- // cur_path = urlendpoint.base + "/enclave/id_info"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { std::string id_info_str = ed->get_enclave_id_info(); if (id_info_str.compare("") == 0) { json::JSON ret_body; ret_body[HTTP_STATUS_CODE] = 400; ret_body[HTTP_MESSAGE] = "Get id info failed!Invoke SGX API failed!"; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); } else { json::JSON id_json = json::JSON::Load_unsafe(id_info_str); id_json["account"] = p_config->chain_address; id_json["version"] = VERSION; id_json["sworker_version"] = SWORKER_VERSION; id_json["attestation_mode"] = is_ecdsa_mode ? "ecdsa" : "epid"; res.body() = id_json.dump(); res.result(200); } goto getcleanup; } // ----- Get sealed file information by cid ----- // cur_path = urlendpoint.base + "/file/info"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { int ret_code = 400; std::string ret_info; json::JSON ret_body; std::string param_name = "cid"; if (params_m.find(param_name) == params_m.end()) { ret_info = "Bad parameter! Need a string type parameter:'" + param_name + "'"; ret_code = 400; } else { std::string cid = params_m[param_name]; json::JSON ret_body; std::string file_info = EnclaveData::get_instance()->get_file_info(cid); if (file_info.compare("") == 0) { ret_info = "File not found."; ret_code = 404; } else { res.result(200); res.body() = file_info; goto getcleanup; } } ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); goto getcleanup; } // ----- Get sealed file information by type ----- // cur_path = urlendpoint.base + "/file/info_by_type"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { res.result(200); std::string param_name = "type"; bool bad_req = false; if (params_m.find(param_name) == params_m.end()) { bad_req = true; } else { std::string type = params_m[param_name]; if (sealed_file_types.find(type) == sealed_file_types.end()) { bad_req = true; } else { if (type.compare("all") == 0) { res.body() = EnclaveData::get_instance()->get_file_info_all(); } else { res.body() = EnclaveData::get_instance()->get_file_info_by_type(type); } } } if (bad_req) { json::JSON ret_body; ret_body[HTTP_STATUS_CODE] = 400; ret_body[HTTP_MESSAGE] = "Bad parameter! Need a string type parameter:'" + param_name + "' which should be 'all', 'pending', 'valid', 'lost'"; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); } goto getcleanup; } // ----- Inform upgrade ----- // cur_path = urlendpoint.base + "/upgrade/start"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { int ret_code = 400; json::JSON ret_body; std::string ret_info; if (UPGRADE_STATUS_NONE != ed->get_upgrade_status() && UPGRADE_STATUS_STOP_WORKREPORT != ed->get_upgrade_status()) { ret_body[HTTP_STATUS_CODE] = 502; ret_body[HTTP_MESSAGE] = "Another upgrading is still running!"; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); goto getcleanup; } // Block current work-report for a while ed->set_upgrade_status(UPGRADE_STATUS_STOP_WORKREPORT); sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; crust::BlockHeader block_header; if (!crust::Chain::get_instance()->get_block_header(block_header)) { ret_info = "Chain is not running!Get block header failed!"; ret_code = 400; p_log->err("%s\n", ret_info.c_str()); } else if (SGX_SUCCESS != (sgx_status = Ecall_enable_upgrade(global_eid, &crust_status, block_header.number))) { ret_info = "Invoke SGX API failed!"; ret_code = 500; p_log->err("%sError code:%lx\n", ret_info.c_str(), sgx_status); } else { if (CRUST_SUCCESS == crust_status) { ret_info = "Receive upgrade inform successfully!"; ret_code = 200; // Set upgrade status ed->set_upgrade_status(UPGRADE_STATUS_PROCESS); // Give current tasks some time to go into enclave queue. sleep(10); p_log->info("%s\n", ret_info.c_str()); } else { switch (crust_status) { case CRUST_UPGRADE_BLOCK_EXPIRE: ret_info = "Block expired!Wait for next report slot(" + std::to_string(REPORT_SLOT) + " blocks)."; ret_code = 400; break; case CRUST_UPGRADE_NO_VALIDATE: ret_info = "Necessary validation not completed!"; ret_code = 400; break; case CRUST_UPGRADE_RESTART: ret_info = "Cannot report due to restart!Wait for report slot(" + std::to_string(REPORT_SLOT) + " blocks)."; ret_code = 400; break; case CRUST_UPGRADE_NO_FILE: ret_info = "Cannot get files for check!Please check ipfs!"; ret_code = 400; break; default: ret_info = "Unknown error."; ret_code = 400; } } } ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); goto getcleanup; } // ----- Get upgrade metadata ----- // cur_path = urlendpoint.base + "/upgrade/metadata"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { upgrade_status_t upgrade_status = ed->get_upgrade_status(); if (UPGRADE_STATUS_COMPLETE != upgrade_status) { json::JSON ret_body; if (UPGRADE_STATUS_NONE == upgrade_status) { // Set timeout http status code ret_body[HTTP_STATUS_CODE] = 408; ret_body[HTTP_MESSAGE] = "Upgrade timeout for old sworker!"; } else { ret_body[HTTP_STATUS_CODE] = 502; ret_body[HTTP_MESSAGE] = "Metadata is still collecting!"; } res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); } else { std::string upgrade_data = ed->get_upgrade_data(); p_log->info("Generate upgrade data successfully!Data size:%ld.\n", upgrade_data.size()); res.result(200); res.body() = upgrade_data; } goto getcleanup; } // ----- Inform current sworker upgrade result ----- // cur_path = urlendpoint.base + "/upgrade/complete"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { res.result(200); int ret_code = 200; std::string ret_info; json::JSON ret_body; json::JSON req_json = json::JSON::Load_unsafe((const uint8_t *)req.body().data(), req.body().size()); std::string param_name = "success"; if (!req_json.hasKey(param_name) || req_json[param_name].JSONType() != json::JSON::Class::Boolean) { ret_info = "Bad parameter! Need a boolean type parameter:'" + param_name + "'"; ret_code = 400; ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); } else { bool upgrade_ret = req_json[param_name].ToBool(); crust_status_t crust_status = CRUST_SUCCESS; if (!upgrade_ret) { ret_info = "Upgrade failed! Current version will restore work."; p_log->err("%s\n", ret_info.c_str()); ed->set_upgrade_status(UPGRADE_STATUS_NONE); } else { if (UPGRADE_STATUS_COMPLETE == ed->get_upgrade_status()) { // Store old metadata to ID_METADATA_OLD crust::DataBase *db = crust::DataBase::get_instance(); std::string metadata_old; if (CRUST_SUCCESS != (crust_status = db->get(ID_METADATA, metadata_old))) { ret_info = "Upgrade: get old metadata failed!Status code:" + num_to_hexstring(crust_status); p_log->warn("%s\n", ret_info.c_str()); } else { if (CRUST_SUCCESS != (crust_status = db->set(ID_METADATA_OLD, metadata_old))) { ret_info = "Upgrade: store old metadata failed!Status code:" + num_to_hexstring(crust_status); p_log->warn("%s\n", ret_info.c_str()); } } if (CRUST_SUCCESS != (crust_status = db->del(ID_METADATA))) { ret_info = "Upgrade: delete old metadata failed!Status code:" + num_to_hexstring(crust_status); p_log->warn("%s\n", ret_info.c_str()); } else { ret_info = "Upgrade: clean old version's data successfully!"; p_log->info("%s\n", ret_info.c_str()); } // Set upgrade exit flag ed->set_upgrade_status(UPGRADE_STATUS_EXIT); } else { ret_info = "Cannot exit upgrade because of unexpected upgrade status!"; p_log->err("%s\n", ret_info.c_str()); } } ret_body[HTTP_STATUS_CODE] = std::stoi(num_to_hexstring(crust_status), NULL, 10); ret_body[HTTP_MESSAGE] = ret_info; res.body() = ret_body.dump(); } goto getcleanup; } getcleanup: res.content_length(res.body().size()); res.keep_alive(req.keep_alive()); return send(std::move(res)); } // ----- Respond to POST request ----- // if(req.method() == http::verb::post) { res.result(400); res.body() = "Unknown request!"; json::JSON res_json; // ----- Set debug flag ----- // cur_path = urlendpoint.base + "/debug"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { // Check input parameters std::string ret_info; int ret_code = 400; json::JSON ret_body; json::JSON req_json = json::JSON::Load_unsafe((const uint8_t *)req.body().data(), req.body().size()); std::string param_name = "debug"; if (!req_json.hasKey(param_name) || req_json[param_name].JSONType() != json::JSON::Class::Boolean) { ret_info = "Bad parameter! Need a boolean type parameter:'" + param_name + "'"; ret_code = 400; } else { bool debug_flag = req_json[param_name].ToBool(); p_log->set_debug(debug_flag); ret_info = "Set debug flag successfully!"; p_log->info("%s %s debug.\n", ret_info.c_str(), debug_flag ? "Open" : "Close"); ret_code = 200; // Store debug flag crust_status_t ret = crust::DataBase::get_instance()->set(DB_DEBUG, std::to_string(debug_flag)); if (CRUST_SUCCESS != ret) { p_log->debug("Cannot store debug flag in db, code:%lx\n", ret); } } ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); goto postcleanup; } // ----- Set config path ----- // cur_path = urlendpoint.base + "/config/add_path"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { int ret_code = 400; std::string ret_info; json::JSON req_json = json::JSON::Load_unsafe((const uint8_t *)req.body().data(), req.body().size()); json::JSON ret_body; if (!p_config->config_file_add_data_paths(req_json)) { ret_info = "Add data paths to config failed!"; p_log->err("%s\n", ret_info.c_str()); ret_code = 400; } else { ret_info = "Change config data path successfully!"; p_log->err("%s\n", ret_info.c_str()); ret_code = 200; } ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); goto postcleanup; } // --- Change srd --- // cur_path = urlendpoint.base + "/srd/change"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON ret_body; int ret_code = 400; std::string ret_info; // Check input parameters json::JSON req_json = json::JSON::Load_unsafe((const uint8_t *)req.body().data(), req.body().size()); std::string param_name = "change"; if (!req_json.hasKey(param_name) || req_json[param_name].JSONType() != json::JSON::Class::Integral) { ret_info = "Bad parameter! Need a integral type parameter:'" + param_name + "'"; ret_code = 400; } else { change_srd_num = req_json[param_name].ToInt(); if (change_srd_num == 0) { ret_info = "Invalid change"; p_log->info("%s\n", ret_info.c_str()); ret_code = 400; } else { crust_status_t crust_status = CRUST_SUCCESS; json::JSON wl_info = EnclaveData::get_instance()->gen_workload(); long srd_complete = wl_info[WL_SRD][WL_SRD_COMPLETE].ToInt(); long srd_remaining_task = wl_info[WL_SRD][WL_SRD_REMAINING_TASK].ToInt(); long disk_avail_for_srd = wl_info[WL_SRD][WL_DISK_AVAILABLE_FOR_SRD].ToInt(); long running_srd_task = get_running_srd_task(); if (change_srd_num > 0) { long avail_space = std::max(disk_avail_for_srd - running_srd_task, (long)0) - srd_remaining_task; long true_increase = std::min(change_srd_num, avail_space); if (true_increase <= 0) { ret_info = "No more srd can be added. Use 'sudo crust tools workload' to check."; ret_code = 400; goto change_end; } change_srd_num = true_increase; } else { long abs_change_srd_num = std::abs(change_srd_num); long avail_space = srd_complete + srd_remaining_task + running_srd_task; long true_decrease = std::min(abs_change_srd_num, avail_space); if (true_decrease <= 0) { ret_info = "No srd space to be deleted. Use 'sudo crust tools workload' to check."; ret_code = 400; goto change_end; } change_srd_num = -true_decrease; } // Start changing srd long real_change = 0; if (SGX_SUCCESS != Ecall_change_srd_task(global_eid, &crust_status, change_srd_num, &real_change)) { ret_info = "Change srd failed! Invoke SGX api failed!"; ret_code = 500; } else { switch (crust_status) { case CRUST_SUCCESS: ret_info = "Change task:" + std::to_string(real_change) + "G has been added, will be executed later."; ret_code = 200; break; case CRUST_SRD_NUMBER_EXCEED: ret_info = "Only " + std::to_string(real_change) + "G srd will be added. Rest srd task exceeds upper limit."; ret_code = 200; break; case CRUST_UPGRADE_IS_UPGRADING: ret_info = "Change srd interface is stopped due to upgrading or exiting"; ret_code = 503; break; default: ret_info = "Unexpected error has occurred!"; ret_code = 500; } } p_log->info("%s\n", ret_info.c_str()); } } change_end: ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_code); res.body() = ret_body.dump(); goto postcleanup; } // --- Delete meaningful file --- // cur_path = urlendpoint.base + "/storage/delete"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON ret_body; int ret_code = 400; std::string ret_info; // Delete file json::JSON req_json = json::JSON::Load_unsafe((const uint8_t *)req.body().data(), req.body().size()); std::string param_name = "cid"; if (!req_json.hasKey(param_name) || req_json[param_name].JSONType() != json::JSON::Class::String) { ret_info = "Bad parameter! Need a string type parameter:'" + param_name + "'"; ret_code = 400; } else { std::string cid = req_json[param_name].ToString(); sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; if (SGX_SUCCESS != (sgx_status = Ecall_delete_file(global_eid, &crust_status, cid.c_str()))) { ret_info = "Delete file '" + cid + "' failed! Invoke SGX API failed! Error code:" + num_to_hexstring(sgx_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } else if (CRUST_SUCCESS == crust_status) { EnclaveData::get_instance()->del_file_info(cid); ret_info = "Deleting file '" + cid + "' successfully"; ret_code = 200; } else if (CRUST_STORAGE_NEW_FILE_NOTFOUND == crust_status) { ret_info = "File '" + cid + "' is not existed in sworker"; ret_code = 404; } else if (CRUST_UPGRADE_IS_UPGRADING == crust_status) { ret_info = "Deleting file '" + cid + "' stoped due to upgrading or exiting"; ret_code = 503; } else { ret_info = "Unexpected error: " + num_to_hexstring(crust_status); ret_code = 500; } } ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); goto postcleanup; } // ----- Seal file start ----- // cur_path = urlendpoint.base + "/storage/seal_start"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON ret_body; int ret_code = 400; std::string ret_info; crust_status_t crust_status = CRUST_SUCCESS; sgx_status_t sgx_status = SGX_SUCCESS; // Delete file json::JSON req_json = json::JSON::Load_unsafe((const uint8_t *)req.body().data(), req.body().size()); std::string param_cid_name = "cid"; std::string param_cid_b58_name = "cid_b58"; if (!req_json.hasKey(param_cid_name) || req_json[param_cid_name].JSONType() != json::JSON::Class::String || !req_json.hasKey(param_cid_b58_name) || req_json[param_cid_b58_name].JSONType() != json::JSON::Class::String) { ret_info = "Bad parameter! Need a string type parameter:'" + param_cid_name + "' or '" + param_cid_b58_name + "'"; ret_code = 400; } else { std::string cid = req_json[param_cid_name].ToString(); std::string cid_b58 = req_json[param_cid_b58_name].ToString(); // Do start seal if (SGX_SUCCESS != (sgx_status = Ecall_seal_file_start(global_eid, &crust_status, cid.c_str(), cid_b58.c_str()))) { ret_info = "Start seal file '%s' failed! Invoke SGX API failed! Error code:" + num_to_hexstring(sgx_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } else if (CRUST_SUCCESS != crust_status) { switch (crust_status) { case CRUST_FILE_NUMBER_EXCEED: ret_info = "Seal file '" + cid + "' failed! No more file can be sealed! File number reachs the upper limit"; p_log->err("%s\n", ret_info.c_str()); ret_code = 500; break; case CRUST_UPGRADE_IS_UPGRADING: ret_info = "Seal file '" + cid + "' stopped due to upgrading or exiting"; p_log->info("%s\n", ret_info.c_str()); ret_code = 503; break; case CRUST_STORAGE_FILE_DUP: ret_info = "This file '" + cid + "' has been sealed"; p_log->info("%s\n", ret_info.c_str()); ret_code = 200; break; case CRUST_STORAGE_FILE_SEALING: ret_info = "Same file '" + cid + "' is being sealed."; p_log->info("%s\n", ret_info.c_str()); ret_code = 200; break; case CRUST_STORAGE_FILE_DELETING: ret_info = "Same file '" + cid + "' is being deleted."; p_log->info("%s\n", ret_info.c_str()); ret_code = 400; break; default: ret_info = "Seal file '" + cid + "' failed! Unexpected error, error code:" + num_to_hexstring(crust_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } } else { ret_info = "Ready for sealing file '" + cid + "', waiting for file block"; p_log->info("%s\n", ret_info.c_str()); ret_code = 200; } } ret_body[HTTP_STATUS_CODE] = std::stoi(num_to_hexstring(crust_status), NULL, 10); ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_code); res.body() = ret_body.dump(); goto postcleanup; } // ----- Seal file ----- // cur_path = urlendpoint.base + "/storage/seal"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON ret_body; int ret_code = 400; std::string ret_info; crust_status_t crust_status = CRUST_SUCCESS; // Parse paramters std::string cid = params_m["cid"]; bool is_link = (params_m["new_block"] == "true"); std::vector<uint8_t> body_vec = req.body(); const uint8_t *sealed_data = (const uint8_t *)body_vec.data(); size_t sealed_data_sz = body_vec.size(); //p_log->info("Dealing with seal request(file cid:'%s')...\n", cid.c_str()); sgx_status_t sgx_status = SGX_SUCCESS; char *index_path = (char *)malloc(IPFS_INDEX_LENGTH); memset(index_path, 0, IPFS_INDEX_LENGTH); if (SGX_SUCCESS != (sgx_status = Ecall_seal_file(global_eid, &crust_status, cid.c_str(), sealed_data, sealed_data_sz, is_link, index_path, IPFS_INDEX_LENGTH))) { ret_info = "Seal file '%s' failed! Invoke SGX API failed! Error code:" + num_to_hexstring(sgx_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } else if (CRUST_SUCCESS != crust_status) { switch (crust_status) { case CRUST_SEAL_DATA_FAILED: ret_info = "Seal file '" + cid + "' failed! Internal error: seal data failed"; p_log->err("%s\n", ret_info.c_str()); ret_code = 500; break; case CRUST_UPGRADE_IS_UPGRADING: ret_info = "Seal file '" + cid + "' stopped due to upgrading or exiting"; p_log->info("%s\n", ret_info.c_str()); ret_code = 503; break; case CRUST_STORAGE_NEW_FILE_NOTFOUND: ret_info = "Seal file '" + cid + "' failed, no request or file has been removed"; p_log->debug("%s\n", ret_info.c_str()); ret_code = 500; break; case CRUST_STORAGE_NO_ENOUGH_SPACE: ret_info = "Seal file '" + cid + "' failed, no enough space"; p_log->err("%s\n", ret_info.c_str()); ret_code = 500; break; default: ret_info = "Seal file '" + cid + "' failed! Unexpected error, error code:" + num_to_hexstring(crust_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } } else { ret_info = "Seal file '" + cid + "' successfully"; //p_log->info("%s\n", ret_info.c_str()); ret_code = 200; ret_body[HTTP_IPFS_INDEX_PATH] = std::string(index_path); } free(index_path); ret_body[HTTP_STATUS_CODE] = std::stoi(num_to_hexstring(crust_status), NULL, 10); ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_code); res.body() = ret_body.dump(); goto postcleanup; } // ----- Seal file end ----- // cur_path = urlendpoint.base + "/storage/seal_end"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON ret_body; int ret_code = 400; std::string ret_info; crust_status_t crust_status = CRUST_SUCCESS; sgx_status_t sgx_status = SGX_SUCCESS; // Delete file json::JSON req_json = json::JSON::Load_unsafe((const uint8_t *)req.body().data(), req.body().size()); std::string param_name = "cid"; if (!req_json.hasKey(param_name) || req_json[param_name].JSONType() != json::JSON::Class::String) { ret_info = "Bad parameter! Need a string type parameter:'" + param_name + "'"; ret_code = 400; } else { std::string cid = req_json[param_name].ToString(); if (SGX_SUCCESS != (sgx_status = Ecall_seal_file_end(global_eid, &crust_status, cid.c_str()))) { ret_info = "Start seal file '%s' failed! Invoke SGX API failed! Error code:" + num_to_hexstring(sgx_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } else if (CRUST_SUCCESS != crust_status) { switch (crust_status) { case CRUST_UPGRADE_IS_UPGRADING: ret_info = "Seal file '" + cid + "' stopped due to upgrading or exiting"; p_log->info("%s\n", ret_info.c_str()); ret_code = 503; break; case CRUST_STORAGE_NEW_FILE_NOTFOUND: ret_info = "File '" + cid + "' is not being sealed"; p_log->info("%s\n", ret_info.c_str()); ret_code = 404; break; case CRUST_STORAGE_INCOMPLETE_BLOCK: ret_info = "Seal file '" + cid + "' failed due to incomplete file blocks"; p_log->info("%s\n", ret_info.c_str()); ret_code = 500; break; default: ret_info = "Seal file '" + cid + "' failed! Error code:" + num_to_hexstring(crust_status); p_log->info("%s\n", ret_info.c_str()); ret_code = 500; } } else { ret_info = "Seal file '" + cid + "' successfully"; p_log->info("%s\n", ret_info.c_str()); ret_code = 200; } } ret_body[HTTP_STATUS_CODE] = std::stoi(num_to_hexstring(crust_status), NULL, 10); ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_code); res.body() = ret_body.dump(); goto postcleanup; } // ----- Unseal data ----- // cur_path = urlendpoint.base + "/storage/unseal"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { std::string ret_info; int ret_code = 400; //p_log->info("Dealing with unseal request...\n"); // Parse parameters json::JSON req_json = json::JSON::Load_unsafe((const uint8_t *)req.body().data(), req.body().size()); std::string param_name = "path"; if (!req_json.hasKey(param_name) || req_json[param_name].JSONType() != json::JSON::Class::String) { ret_info = "Bad parameter! Need a string type parameter:'" + param_name + "'"; ret_code = 400; } else { std::string index_path = req_json[param_name].ToString(); // ----- Unseal file ----- // crust_status_t crust_status = CRUST_SUCCESS; sgx_status_t sgx_status = SGX_SUCCESS; if (index_path == EMPTY_BLOCK_FLAG) { ret_info = "Unseal data successfully!"; ret_code = 200; res.body().clear(); res.result(ret_code); } else { if (!is_file_exist(index_path.c_str(), STORE_TYPE_FILE)) { std::string cid_header = index_path.substr(0, index_path.find_last_of('/')); if (cid_header.size() <= UUID_LENGTH * 2) { ret_info = "Malwared index path:" + index_path; ret_code = 404; } else { std::string cid = cid_header.substr(UUID_LENGTH * 2, cid_header.size() - (UUID_LENGTH * 2)); std::string type; bool exist = ed->find_file_type(cid, type); if (!exist || (exist && type.compare(FILE_TYPE_PENDING) == 0)) { ret_info = "Requested cid:'" + cid + "' is not existed."; ret_code = 404; } else { ret_info = "File block:'" + index_path + "' is lost"; ret_code = 410; } } p_log->debug("%s\n", ret_info.c_str()); } else { size_t decrypted_data_sz = get_file_size(index_path.c_str(), STORE_TYPE_FILE); uint8_t *p_decrypted_data = (uint8_t *)malloc(decrypted_data_sz); size_t decrypted_data_sz_r = 0; memset(p_decrypted_data, 0, decrypted_data_sz); Defer def_decrypted_data([&p_decrypted_data](void) { free(p_decrypted_data); }); if (SGX_SUCCESS != (sgx_status = Ecall_unseal_file(global_eid, &crust_status, index_path.c_str(), p_decrypted_data, decrypted_data_sz, &decrypted_data_sz_r))) { ret_info = "Unseal failed! Invoke SGX API failed! Error code:" + num_to_hexstring(sgx_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } else { if (CRUST_SUCCESS == crust_status) { ret_info = "Unseal data successfully!"; ret_code = 200; //p_log->info("%s\n", ret_info.c_str()); res.body().clear(); res.body().append(reinterpret_cast<char *>(p_decrypted_data), decrypted_data_sz_r); res.result(ret_code); } else { switch (crust_status) { case CRUST_UNSEAL_DATA_FAILED: ret_info = "Unseal data failed! SGX unseal data failed!"; p_log->err("%s\n", ret_info.c_str()); ret_code = 400; break; case CRUST_UPGRADE_IS_UPGRADING: ret_info = "Unseal file stoped due to upgrading or exiting"; p_log->info("%s\n", ret_info.c_str()); ret_code = 503; break; default: ret_info = "Unseal data failed! Error code:" + num_to_hexstring(crust_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 404; } } } } } } if (200 != ret_code) { json::JSON ret_body; ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); res.body() = ret_body.dump(); } goto postcleanup; } // ----- Recover illegal file ----- // cur_path = urlendpoint.base + "/file/recover_illegal"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { std::string ret_info; int ret_code = 400; sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; json::JSON req_json = json::JSON::Load(&crust_status, req.body().data(), req.body().size()); if (CRUST_SUCCESS != crust_status) { ret_info = "Invalid parameter! Need a json format parameter like:{\"added_files\":[\"Qmxxx\"],\"deleted_files\":[\"Qmxxx\"]}"; p_log->err("%s\n", ret_info.c_str()); ret_code = 400; } else { if ((!req_json.hasKey(WORKREPORT_FILES_ADDED) && !req_json.hasKey(WORKREPORT_FILES_DELETED)) || (req_json.hasKey(WORKREPORT_FILES_ADDED) && req_json[WORKREPORT_FILES_ADDED].JSONType() != json::JSON::Class::Array) || (req_json.hasKey(WORKREPORT_FILES_DELETED) && req_json[WORKREPORT_FILES_DELETED].JSONType() != json::JSON::Class::Array)) { ret_info = "Invalid parameter! Need a json format parameter like:{\"added_files\":[\"Qmxxx\"],\"deleted_files\":[\"Qmxxx\"]}"; p_log->err("%s\n", ret_info.c_str()); ret_code = 400; } else { if (SGX_SUCCESS != (sgx_status = Ecall_recover_illegal_file(global_eid, &crust_status, req.body().data(), req.body().size()))) { ret_info = "Recover illegal file failed! Invoke SGX API failed! Error code:" + num_to_hexstring(sgx_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } else { if (CRUST_SUCCESS != crust_status) { ret_info = "Unexpected error:" + num_to_hexstring(crust_status); p_log->err("%s\n", ret_info.c_str()); ret_code = 500; } else { ret_info = "Recover illegal file done."; p_log->info("%s\n", ret_info.c_str()); ret_code = 200; } } } } json::JSON ret_body; ret_body[HTTP_STATUS_CODE] = ret_code; ret_body[HTTP_MESSAGE] = ret_info; res.result(ret_body[HTTP_STATUS_CODE].ToInt()); std::string ret_str = ret_body.dump(); remove_char(ret_str, '\\'); res.body() = ret_str; goto postcleanup; } postcleanup: res.content_length(res.body().size()); res.keep_alive(req.keep_alive()); return send(std::move(res)); } } #endif /* !_CRUST_API_HANDLER_H_ */
52,798
C++
.h
1,151
29.991312
182
0.465288
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,391
EnclaveData.h
crustio_crust-sworker/src/app/process/EnclaveData.h
#ifndef _APP_ENCLAVE_DATA_H_ #define _APP_ENCLAVE_DATA_H_ #include <stdio.h> #include <string> #include <mutex> #include <unordered_map> #include "Resource.h" #include "SafeLock.h" #include "Log.h" #include "Common.h" #include "DataBase.h" #include "Srd.h" class EnclaveData { public: static EnclaveData *get_instance(); std::string get_enclave_id_info(); void set_enclave_id_info(std::string id_info); std::string get_upgrade_data(); void set_upgrade_data(std::string data); upgrade_status_t get_upgrade_status(); void set_upgrade_status(upgrade_status_t status); void set_workreport(const uint8_t *data, size_t data_size); std::string get_workreport(); // File information void add_file_info(const std::string &cid, std::string type, std::string info); std::string get_file_info(std::string cid); void change_file_type(const std::string &cid, std::string old_type, std::string new_type); std::string get_file_info_all(); std::string get_file_info_by_type(std::string type); std::string _get_file_info_by_type(std::string type, std::string pad, bool raw); size_t get_pending_files_size_all(); void del_file_info(std::string cid); void del_file_info(std::string cid, std::string type); bool find_file_type(std::string cid, std::string &type); bool find_file_type_nolock(std::string cid, std::string &type); void restore_file_info(const uint8_t *data, size_t data_size); void set_srd_info(const uint8_t *data, size_t data_size); void add_pending_file_size(std::string cid, long size); long get_pending_file_size(std::string cid); void del_pending_file_size(std::string cid); json::JSON get_srd_info(); // Get workload std::string gen_workload_str(long srd_task = 0); json::JSON gen_workload_for_print(long srd_task = 0); json::JSON gen_workload(long srd_task = 0); // For uuid and disk path void construct_uuid_disk_path_map(); void set_uuid_disk_path_map(std::string uuid, std::string path); std::string get_disk_path(std::string uuid); std::string get_uuid(std::string path); bool is_disk_exist(std::string path); bool is_uuid_exist(std::string uuid); private: static EnclaveData *enclavedata; EnclaveData() : enclave_id_info("") , upgrade_data("") , upgrade_status(UPGRADE_STATUS_NONE) {} std::string get_file_info_item(std::string cid, std::string &info, bool raw); // Show information std::set<std::string> file_spec_type = { FILE_TYPE_PENDING, FILE_TYPE_VALID, FILE_TYPE_LOST, }; // Store enclave identity information std::string enclave_id_info; std::mutex enclave_id_info_mutex; // Upgrade data std::string upgrade_data; std::mutex upgrade_data_mutex; // Upgrade status upgrade_status_t upgrade_status; std::mutex upgrade_status_mutex; // Sealed file map std::map<std::string, std::map<std::string, std::string>> sealed_file; std::mutex sealed_file_mutex; // Pending file std::unordered_map<std::string, long> pending_file_size_um; std::mutex pending_file_size_um_mutex; // Srd info json::JSON srd_info; std::mutex srd_info_mutex; // For uuid and disk path std::unordered_map<std::string, std::string> uuid_to_disk_path; std::unordered_map<std::string, std::string> disk_path_to_uuid; std::mutex uuid_disk_path_map_mutex; // For workreport std::string workreport; std::mutex workreport_mutex; }; #endif /* !_APP_ENCLAVE_DATA_H_ */
3,571
C++
.h
93
33.817204
94
0.682906
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,392
EntryNetwork.h
crustio_crust-sworker/src/app/process/EntryNetwork.h
#ifndef _CRUST_ENTRY_NETWORK_H_ #define _CRUST_ENTRY_NETWORK_H_ #include <string> #include <stdlib.h> #include "Resource.h" #include "Chain.h" #include "Common.h" #include "Config.h" #include "Log.h" #include "SgxSupport.h" #include "FormatUtils.h" #include "CrustStatus.h" #include "EnclaveData.h" #include "HttpClient.h" // For EPID #include <sgx_eid.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> // For ECDSA #include "sgx_report.h" #include "sgx_dcap_ql_wrapper.h" #include "sgx_pce.h" #include "sgx_error.h" #include "sgx_quote_3.h" #include "sgx_ql_quote.h" #include "sgx_dcap_quoteverify.h" #include "sgx_utils.h" #include "sgx_urts.h" #define OPT_ISSET(x, y) x &y #define _rdrand64_step(x) ({ unsigned char err; asm volatile("rdrand %0; setc %1":"=r"(*x), "=qm"(err)); err; }) #define OPT_PSE 0x01 #define OPT_NONCE 0x02 #define OPT_LINK 0x04 #define OPT_PUBKEY 0x08 crust_status_t entry_network(); #endif /* !_CRUST_ENTRY_NETWORK_H_ */
992
C++
.h
37
25.648649
112
0.726027
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,393
Validator.h
crustio_crust-sworker/src/app/process/Validator.h
#ifndef _APP_VALIDATOR_H_ #define _APP_VALIDATOR_H_ #include <vector> #include "Config.h" #include "Ctpl.h" #define VALIDATE_MAX_THREAD_NUM 8 class Validator { public: static Validator *get_instance(); void validate_file(); void validate_srd(); private: Validator(); static Validator *validator; ctpl::thread_pool *validate_pool; std::vector<std::shared_ptr<std::future<void>>> validate_tasks_v; }; #endif /* ! _APP_VALIDATOR_H_ */
466
C++
.h
19
21.736842
69
0.709751
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,394
Process.h
crustio_crust-sworker/src/app/process/Process.h
#ifndef _CRUST_PROCESS_H_ #define _CRUST_PROCESS_H_ #include <stdlib.h> #include <stdio.h> #include <limits.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <unistd.h> #include <algorithm> #include <mutex> #include <map> #include <fstream> #include <future> #include <chrono> #include <sgx_key_exchange.h> #include <sgx_report.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include <sgx_error.h> #include <sgx_eid.h> #include <sgx_urts.h> #include <sgx_capable.h> #include "SgxSupport.h" #include "ECalls.h" #include "Config.h" #include "FormatUtils.h" #include "Common.h" #include "Resource.h" #include "FileUtils.h" #include "Log.h" #include "WorkReport.h" #include "Srd.h" #include "DataBase.h" #include "EntryNetwork.h" #include "Chain.h" typedef void (*task_func_t)(void); int process_run(); #endif /* !_CRUST_PROCESS_H_ */
902
C++
.h
40
21.4
34
0.738318
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,395
WorkReport.h
crustio_crust-sworker/src/app/process/WorkReport.h
#ifndef _CRUST_WORK_REPORT_H_ #define _CRUST_WORK_REPORT_H_ #include <string> #include <stdlib.h> #include <time.h> #include <sgx_eid.h> #include "ECalls.h" #include "Config.h" #include "Log.h" #include "Chain.h" #include "CrustStatus.h" #include "FormatUtils.h" #include "EnclaveData.h" void work_report_loop(void); #endif /* !_CRUST_WORK_REPORT_H_ */
358
C++
.h
15
22.533333
35
0.736686
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,396
Srd.h
crustio_crust-sworker/src/app/process/Srd.h
#ifndef _APP_SRD_H_ #define _APP_SRD_H_ #include <sys/types.h> #include <sys/stat.h> #include <sys/vfs.h> #include <string> #include <vector> #include <unordered_set> #include "Config.h" #include "FileUtils.h" #include "FormatUtils.h" #include "DataBase.h" #include "Log.h" #include "EnclaveData.h" #include "Ctpl.h" #include "HttpClient.h" #include "../enclave/utils/Defer.h" // Indicates maximal srd reserved space #define DEFAULT_SRD_RESERVED 50 // Indicates srd upgrade timeout #define SRD_UPGRADE_TIMEOUT 20 #define SRD_UPGRADE_INFO "srd_upgrade_info" #define SRD_UPGRADE_INFO_TIMEOUT "timeout" #define SRD_UPGRADE_INFO_SRD "srd" json::JSON get_disk_info(); json::JSON get_increase_srd_info(long &change); #if defined(__cplusplus) extern "C" { #endif crust_status_t srd_change(long change); void srd_check_reserved(void); size_t get_reserved_space(); void set_running_srd_task(long srd_task); long get_running_srd_task(); void decrease_running_srd_task(); bool check_or_init_disk(std::string path); #if defined(__cplusplus) } #endif #endif /* !_APP_SRD_H_*/
1,072
C++
.h
41
24.926829
47
0.760274
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,397
FileUtils.h
crustio_crust-sworker/src/app/utils/FileUtils.h
#ifndef _CRUST_FILE_UTILS_H_ #define _CRUST_FILE_UTILS_H_ #include <iostream> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <dirent.h> #include <vector> #include <stack> #include <unordered_map> #include <string.h> #include <sys/stat.h> #include <sys/vfs.h> #include <errno.h> #include <sys/types.h> #include <experimental/filesystem> #include <exception> #include "Config.h" #include "DataBase.h" std::vector<std::string> get_files_under_path(const std::string &path); std::vector<std::string> get_folders_under_path(const std::string &path); int rm_dir(const std::string &dir_full_path); int rm(const std::string &path); size_t get_free_space_under_directory(const std::string &path); crust_status_t rename_dir(const std::string &old_path, const std::string &new_path); crust_status_t create_directory(const std::string &path); std::vector<std::string> get_sub_folders_and_files(const char *path); crust_status_t get_file(const char *path, uint8_t **p_data, size_t *data_size); long get_file_size(const char *path, store_type_t type); bool is_file_exist(const char *path, store_type_t type); std::string get_real_path_by_type(const char *path, store_type_t type); crust_status_t save_file(const char *path, const uint8_t *data, size_t data_size); crust_status_t save_file_ex(const char *path, const uint8_t *data, size_t data_size, mode_t mode, save_file_type_t type); size_t get_total_space_under_dir_k(const std::string &path); size_t get_total_space_under_dir_m(const std::string &path); size_t get_total_space_under_dir_g(const std::string &path); size_t get_avail_space_under_dir_k(const std::string &path); size_t get_avail_space_under_dir_m(const std::string &path); size_t get_avail_space_under_dir_g(const std::string &path); size_t get_file_or_folder_size(const std::string &path); size_t get_file_size_by_cid(const std::string &cid); #endif /* !_CRUST_FILE_UTILS_H_ */
1,908
C++
.h
42
44.333333
121
0.745972
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,398
SafeLock.h
crustio_crust-sworker/src/app/utils/SafeLock.h
#ifndef _CRUST_SAFELOCK_H_ #define _CRUST_SAFELOCK_H_ #include <mutex> class SafeLock { public: SafeLock(std::mutex &mutex): _mutex(mutex), lock_time(0) {} ~SafeLock(); void lock(); void unlock(); private: std::mutex &_mutex; int lock_time; }; #endif /* !_CRUST_SAFELOCK_H_ */
306
C++
.h
15
17.466667
63
0.653846
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,399
Common.h
crustio_crust-sworker/src/app/utils/Common.h
#ifndef _COMMON_H_ #define _COMMON_H_ /* Help keep our console messages clean and organzied */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdarg.h> #include <cstdio> #include <cstring> #include <string> #include <vector> #include <algorithm> #include <random> #include <chrono> #include <boost/algorithm/string.hpp> #include <sgx_eid.h> #include <sgx_error.h> #include "Resource.h" #include "CrustStatus.h" #include "FormatUtils.h" #include "MerkleTree.h" #include "Log.h" #include "../enclave/utils/Json.h" using seconds_t = std::chrono::seconds; #if defined(__cplusplus) extern "C" { #endif struct UrlEndPoint { std::string ip; std::string base; int port = -1; }; UrlEndPoint get_url_end_point(std::string url); void remove_chars_from_string(std::string &str, const char *chars_to_remove); MerkleTree *deserialize_merkle_tree_from_json(json::JSON tree_json); json::JSON serialize_merkletree_to_json(MerkleTree *root); void free_merkletree(MerkleTree *root); std::string flat_urlformat(std::string &url); bool is_number(const std::string &s); void replace(std::string &data, std::string org_str, std::string det_str); void remove_char(std::string &data, char c); void srand_string(std::string seed); void print_logo(const char *logo, const char *color); void print_attention(); bool sleep_interval(uint32_t time, std::function<bool()> func); std::string float_to_string(double num); void read_rand(uint8_t *buf, size_t buf_size); decltype(seconds_t().count()) get_seconds_since_epoch(); std::string get_time_diff_humanreadable(long time); std::string get_file_size_humanreadable(size_t size); sgx_status_t safe_ecall_store2(sgx_enclave_id_t eid, crust_status_t *status, ecall_store_type_t t, const uint8_t *u, size_t s); #if defined(__cplusplus) } #endif #endif
1,909
C++
.h
57
30.350877
131
0.711726
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,400
FormatUtils.h
crustio_crust-sworker/src/app/utils/FormatUtils.h
#ifndef _CRUST_FORMAT_UTILS_H_ #define _CRUST_FORMAT_UTILS_H_ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <algorithm> #include <string.h> #include <string> #include <openssl/bio.h> #include <openssl/evp.h> #ifdef __cplusplus extern "C" { #endif int char_to_int(char input); uint8_t *hex_string_to_bytes(const char *src, size_t len); int from_hexstring(unsigned char *dest, const void *src, size_t len); void print_hexstring(const void *vsrc, size_t len); char *hexstring(const void *src, size_t len); std::string hexstring_safe(const void *vsrc, size_t len); std::string num_to_hexstring(size_t num); char *base64_encode(const char *msg, size_t sz); char *base64_decode(const char *msg, size_t *sz); #ifdef __cplusplus }; #endif #endif /* !_CRUST_FORMAT_UTILS_H_ */
856
C++
.h
28
28.035714
73
0.706456
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,401
SgxSupport.h
crustio_crust-sworker/src/app/utils/SgxSupport.h
#ifndef _SGX_SUPPORT_H_ #define _SGX_SUPPORT_H_ #pragma once #include <limits.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sgx_edger8r.h> #include <sgx_uae_launch.h> #include <sgx_uae_epid.h> #include <sgx_uae_quote_ex.h> #include <sgx_urts.h> #include <sgx_urts.h> #include <sgx_capable.h> #include "Resource.h" #ifdef _WIN32 #include <Windows.h> #else #include <dlfcn.h> #endif #define SGX_SUPPORT_UNKNOWN 0x00000000 #define SGX_SUPPORT_NO 0x08000000 #define SGX_SUPPORT_YES 0x00000001 #define SGX_SUPPORT_ENABLED 0x00000002 #define SGX_SUPPORT_REBOOT_REQUIRED 0x00000004 #define SGX_SUPPORT_ENABLE_REQUIRED 0x00000008 #ifdef __cplusplus extern "C" { #endif int get_sgx_support(void); int get_quote_size(sgx_status_t *status, uint32_t *quote_size); int have_sgx_psw(void); void *get_sgx_ufunction(const char *name); /* Returns func pointer */ #ifdef __cplusplus } #endif #endif /* !_SGX_SUPPORT_H_ */
1,001
C++
.h
40
23.375
73
0.752892
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,402
Resource.h
crustio_crust-sworker/src/app/include/Resource.h
#ifndef _CRUST_RESOURCE_H_ #define _CRUST_RESOURCE_H_ #include <stdint.h> #include "Parameter.h" #define VERSION "2.0.1" #define CRUST_INST_DIR "/opt/crust/crust-sworker/" VERSION #define ENCLAVE_FILE_PATH CRUST_INST_DIR "/etc/enclave.signed.so" #define SGX_WL_FILE_PATH CRUST_INST_DIR "/etc/sgx_white_list_cert.bin" #define HTTP_BODY_LIMIT 524288000 /* 500*1024*1024 */ #define WEB_TIMEOUT 7200 #define DB_DEBUG "debug_flag" // For upgrade typedef enum _upgrade_status_t { UPGRADE_STATUS_NONE, // No upgrade UPGRADE_STATUS_STOP_WORKREPORT, // Block work-report UPGRADE_STATUS_PROCESS, // Processing running tasks UPGRADE_STATUS_END, // Finish running tasks and generate uprade data successfully UPGRADE_STATUS_COMPLETE, // Finish generating upgrade data UPGRADE_STATUS_EXIT, // Will exit process } upgrade_status_t; const uint32_t UPGRADE_START_TRYOUT = BLOCK_INTERVAL * REPORT_SLOT * 5; const uint32_t UPGRADE_META_TRYOUT = BLOCK_INTERVAL * REPORT_SLOT; const uint32_t UPGRADE_COMPLETE_TRYOUT = BLOCK_INTERVAL * 10; #define ID_METADATA_OLD "metadata_old" // For workload #define WL_DISK_AVAILABLE "disk_available" #define WL_DISK_AVAILABLE_FOR_SRD "disk_available_for_srd" #define WL_DISK_RESERVED "disk_reserved" #define WL_DISK_VOLUME "disk_volume" #define WL_SYS_DISK_AVAILABLE "sys_disk_available" #define WL_DISK_PATH "disk_path" #define WL_DISK_USE "disk_use" #define WL_DISK_UUID "disk_uuid" // For srd #define DISK_SWORKER_DIR "/sworker" #define DISK_SRD_DIR DISK_SWORKER_DIR "/srd" #define DISK_FILE_DIR DISK_SWORKER_DIR "/files" #define DISK_UUID_FILE DISK_SWORKER_DIR "/uuid" #define SRD_THREAD_NUM 8 // For print #define PRINT_GAP 20 #define RED "\033[0;31m" #define HRED "\033[1;31m" #define GREEN "\033[0;32m" #define HGREEN "\033[1;32m" #define NC "\033[0m" const char* ATTENTION_LOGO = " ___ __ __ __ _ __ __ __\n" " / | / /_/ /____ ____ / /_(_)___ ____ / / / / / /\n" " / /| |/ __/ __/ _ %/ __ %/ __/ / __ %/ __ % / / / / / / \n" " / ___ / /_/ /_/ __/ / / / /_/ / /_/ / / / / /_/ /_/ /_/ \n" "/_/ |_%__/%__/%___/_/ /_/%__/_/%____/_/ /_/ (_) (_) (_) \n"; const char* UPGRADE_SUCCESS_LOGO = " __ ______ __________ ___ ____ ______ _____ __ ______________________________ ________ ____ ____ __ __\n" " / / / / __ %/ ____/ __ %/ | / __ %/ ____/ / ___// / / / ____/ ____/ ____/ ___/ ___// ____/ / / / / / /% %/ / / /\n" " / / / / /_/ / / __/ /_/ / /| | / / / / __/ %__ %/ / / / / / / / __/ %__ %%__ %/ /_ / / / / / / / % / / / \n" "/ /_/ / ____/ /_/ / _, _/ ___ |/ /_/ / /___ ___/ / /_/ / /___/ /___/ /___ ___/ /__/ / __/ / /_/ / /___/ /___/ / /_/ \n" "%____/_/ %____/_/ |_/_/ |_/_____/_____/ /____/%____/%____/%____/_____//____/____/_/ %____/_____/_____/_/ (_) \n"; const char* UPGRADE_FAILED_LOGO = " __ ______ __________ ___ ____ ______ _________ ______ __________ __ __ __\n" " / / / / __ %/ ____/ __ %/ | / __ %/ ____/ / ____/ | / _/ / / ____/ __ % / / / / / /\n" " / / / / /_/ / / __/ /_/ / /| | / / / / __/ / /_ / /| | / // / / __/ / / / / / / / / / / \n" "/ /_/ / ____/ /_/ / _, _/ ___ |/ /_/ / /___ / __/ / ___ |_/ // /___/ /___/ /_/ / /_/ /_/ /_/ \n" "%____/_/ %____/_/ |_/_/ |_/_____/_____/ /_/ /_/ |_/___/_____/_____/_____/ (_) (_) (_) \n"; // Webserver return format #define HTTP_STATUS_CODE "status_code" #define HTTP_MESSAGE "message" #define HTTP_IPFS_INDEX_PATH "path" typedef enum _save_file_type_t { SF_NONE, SF_CREATE_DIR, } save_file_type_t; #endif /* !_CRUST_RESOURCE_H_ */
3,723
C++
.h
75
48
127
0.439582
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,403
Chain.h
crustio_crust-sworker/src/app/chain/Chain.h
#ifndef _CRUST_CHAIN_H_ #define _CRUST_CHAIN_H_ #include <string> #include "Common.h" #include "Log.h" #include "Config.h" #include "HttpClient.h" namespace crust { struct BlockHeader { size_t number; /* Current block number */ std::string hash; /* Current block hash */ }; class Chain { private: Chain(std::string url, std::string password_tmp, std::string backup_tmp, bool is_offline); std::string url; /* Request url */ std::string password; /* The password of chain account */ std::string backup; /* The backup of chain account */ bool is_offline; /* Offline mode */ size_t offline_block_height; /* Base offline block */ std::mutex offline_block_height_mutex; static Chain *chain; public: static Chain *get_instance(); bool get_block_header(BlockHeader &block_header); std::string get_block_hash(size_t block_number); std::string get_swork_code(); bool post_epid_identity(std::string identity); bool post_ecdsa_quote(std::string quote); bool post_ecdsa_identity(std::string identity); std::string get_ecdsa_verify_result(); bool post_sworker_work_report(std::string work_report); bool is_online(void); bool is_syncing(void); bool wait_for_running(void); size_t get_offline_block_height(void); void add_offline_block_height(size_t h); ~Chain(); }; } // namespace crust #endif /* !_CRUST_CHAIN_H_ */
1,463
C++
.h
44
29.840909
94
0.670205
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,404
Config.h
crustio_crust-sworker/src/app/config/Config.h
#ifndef _CRUST_CONFIG_H_ #define _CRUST_CONFIG_H_ #include <stdio.h> #include <string> #include <fstream> #include <omp.h> #include <set> #include <sgx_urts.h> #include "Resource.h" #include "../enclave/utils/Json.h" #include "../enclave/utils/Defer.h" #include "Common.h" #include "Srd.h" // ----- IAS CONFIG ----- // #define IAS_LINKABLE false #define IAS_RANDOM_NONCE true #define IAS_BASE_URL "https://api.trustedservices.intel.com" #if SGX_DEBUG_FLAG == 1 #define IAS_SPID "138D059F6C7587BAFFFA0961FFB38002" #define IAS_PRIMARY_SUBSCRIPTION_KEY "1217773e5a82410f98ee70aa1700f599" #define IAS_SECONDARY_SUBSCRIPTION_KEY "9fdebd5027cd4a57a1eb23d818e7b2e7" #define IAS_REPORT_PATH "/sgx/dev/attestation/v4/report" #else #define IAS_SPID "668D353F661978655C9D6820CF93B66B" #define IAS_PRIMARY_SUBSCRIPTION_KEY "80a0aa3b45124b8c8ba937ff9180a226" #define IAS_SECONDARY_SUBSCRIPTION_KEY "d9df4c30d1db412c9cff3823e30ebb80" #define IAS_REPORT_PATH "/sgx/attestation/v4/report" #endif #define IAS_FLAGS 0 #define IAS_API_DEF_VERSION 3 #define DCAP_BASE_URL "https://dcap-attestation.crust.network" #define DCAP_REPORT_PATH "/attestation/report" class Config { public: // base information std::string base_path; /* sworker base path */ std::string db_path; /* DB path */ std::string base_url; /* External API base url */ int websocket_thread_num; /* WebSocket thread number */ int srd_thread_num; /* srd srd files thread number */ // crust storage std::string ipfs_url; /* ipfs url */ // crust chain std::string chain_api_base_url; /* Used to connect to Crust API */ std::string chain_address; /* The address of crust chain account */ std::string chain_account_id; /* The account id(hex string) of crust chain account */ std::string chain_password; /* The password of crust chain account */ std::string chain_backup; /* The backup of crust chain account */ // crust dcap service std::string dcap_base_url; /* The Crust DCAP Attestation Service Base URL */ std::string dcap_report_path; /* The Crust DCAP Attestation Service Report Path */ void show(void); static Config *get_instance(); std::string get_config_path(); bool is_valid_or_normal_disk(const std::string &path); void refresh_data_paths(); std::vector<std::string> get_data_paths(); bool config_file_add_data_paths(const json::JSON &paths); private: static Config *config; Config() {} Config(const Config &); bool unique_paths(); bool init(std::string path); void sort_data_paths(); bool is_valid_data_path(const std::string &path); Config& operator = (const Config &); std::string sys_fsid; std::vector<std::string> data_paths; /* data path */ std::mutex data_paths_mutex; std::vector<std::string> org_data_paths; std::mutex org_data_paths_mutex; }; #endif /* !_CRUST_CONFIG_H_ */
3,012
C++
.h
75
36.946667
91
0.693046
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,405
Log.h
crustio_crust-sworker/src/app/log/Log.h
#ifndef _CRUST_LOG_H_ #define _CRUST_LOG_H_ #include <stdio.h> #include <sys/time.h> #include <stdlib.h> #include <time.h> #include <stdarg.h> #include <string> #include <mutex> #include "Resource.h" #define CRUST_LOG_BUF_SIZE 33554432 /* 32*1024*1024 */ #define CRUST_LOG_INFO_TAG "INFO" #define CRUST_LOG_WARN_TAG "WARN" #define CRUST_LOG_ERR_TAG "ERROR" #define CRUST_LOG_DEBUG_TAG "DEBUG" namespace crust { class Log { public: static Log *log; static Log *get_instance(); void set_debug(bool flag); void info(const char *format, ...); void warn(const char *format, ...); void err(const char *format, ...); void debug(const char *format, ...); bool get_debug_flag(); void restore_debug_flag(); private: void base_log(std::string log_data, std::string tag); bool debug_flag; std::mutex debug_flag_mutex; char log_buf[CRUST_LOG_BUF_SIZE]; Log(void); }; } // namespace crust #endif /* !_CRUST_LOG_H_ */
968
C++
.h
38
22.789474
57
0.682213
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,406
ECalls.h
crustio_crust-sworker/src/app/ecalls/ECalls.h
#ifndef _ECALLS_H_ #define _ECALLS_H_ #include "EnclaveQueue.h" #if defined(__cplusplus) extern "C" { #endif sgx_status_t Ecall_srd_increase(sgx_enclave_id_t eid, crust_status_t *status, const char *uuid); sgx_status_t Ecall_srd_decrease(sgx_enclave_id_t eid, size_t *size, size_t change); sgx_status_t Ecall_srd_remove_space(sgx_enclave_id_t eid, const char *data, size_t data_size); sgx_status_t Ecall_change_srd_task(sgx_enclave_id_t eid, crust_status_t *status, long change, long *real_change); sgx_status_t Ecall_main_loop(sgx_enclave_id_t eid); sgx_status_t Ecall_stop_all(sgx_enclave_id_t eid); sgx_status_t Ecall_restore_metadata(sgx_enclave_id_t eid, crust_status_t *status); sgx_status_t Ecall_cmp_chain_account_id(sgx_enclave_id_t eid, crust_status_t *status, const char *account_id, size_t len); sgx_status_t Ecall_gen_and_upload_work_report(sgx_enclave_id_t eid, crust_status_t *status, const char *block_hash, size_t block_height); sgx_status_t Ecall_gen_key_pair(sgx_enclave_id_t eid, sgx_status_t *status, const char *account_id, size_t len); sgx_status_t Ecall_get_quote_report(sgx_enclave_id_t eid, sgx_status_t *status, sgx_report_t *report, sgx_target_info_t *target_info); sgx_status_t Ecall_gen_sgx_measurement(sgx_enclave_id_t eid, sgx_status_t *status); sgx_status_t Ecall_gen_upload_epid_identity(sgx_enclave_id_t eid, crust_status_t *status, char **IASReport, size_t len); sgx_status_t Ecall_gen_upload_ecdsa_quote(sgx_enclave_id_t eid, crust_status_t *status, uint8_t *p_quote, uint32_t quote_size); sgx_status_t Ecall_gen_upload_ecdsa_identity(sgx_enclave_id_t eid, crust_status_t *status, const char *report, uint32_t size); sgx_status_t Ecall_seal_file_start(sgx_enclave_id_t eid, crust_status_t *status, const char *cid, const char *cid_b58); sgx_status_t Ecall_seal_file(sgx_enclave_id_t eid, crust_status_t *status, const char *cid, const uint8_t *data, size_t data_size, bool is_link, char *path, size_t path_size); sgx_status_t Ecall_seal_file_end(sgx_enclave_id_t eid, crust_status_t *status, const char *cid); sgx_status_t Ecall_unseal_file(sgx_enclave_id_t eid, crust_status_t *status, const char *path, uint8_t *p_decrypted_data, size_t decrypted_data_size, size_t *p_decrypted_data_size); sgx_status_t Ecall_delete_file(sgx_enclave_id_t eid, crust_status_t *status, const char *hash); sgx_status_t Ecall_id_get_info(sgx_enclave_id_t eid); sgx_status_t Ecall_recover_illegal_file(sgx_enclave_id_t eid, crust_status_t *status, const uint8_t *data, size_t data_size); sgx_status_t Ecall_enable_upgrade(sgx_enclave_id_t eid, crust_status_t *status, size_t block_height); sgx_status_t Ecall_disable_upgrade(sgx_enclave_id_t eid); sgx_status_t Ecall_gen_upgrade_data(sgx_enclave_id_t eid, crust_status_t *status, size_t block_height); sgx_status_t Ecall_restore_from_upgrade(sgx_enclave_id_t eid, crust_status_t *status, const uint8_t *data, size_t data_size); sgx_status_t Ecall_validate_file(sgx_enclave_id_t eid); sgx_status_t Ecall_validate_srd(sgx_enclave_id_t eid); sgx_status_t Ecall_safe_store2(sgx_enclave_id_t eid, crust_status_t *status, ecall_store_type_t f, const uint8_t *data, size_t total_size, size_t partial_size, size_t offset, uint32_t buffer_key); #if defined(__cplusplus) } #endif #endif /* !_ECALLS_H_ */
3,279
C++
.h
40
80.55
196
0.755742
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,407
EnclaveQueue.h
crustio_crust-sworker/src/app/ecalls/EnclaveQueue.h
#ifndef _ENCLAVE_QUEUE_H_ #define _ENCLAVE_QUEUE_H_ #include <iostream> #include <sstream> #include <unistd.h> #include <vector> #include <map> #include <unordered_map> #include <unordered_set> #include <mutex> #include <thread> #include <sgx_error.h> #include <sgx_eid.h> #include "Resource.h" #include "Enclave_u.h" #include "Log.h" #include "EnclaveData.h" #include "CrustStatus.h" #include "SafeLock.h" // Max thread number. // Note: If you change this macro name, you should change corresponding name in Makefile #define ENC_MAX_THREAD_NUM 32 // Reserved enclave resource for highest priority task #define ENC_RESERVED_THREAD_NUM 1 // Threshold to trigger timeout mechanism #define ENC_PRIO_TIMEOUT_THRESHOLD 1 // Number of running in enclave permanently #define ENC_PERMANENT_TASK_NUM 1 // Highest priority #define ENC_HIGHEST_PRIORITY 0 // Task timeout number #define ENC_TASK_TIMEOUT 30 class EnclaveQueue { public: std::map<ecall_store_type_t, std::string> ecall_store2_func_m = { {ECALL_RESTORE_FROM_UPGRADE, "Ecall_restore_from_upgrade"}, }; void increase_waiting_queue(std::string name); void decrease_waiting_queue(std::string name); void increase_running_queue(std::string name); void decrease_running_queue(std::string name); int get_running_ecalls_sum(); int get_running_ecalls_num(std::string name); std::string get_running_ecalls_info(); int get_higher_prio_waiting_task_num(std::string name); void task_sleep(int priority); sgx_status_t try_get_enclave(const char *name); void free_enclave(const char *name); int get_upgrade_ecalls_num(); bool has_stopping_block_task(); static EnclaveQueue *enclaveQueue; static EnclaveQueue *get_instance(); private: EnclaveQueue(): running_task_num(0) {} // Task priority map, lower number represents higher priority std::unordered_map<std::string, int> task_priority_um = { {"Ecall_restore_metadata", 0}, {"Ecall_gen_key_pair", 0}, {"Ecall_cmp_chain_account_id", 0}, {"Ecall_get_quote_report", 0}, {"Ecall_gen_upload_epid_identity", 0}, {"Ecall_gen_upload_ecdsa_quote", 0}, {"Ecall_gen_upload_ecdsa_identity", 0}, {"Ecall_get_ecdsa_identity", 0}, {"Ecall_gen_sgx_measurement", 0}, {"Ecall_main_loop", 0}, {"Ecall_stop_all", 0}, {"Ecall_gen_and_upload_work_report", 0}, {"Ecall_gen_upgrade_data", 0}, {"Ecall_restore_from_upgrade", 0}, {"Ecall_enable_upgrade", 0}, {"Ecall_disable_upgrade", 0}, {"Ecall_recover_illegal_file", 1}, {"Ecall_delete_file",1}, {"Ecall_validate_file", 1}, {"Ecall_validate_srd", 1}, {"Ecall_seal_file_start", 1}, {"Ecall_seal_file", 1}, {"Ecall_seal_file_end", 1}, {"Ecall_unseal_file", 1}, {"Ecall_srd_decrease", 1}, {"Ecall_srd_remove_space", 1}, {"Ecall_change_srd_task", 1}, {"Ecall_srd_increase", 2}, {"Ecall_id_get_info", 2}, }; // Mapping of Enclave task to its block tasks, current task cannot run when there exists its block task std::unordered_map<std::string, std::unordered_set<std::string>> block_tasks_um = { { "Ecall_srd_increase", { "Ecall_seal_file_start", "Ecall_seal_file", "Ecall_seal_file_end", } }, }; // Lower priority ignore higher priority task std::unordered_map<std::string, std::unordered_set<std::string>> low_ignore_high_um = { { "Ecall_srd_increase", { "Ecall_unseal_file", } } }; // Upgrade blocks task set1 std::unordered_set<std::string> upgrade_blocked_task_us = { "Ecall_seal_file_start", "Ecall_seal_file", "Ecall_seal_file_end", "Ecall_unseal_file", "Ecall_srd_decrease", "Ecall_srd_increase", "Ecall_delete_file", "Ecall_srd_remove_space", }; // Stopping block task std::vector<std::string> stop_block_task_v = { "Ecall_gen_and_upload_work_report", "Ecall_main_loop", }; // Record running task number int running_task_num; std::mutex running_task_num_mutex; // Waiting queue item structure struct waiting_priority_item { int num; std::unordered_map<std::string, int> task_num_um; }; // Waiting task name to number map std::unordered_map<int, waiting_priority_item> waiting_task_um; std::mutex waiting_task_um_mutex; // Ecall function name to running number mapping std::unordered_map<std::string, int> running_ecalls_um; std::mutex running_ecalls_mutex; // Waiting time(million seconds) for different priority task std::vector<uint32_t> task_wait_time_v = {100, 10000, 500000, 1000000}; }; #endif /* !_ENCLAVE_QUEUE_H_ */
4,951
C++
.h
141
29.113475
107
0.637992
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,408
DataBase.h
crustio_crust-sworker/src/app/database/DataBase.h
#ifndef _CRUST_DATABASE_H_ #define _CRUST_DATABASE_H_ #include "leveldb/db.h" #include "leveldb/write_batch.h" #include "CrustStatus.h" #include "Config.h" #include "Log.h" #include "FileUtils.h" namespace crust { class DataBase { public: ~DataBase(); static DataBase *get_instance(); crust_status_t add(std::string key, std::string value); crust_status_t del(std::string key); crust_status_t set(std::string key, std::string value); crust_status_t get(std::string key, std::string &value); private: static DataBase *database; DataBase() {} DataBase(const DataBase &); DataBase& operator = (const DataBase &); leveldb::DB *db = NULL; leveldb::WriteOptions write_opt; }; } // namespace crust #endif /* !_CRUST_DATABASE_H_ */
778
C++
.h
29
23.965517
60
0.701211
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,409
PersistOCalls.h
crustio_crust-sworker/src/app/ocalls/PersistOCalls.h
#ifndef _CRUST_PERSIST_OCALLS_H_ #define _CRUST_PERSIST_OCALLS_H_ #include "CrustStatus.h" #include "Config.h" #include "Common.h" #include "Log.h" #include "DataBase.h" #if defined(__cplusplus) extern "C" { #endif crust_status_t ocall_persist_add(const char *key, const uint8_t *value, size_t value_len); crust_status_t ocall_persist_del(const char *key); crust_status_t ocall_persist_set(const char *key, const uint8_t *value, size_t value_len, size_t total_size, uint8_t **total_buf, size_t offset); crust_status_t ocall_persist_get(const char *key, uint8_t **value, size_t *value_len); #if defined(__cplusplus) } #endif #endif /* !_CRUST_PERSIST_OCALLS_H_ */
677
C++
.h
20
32.15
90
0.733129
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,410
OCalls.h
crustio_crust-sworker/src/app/ocalls/OCalls.h
#ifndef _CRUST_OCALLS_H_ #define _CRUST_OCALLS_H_ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <boost/algorithm/string.hpp> #include <exception> #include "CrustStatus.h" #include "FileUtils.h" #include "FormatUtils.h" #include "Config.h" #include "Common.h" #include "Log.h" #include "EnclaveData.h" #include "WebsocketClient.h" #include "Srd.h" #include "DataBase.h" #include "EntryNetwork.h" #include "Chain.h" #include "Validator.h" #include "SafeLock.h" #if defined(__cplusplus) extern "C" { #endif // For log void ocall_print_info(const char *str); void ocall_print_debug(const char *str); void ocall_log_info(const char *str); void ocall_log_warn(const char *str); void ocall_log_err(const char *str); void ocall_log_debug(const char *str); // For file crust_status_t ocall_chain_get_block_info(uint8_t *data, size_t data_size, size_t *real_size); void ocall_store_file_info(const char* cid, const char *data, const char *type); crust_status_t ocall_store_file_info_all(const uint8_t *data, size_t data_size); void ocall_usleep(int u); crust_status_t ocall_free_outer_buffer(uint8_t **value); // For srd crust_status_t ocall_srd_change(long change); // For enclave data to app void ocall_store_enclave_id_info(const char *info); crust_status_t ocall_store_workreport(const uint8_t *data, size_t data_size); crust_status_t ocall_store_upgrade_data(const uint8_t *data, size_t data_size); // For upgrade crust_status_t ocall_get_block_hash(size_t block_height, char *block_hash, size_t hash_size); crust_status_t ocall_upload_workreport(); crust_status_t ocall_upload_epid_identity(const char *id); crust_status_t ocall_upload_ecdsa_quote(const char *id); crust_status_t ocall_upload_ecdsa_identity(const char *id); crust_status_t ocall_entry_network(); void ocall_recall_validate_file(); void ocall_recall_validate_srd(); void ocall_change_file_type(const char *cid, const char *old_type, const char *new_type); void ocall_delete_file_info(const char *cid, const char *type); crust_status_t ocall_safe_store2(ocall_store_type_t t, const uint8_t *data, size_t total_size, size_t partial_size, size_t offset, uint32_t buffer_key); #if defined(__cplusplus) } #endif #endif /* !_OCALLS_APP_H_ */
2,498
C++
.h
67
34.164179
156
0.721923
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,411
IpfsOCalls.h
crustio_crust-sworker/src/app/ocalls/IpfsOCalls.h
#ifndef _CRUST_IPFS_OCALLS_H_ #define _CRUST_IPFS_OCALLS_H_ #include "CrustStatus.h" #include "DataBase.h" #include "Ipfs.h" #include "Log.h" #include "EnclaveData.h" #if defined(__cplusplus) extern "C" { #endif bool ocall_ipfs_online(); crust_status_t ocall_ipfs_get_block(const char *cid, uint8_t **p_data, size_t *data_size); crust_status_t ocall_ipfs_cat(const char *cid, uint8_t **p_data, size_t *data_size); crust_status_t ocall_ipfs_add(uint8_t *p_data, size_t len, char *cid, size_t cid_len); crust_status_t ocall_ipfs_del(const char *cid); crust_status_t ocall_ipfs_del_all(const char *cid); crust_status_t ocall_save_ipfs_block(const char *path, const uint8_t *data, size_t data_size, char *uuid, size_t uuid_len); crust_status_t ocall_delete_ipfs_file(const char *cid); #if defined(__cplusplus) } #endif #endif /* !_CRUST_IPFS_OCALLS_H_ */
856
C++
.h
23
36
123
0.735507
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,412
StoreOCalls.h
crustio_crust-sworker/src/app/ocalls/StoreOCalls.h
#ifndef _CRUST_STORE_OCALLS_H_ #define _CRUST_STORE_OCALLS_H_ #include "CrustStatus.h" #include "Log.h" #include "FileUtils.h" #include "FormatUtils.h" #if defined(__cplusplus) extern "C" { #endif crust_status_t ocall_create_dir(const char *path, store_type_t type); crust_status_t ocall_rename_dir(const char *old_path, const char *new_path, store_type_t type); crust_status_t ocall_save_file(const char *path, const unsigned char *data, size_t data_size, store_type_t type); crust_status_t ocall_delete_folder_or_file(const char *path, store_type_t type); crust_status_t ocall_get_file(const char *path, unsigned char **p_file, size_t *len, store_type_t type); void ocall_set_srd_info(const uint8_t *data, size_t data_size); #if defined(__cplusplus) } #endif #endif /* !_CRUST_STORE_OCALLS_H_ */
801
C++
.h
20
38.9
113
0.749357
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,413
private_key.cc
falk-werner_zipsign/lib/openssl++/private_key.cc
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #include "openssl++/private_key.hpp" #include "openssl++/basic_io.hpp" #include "openssl++/exception.hpp" #include <openssl/pem.h> #include <openssl/rsa.h> namespace openssl { PrivateKey PrivateKey::fromPEM(std::string const & filename) { BasicIO key_file = BasicIO::openInputFile(filename); EVP_PKEY * key = PEM_read_bio_PrivateKey(key_file, NULL, NULL, NULL); if (NULL == key) { throw OpenSSLException("failed to parse key file"); } return PrivateKey(key); } PrivateKey::PrivateKey(EVP_PKEY * key_) : key(key_) { } PrivateKey & PrivateKey::operator=(PrivateKey && other) { EVP_PKEY_free(this->key); this->key = other.key; other.key = nullptr; return *this; } PrivateKey::PrivateKey(PrivateKey && other) { this->key = other.key; other.key = nullptr; } PrivateKey::~PrivateKey() { EVP_PKEY_free(key); } PrivateKey::operator EVP_PKEY *() { return key; } }
1,139
C++
.cc
45
22.533333
73
0.698148
falk-werner/zipsign
36
13
1
MPL-2.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,535,414
certificate.cc
falk-werner_zipsign/lib/openssl++/certificate.cc
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #include "openssl++/certificate.hpp" #include "openssl++/basic_io.hpp" #include "openssl++/exception.hpp" #include <openssl/pem.h> #include <openssl/x509_vfy.h> #include <memory> namespace openssl { Certificate Certificate::fromPEM(std::string const & filename) { auto cert_file = BasicIO::openInputFile(filename); X509 * cert = PEM_read_bio_X509(cert_file, NULL, NULL, NULL); if (NULL == cert) { throw OpenSSLException("failed to parse certificate file"); } return Certificate(cert); } Certificate::Certificate(X509 * cert_) : cert(cert_) { } Certificate & Certificate::operator=(Certificate && other) { X509_free(this->cert); this->cert = other.cert; other.cert = nullptr; return *this; } Certificate::Certificate(Certificate && other) { this->cert = other.cert; other.cert = nullptr; } Certificate::~Certificate() { X509_free(cert); } Certificate::operator X509*() { return cert; } bool Certificate::verify(X509_STORE * store, STACK_OF(X509) * chain, STACK_OF(X509) * untrusted) { std::unique_ptr<X509_STORE_CTX, void(*)(X509_STORE_CTX *)> context(X509_STORE_CTX_new(), &X509_STORE_CTX_free); int rc = X509_STORE_CTX_init(context.get(), store, cert, chain); if (1 != rc) { throw OpenSSLException("X509_STORE_CTX_init"); } X509_STORE_CTX_set0_untrusted(context.get(), untrusted); rc = X509_verify_cert(context.get()); return (1 == rc); } }
1,672
C++
.cc
58
25.655172
115
0.691343
falk-werner/zipsign
36
13
1
MPL-2.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,415
exception.cc
falk-werner_zipsign/lib/openssl++/exception.cc
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #include "openssl++/exception.hpp" #include <openssl/err.h> #include <sstream> #include <iomanip> namespace { std::string getOpenSSLError(std::string const & message) { constexpr size_t buffer_size = 256; char buffer[buffer_size] = "\0"; unsigned long const error_code = ERR_get_error(); ERR_error_string_n(error_code, buffer, buffer_size); std::stringstream stream; stream << "error: " << message << " (OpenSSL: " << buffer << " [0x" << std::setw(8) << std::setfill('0') << std::hex << error_code << "])" ; return stream.str(); } } namespace openssl { OpenSSLBaseException::OpenSSLBaseException(std::string const & message_) : message(message_) { } OpenSSLBaseException::~OpenSSLBaseException() { } char const * OpenSSLBaseException::what() const noexcept { return message.c_str(); } FileNotFoundException::FileNotFoundException(std::string const & filename_) : OpenSSLBaseException("file not found: " + filename_) , filename(filename_) { } FileNotFoundException::~FileNotFoundException() { } std::string const & FileNotFoundException::path() const { return filename; } OpenSSLException::OpenSSLException(std::string const & message_) : OpenSSLBaseException(getOpenSSLError(message_)) { } OpenSSLException::~OpenSSLException() { } }
1,523
C++
.cc
56
24.678571
88
0.722917
falk-werner/zipsign
36
13
1
MPL-2.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false