## Overview ESBOCS (Enhanced Scalable Byzantine Fault-Tolerant Consensus) is a sophisticated consensus mechanism designed for high-throughput blockchain networks requiring Byzantine fault tolerance and scalability. This module implements a multi-round consensus protocol with validator management, emergency procedures, and directive-based governance for efficient and secure distributed consensus in enterprise blockchain networks. *Based on: `dap_chain_cs_esbocs.h`, `dap_chain_cs_esbocs.c`* ## Document Structure - [[#Overview|Overview]] - [[#Module Structures|Module Structures]] - [[#dap_chain_esbocs_t|dap_chain_esbocs_t - ESBOCS Instance]] - [[#dap_chain_esbocs_message_hdr_t|dap_chain_esbocs_message_hdr_t - Message header]] - [[#dap_chain_esbocs_message_t|dap_chain_esbocs_message_t - ESBOCS message]] - [[#dap_chain_esbocs_message_item_t|dap_chain_esbocs_message_item_t - Message item]] - [[#dap_chain_esbocs_sync_item_t|dap_chain_esbocs_sync_item_t - Sync item]] - [[#dap_chain_esbocs_store_t|dap_chain_esbocs_store_t - Candidate store]] - [[#dap_chain_esbocs_directive_t|dap_chain_esbocs_directive_t - Consensus directive]] - [[#dap_chain_esbocs_round_t|dap_chain_esbocs_round_t - Consensus round]] - [[#dap_chain_esbocs_validator_t|dap_chain_esbocs_validator_t - Validator structure]] - [[#dap_chain_esbocs_penalty_item_t|dap_chain_esbocs_penalty_item_t - Penalty tracking]] - [[#dap_chain_esbocs_session_t|dap_chain_esbocs_session_t - ESBOCS session]] - [[#dap_chain_esbocs_block_collect_t|dap_chain_esbocs_block_collect_t - Block collection]] - [[#s_com_esbocs_err_t|s_com_esbocs_err_t - Error codes]] - [[#dap_chain_block_autocollect_type_t|dap_chain_block_autocollect_type_t - Collection types]] - [[#Module Functions|Module Functions]] - [[#Consensus Management|Consensus Instance Control]] - [[#Validator Operations|Validator Management]] - [[#Round Processing|Consensus Round Execution]] - [[#Vote Handling|Vote Collection and Verification]] - [[#Error Codes|Error Codes]] - [[#Typical Examples|Typical Examples]] ## Module Structures ### dap_chain_esbocs_t Core ESBOCS consensus instance managing protocol execution. ```c typedef struct dap_chain_esbocs { dap_chain_t *chain; // Associated blockchain dap_chain_cs_blocks_t *blocks; // Block consensus interface dap_chain_esbocs_session_t *session; // Current ESBOCS session dap_time_t last_directive_vote_timestamp; // Last directive vote time dap_time_t last_directive_accept_timestamp; // Last directive accept time dap_time_t last_submitted_candidate_timestamp; // Last candidate submission time dap_time_t last_accepted_block_timestamp; // Last block acceptance time void *_pvt; // Private data } dap_chain_esbocs_t; ``` **Fields:** - `chain` - Reference to managed blockchain - `blocks` - Block consensus interface for block operations - `session` - Current active ESBOCS session - `last_directive_vote_timestamp` - Timestamp of last directive vote - `last_directive_accept_timestamp` - Timestamp of last directive acceptance - `last_submitted_candidate_timestamp` - Timestamp of last candidate submission - `last_accepted_block_timestamp` - Timestamp of last block acceptance - `_pvt` - Private implementation data ### dap_chain_esbocs_message_hdr_t Header structure for ESBOCS protocol messages. ```c typedef struct dap_chain_esbocs_message_hdr { uint16_t version; // Protocol version uint8_t type; // Message type uint8_t attempt_num; // Attempt number uint64_t round_id; // Round identifier uint64_t sign_size; // Signature size uint64_t message_size; // Message size dap_time_t ts_created; // Creation timestamp dap_chain_net_id_t net_id; // Network ID dap_chain_id_t chain_id; // Chain ID dap_chain_cell_id_t cell_id; // Cell ID dap_stream_node_addr_t recv_addr; // Receiver address dap_hash_fast_t candidate_hash; // Candidate hash } DAP_ALIGN_PACKED dap_chain_esbocs_message_hdr_t; ``` **Fields:** - `version` - ESBOCS protocol version - `type` - Message type (PreVote, PreCommit, Commit, etc.) - `attempt_num` - Consensus attempt number - `round_id` - Unique round identifier - `sign_size` - Size of attached signature - `message_size` - Total message size - `ts_created` - Message creation timestamp - `net_id` - Target network identifier - `chain_id` - Target chain identifier - `cell_id` - Target cell identifier - `recv_addr` - Intended receiver address - `candidate_hash` - Hash of candidate block ### dap_chain_esbocs_message_t Complete ESBOCS message with header and signature. ```c typedef struct dap_chain_esbocs_message { dap_chain_esbocs_message_hdr_t hdr; // Message header uint8_t msg_n_sign[]; // Message and signature data } DAP_ALIGN_PACKED dap_chain_esbocs_message_t; ``` **Fields:** - `hdr` - Message header with protocol information - `msg_n_sign` - Variable-length message content and signature ### dap_chain_esbocs_message_item_t Hash table item for managing ESBOCS messages. ```c typedef struct dap_chain_esbocs_message_item { dap_hash_fast_t message_hash; // Message hash key dap_chain_esbocs_message_t *message; // Message data dap_chain_addr_t signing_addr; // Signing address bool unprocessed; // Processing status flag UT_hash_handle hh; // Hash table handle } dap_chain_esbocs_message_item_t; ``` **Fields:** - `message_hash` - Unique message hash for identification - `message` - Pointer to message data - `signing_addr` - Address that signed the message - `unprocessed` - Flag to prevent double processing - `hh` - Hash table handle for efficient lookup ### dap_chain_esbocs_sync_item_t Synchronization item for tracking consensus state. ```c typedef struct dap_chain_esbocs_sync_item { dap_hash_fast_t last_block_hash; // Last known block hash dap_list_t *messages; // Associated messages UT_hash_handle hh; // Hash table handle } dap_chain_esbocs_sync_item_t; ``` **Fields:** - `last_block_hash` - Hash of the last known block - `messages` - List of messages for this sync point - `hh` - Hash table handle for sync item management ### dap_chain_esbocs_store_t Storage structure for candidate blocks and voting results. ```c typedef struct dap_chain_esbocs_store { dap_hash_fast_t candidate_hash; // Candidate block hash dap_hash_fast_t precommit_candidate_hash; // Precommit candidate hash dap_chain_block_t *candidate; // Candidate block data size_t candidate_size; // Candidate block size dap_list_t *candidate_signs; // Candidate signatures uint16_t approve_count; // Approval vote count uint16_t reject_count; // Rejection vote count uint16_t precommit_count; // Precommit vote count bool decide_reject; // Rejection decision flag bool decide_approve; // Approval decision flag bool decide_commit; // Commit decision flag UT_hash_handle hh; // Hash table handle } dap_chain_esbocs_store_t; ``` **Fields:** - `candidate_hash` - Hash of candidate block - `precommit_candidate_hash` - Hash for precommit phase - `candidate` - Actual candidate block data - `candidate_size` - Size of candidate block - `candidate_signs` - List of validator signatures - `approve_count` - Number of approval votes received - `reject_count` - Number of rejection votes received - `precommit_count` - Number of precommit votes received - `decide_reject` - Flag indicating rejection decision - `decide_approve` - Flag indicating approval decision - `decide_commit` - Flag indicating commit decision - `hh` - Hash table handle for storage management ### dap_chain_esbocs_directive_t Consensus directive structure for protocol parameter changes. ```c typedef struct dap_chain_esbocs_directive { uint8_t version; // Directive version uint8_t type; // Directive type uint16_t pad; // Padding for alignment uint32_t size; // Directive size dap_nanotime_t timestamp; // Creation timestamp byte_t tsd[]; // Type-Size-Data payload } DAP_ALIGN_PACKED dap_chain_esbocs_directive_t; ``` **Fields:** - `version` - Directive format version - `type` - Type of directive (parameter change, validator update, etc.) - `pad` - Padding for proper alignment - `size` - Size of the directive data - `timestamp` - Directive creation timestamp - `tsd` - Variable-length directive payload ### dap_chain_esbocs_validator_t Validator structure for ESBOCS consensus participation. ```c typedef struct dap_chain_esbocs_validator { dap_chain_node_addr_t node_addr; // Validator node address dap_chain_addr_t signing_addr; // Signing address uint256_t weight; // Validator weight/stake bool is_synced; // Synchronization status bool is_chosen; // Selection status for round } dap_chain_esbocs_validator_t; ``` **Fields:** - `node_addr` - Network address of validator node - `signing_addr` - Address used for signing votes - `weight` - Validator weight in consensus (typically stake amount) - `is_synced` - Flag indicating if validator is synchronized - `is_chosen` - Flag indicating if validator is chosen for current round ### s_com_esbocs_err_t Error codes for ESBOCS operations. ```c typedef enum s_com_esbocs_err { DAP_CHAIN_NODE_CLI_COM_ESBOCS_OK = 0, // Success DAP_CHAIN_NODE_CLI_COM_ESBOCS_PARAM_ERR, // Parameter error DAP_CHAIN_NODE_CLI_COM_ESBOCS_CHAIN_TYPE_ERR, // Wrong chain type DAP_CHAIN_NODE_CLI_COM_ESBOCS_CERT_ERR, // Certificate error DAP_CHAIN_NODE_CLI_COM_ESBOCS_PVT_KEY_ERR, // Private key error DAP_CHAIN_NODE_CLI_COM_ESBOCS_UNREC_COM_ERR, // Unrecognized command DAP_CHAIN_NODE_CLI_COM_ESBOCS_MINVALSET_ERR, // Min validator set error DAP_CHAIN_NODE_CLI_COM_ESBOCS_CHECKING_ERR, // Validation error DAP_CHAIN_NODE_CLI_COM_ESBOCS_HASH_ERR, // Hash error DAP_CHAIN_NODE_CLI_COM_ESBOCS_HASH_FORMAT_ERR, // Hash format error DAP_CHAIN_NODE_CLI_COM_ESBOCS_ADD_DEL_ERR, // Add/delete error DAP_CHAIN_NODE_CLI_COM_ESBOCS_SUB_ERR, // Substitution error DAP_CHAIN_NODE_CLI_COM_ESBOCS_NO_NET, // No network DAP_CHAIN_NODE_CLI_COM_ESBOCS_CANT_FIND_NET, // Cannot find network DAP_CHAIN_NODE_CLI_COM_ESBOCS_NO_SESSION, // No session DAP_CHAIN_NODE_CLI_COM_ESBOCS_NO_STAKE, // No stake DAP_CHAIN_NODE_CLI_COM_ESBOCS_WRONG_CHAIN, // Wrong chain DAP_CHAIN_NODE_CLI_COM_ESBOCS_UNKNOWN // Unknown error } s_com_esbocs_err_t; ``` **Error Categories:** - **Configuration Errors** - PARAM_ERR, CHAIN_TYPE_ERR, CERT_ERR - **Security Errors** - PVT_KEY_ERR, HASH_ERR, HASH_FORMAT_ERR - **Network Errors** - NO_NET, CANT_FIND_NET, NO_SESSION - **Validation Errors** - MINVALSET_ERR, CHECKING_ERR, NO_STAKE ### dap_chain_block_autocollect_type_t Block collection types for automated fee and reward collection. ```c typedef enum dap_chain_block_autocollect_type { DAP_CHAIN_BLOCK_COLLECT_BOTH, // Collect both fees and rewards DAP_CHAIN_BLOCK_COLLECT_FEES, // Collect only transaction fees DAP_CHAIN_BLOCK_COLLECT_REWARDS // Collect only block rewards } dap_chain_block_autocollect_type_t; ``` **Collection Types:** - `COLLECT_BOTH` - Collect both transaction fees and block rewards - `COLLECT_FEES` - Collect only transaction fees from blocks - `COLLECT_REWARDS` - Collect only consensus block rewards ### dap_chain_esbocs_round_t Comprehensive structure managing ESBOCS consensus rounds. ```c typedef struct dap_chain_esbocs_round { uint64_t id; // Round identifier uint64_t sync_attempt; // Synchronization attempt number dap_time_t round_start_ts; // Round start timestamp dap_time_t prev_round_start_ts; // Previous round start time dap_hash_fast_t last_block_hash; // Last accepted block hash dap_hash_fast_t directive_hash; // Current directive hash dap_hash_fast_t attempt_candidate_hash; // Candidate hash for this attempt dap_chain_addr_t attempt_submit_validator; // Validator submitting candidate dap_list_t *all_validators; // All available validators dap_chain_esbocs_store_t *store_items; // Storage items hash table dap_chain_esbocs_message_item_t *message_items; // Messages hash table dap_chain_esbocs_directive_t *directive; // Current round directive uint16_t *excluded_list; // Excluded validators list dap_list_t *validators_list; // Active validators list uint16_t votes_for_count; // Votes for directive count uint16_t votes_against_count; // Votes against directive count uint16_t validators_synced_count; // Synced validators count uint16_t total_validators_synced; // Total validators synced bool directive_applied; // Directive application status bool sync_sent; // Sync message sent flag uint8_t attempt_num; // Current attempt number } dap_chain_esbocs_round_t; ``` ### dap_chain_esbocs_penalty_item_t Penalty tracking structure for validator performance monitoring. ```c typedef struct dap_chain_esbocs_penalty_item { dap_chain_addr_t signing_addr; // Validator signing address uint16_t miss_count; // Number of missed rounds UT_hash_handle hh; // Hash table handle } dap_chain_esbocs_penalty_item_t; ``` **Penalty System:** - `miss_count` - Tracks consecutive missed rounds - **Kick Threshold:** `DAP_CHAIN_ESBOCS_PENALTY_KICK` (3 missed rounds) - **Auto-removal:** Validators kicked after exceeding threshold ### dap_chain_esbocs_session_t Complete ESBOCS session managing consensus state and operations. ```c typedef struct dap_chain_esbocs_session { dap_proc_thread_t *proc_thread; // Processing thread dap_chain_block_t *processing_candidate; // Currently processing candidate dap_chain_t *chain; // Associated blockchain dap_chain_esbocs_t *esbocs; // ESBOCS instance dap_time_t ts_round_sync_start; // Round sync start time dap_time_t ts_stage_entry; // Stage entry timestamp dap_chain_esbocs_sync_item_t *sync_items; // Sync items hash table dap_chain_esbocs_penalty_item_t *penalty; // Penalty tracking hash table dap_global_db_cluster_t *db_cluster; // Database cluster struct dap_chain_esbocs_session *prev, *next; // Linked list pointers dap_chain_esbocs_round_t cur_round; // Current round data unsigned int listen_ensure; // Listen ensure counter dap_chain_node_addr_t my_addr; // Local node address uint8_t state; // Current session state uint8_t old_state; // Previous session state bool cs_timer; // Consensus timer flag bool round_fast_forward; // Fast forward flag bool sync_failed; // Sync failure flag bool new_round_enqueued; // New round queued flag bool is_actual_hash; // Actual hash flag dap_global_db_driver_hash_t db_hash; // Database hash dap_chain_addr_t my_signing_addr; // Local signing address } dap_chain_esbocs_session_t; ``` ### dap_chain_esbocs_block_collect_t Block collection configuration for automated fee and reward collection. ```c typedef struct dap_chain_esbocs_block_collect { uint256_t collecting_level; // Collection level threshold uint256_t minimum_fee; // Minimum fee requirement dap_chain_t *chain; // Target blockchain dap_enc_key_t *blocks_sign_key; // Block signing private key dap_pkey_t *block_sign_pkey; // Block signing public key dap_chain_addr_t *collecting_addr; // Collection destination address dap_chain_cell_id_t cell_id; // Target cell identifier } dap_chain_esbocs_block_collect_t; ``` **Collection Parameters:** - `collecting_level` - Threshold for triggering collection - `minimum_fee` - Minimum fee amount to collect - `blocks_sign_key` - Private key for signing collection transactions - `block_sign_pkey` - Public key for verification - `collecting_addr` - Destination address for collected funds - `cell_id` - Target cell for collection operations ```c typedef struct dap_chain_cs_esbocs_validator { struct { dap_chain_addr_t *addr; // Validator address dap_pkey_t *pkey; // Validator public key uint256_t stake_amount; // Validator stake amount double voting_power; // Calculated voting power dap_chain_cs_esbocs_validator_state_t state; // Validator state dap_time_t last_activity; // Last activity timestamp bool is_online; // Online status flag } pub; struct { dap_enc_key_t *signing_key; // Private signing key (if local) uint64_t rounds_participated; // Number of rounds participated uint64_t votes_cast; // Total votes cast uint64_t blocks_proposed; // Blocks proposed by validator dap_time_t stake_time; // Stake deposit time dap_list_t *recent_votes; // Recent vote history uint64_t reputation_score; // Validator reputation score } priv; } dap_chain_cs_esbocs_validator_t; ``` **Validator Management:** - `addr` - Unique validator address identifier - `pkey` - Public key for signature verification - `stake_amount` - Staked tokens determining voting weight - `voting_power` - Normalized voting power in consensus - `signing_key` - Private key for local validators - `reputation_score` - Performance-based reputation metric ### dap_chain_cs_esbocs_round_t Consensus round data structure managing voting process. ```c typedef struct dap_chain_cs_esbocs_round { struct { uint64_t round_number; // Round identifier uint64_t height; // Target blockchain height dap_time_t start_time; // Round start timestamp dap_time_t timeout; // Round timeout timestamp dap_chain_cs_esbocs_phase_t phase; // Current round phase dap_chain_addr_t *proposer_addr; // Round proposer address uint32_t total_validators; // Total validator count } pub; struct { dap_list_t *proposals; // Block proposals for round dap_htable_t *votes_table; // Votes organized by validator uint64_t total_voting_power; // Total available voting power uint64_t collected_voting_power; // Voting power collected bool has_majority; // Majority vote achieved dap_chain_hash_fast_t *winning_proposal; // Winning proposal hash dap_time_t decision_time; // Decision reached timestamp } priv; } dap_chain_cs_esbocs_round_t; ``` ### dap_chain_cs_esbocs_proposal_t Block proposal structure for consensus rounds. ```c typedef struct dap_chain_cs_esbocs_proposal { struct { dap_chain_hash_fast_t hash; // Proposal hash dap_chain_addr_t *proposer_addr; // Proposer validator address uint64_t round_number; // Associated round number uint64_t height; // Target height dap_time_t timestamp; // Proposal creation time size_t block_size; // Proposed block size uint32_t transactions_count; // Number of transactions } pub; struct { dap_chain_block_t *block; // Proposed block data dap_sign_t *proposer_signature; // Proposer signature dap_list_t *transaction_hashes; // Transaction hash list uint64_t total_fees; // Total transaction fees dap_chain_hash_fast_t prev_block_hash; // Previous block hash bool is_valid; // Validation status dap_time_t validation_time; // Validation completion time } priv; } dap_chain_cs_esbocs_proposal_t; ``` ### dap_chain_cs_esbocs_vote_t Validator vote structure for consensus decisions. ```c typedef struct dap_chain_cs_esbocs_vote { struct { dap_chain_addr_t *validator_addr; // Voting validator address uint64_t round_number; // Target round number uint64_t height; // Target height dap_chain_hash_fast_t proposal_hash; // Voted proposal hash dap_chain_cs_esbocs_vote_type_t type; // Vote type (prevote, precommit) dap_time_t timestamp; // Vote timestamp double voting_power; // Validator voting power } pub; struct { dap_sign_t *signature; // Vote signature uint64_t validator_stake; // Validator stake amount bool is_valid; // Vote validation status dap_time_t received_time; // Vote reception time dap_chain_node_addr_t *sender_addr; // Network sender address uint32_t verification_attempts; // Signature verification attempts } priv; } dap_chain_cs_esbocs_vote_t; ``` ## Module Functions ### Consensus Management #### `dap_chain_cs_esbocs_new()` Creates new ESBOCS consensus instance. ```c dap_chain_cs_esbocs_t* dap_chain_cs_esbocs_new(dap_chain_t *a_chain, dap_chain_cs_esbocs_config_t *a_config); ``` **Parameters:** - `a_chain` (dap_chain_t*) - Target blockchain - `a_config` (dap_chain_cs_esbocs_config_t*) - ESBOCS configuration **Returns:** - `dap_chain_cs_esbocs_t*` - New ESBOCS instance - `NULL` - Creation failed or invalid parameters **Error Conditions:** - Returns NULL if a_chain is NULL - Returns NULL if a_config is invalid - Returns NULL if memory allocation fails #### `dap_chain_cs_esbocs_start()` Starts ESBOCS consensus protocol. ```c int dap_chain_cs_esbocs_start(dap_chain_cs_esbocs_t *a_esbocs); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance to start **Returns:** - `0` - Consensus started successfully - `-1` - Invalid ESBOCS parameter - `-2` - Consensus already running - `-3` - Insufficient validators - `-4` - Startup failed #### `dap_chain_cs_esbocs_stop()` Stops ESBOCS consensus protocol. ```c int dap_chain_cs_esbocs_stop(dap_chain_cs_esbocs_t *a_esbocs); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance to stop **Returns:** - `0` - Consensus stopped successfully - `-1` - Invalid ESBOCS parameter - `-2` - Consensus not running #### `dap_chain_cs_esbocs_delete()` Destroys ESBOCS instance and frees resources. ```c void dap_chain_cs_esbocs_delete(dap_chain_cs_esbocs_t *a_esbocs); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance to destroy ### Validator Operations #### `dap_chain_cs_esbocs_validator_add()` Adds validator to consensus set. ```c int dap_chain_cs_esbocs_validator_add(dap_chain_cs_esbocs_t *a_esbocs, dap_chain_cs_esbocs_validator_t *a_validator); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_validator` (dap_chain_cs_esbocs_validator_t*) - Validator to add **Returns:** - `0` - Validator added successfully - `-1` - Invalid parameters - `-2` - Validator already exists - `-3` - Insufficient stake - `-4` - Maximum validators reached #### `dap_chain_cs_esbocs_validator_remove()` Removes validator from consensus set. ```c int dap_chain_cs_esbocs_validator_remove(dap_chain_cs_esbocs_t *a_esbocs, dap_chain_addr_t *a_validator_addr); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_validator_addr` (dap_chain_addr_t*) - Validator address to remove **Returns:** - `0` - Validator removed successfully - `-1` - Invalid parameters - `-2` - Validator not found - `-3` - Cannot remove during active round #### `dap_chain_cs_esbocs_validator_find()` Finds validator by address. ```c dap_chain_cs_esbocs_validator_t* dap_chain_cs_esbocs_validator_find( dap_chain_cs_esbocs_t *a_esbocs, dap_chain_addr_t *a_validator_addr); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_validator_addr` (dap_chain_addr_t*) - Validator address to find **Returns:** - `dap_chain_cs_esbocs_validator_t*` - Found validator - `NULL` - Validator not found or invalid parameters #### `dap_chain_cs_esbocs_validator_update_stake()` Updates validator stake amount. ```c int dap_chain_cs_esbocs_validator_update_stake(dap_chain_cs_esbocs_t *a_esbocs, dap_chain_addr_t *a_validator_addr, uint256_t a_new_stake); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_validator_addr` (dap_chain_addr_t*) - Validator address - `a_new_stake` (uint256_t) - New stake amount **Returns:** - `0` - Stake updated successfully - `-1` - Invalid parameters - `-2` - Validator not found - `-3` - Invalid stake amount ### Round Processing #### `dap_chain_cs_esbocs_round_start()` Starts new consensus round. ```c int dap_chain_cs_esbocs_round_start(dap_chain_cs_esbocs_t *a_esbocs, uint64_t a_height); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_height` (uint64_t) - Target blockchain height **Returns:** - `0` - Round started successfully - `-1` - Invalid parameters - `-2` - Previous round not finished - `-3` - No validators available - `-4` - Round start failed #### `dap_chain_cs_esbocs_round_finish()` Finishes current consensus round. ```c int dap_chain_cs_esbocs_round_finish(dap_chain_cs_esbocs_t *a_esbocs); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance **Returns:** - `0` - Round finished successfully - `-1` - Invalid ESBOCS parameter - `-2` - No active round - `-3` - Round not ready to finish #### `dap_chain_cs_esbocs_proposal_create()` Creates block proposal for current round. ```c dap_chain_cs_esbocs_proposal_t* dap_chain_cs_esbocs_proposal_create( dap_chain_cs_esbocs_t *a_esbocs, dap_chain_block_t *a_block); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_block` (dap_chain_block_t*) - Block to propose **Returns:** - `dap_chain_cs_esbocs_proposal_t*` - New proposal - `NULL` - Creation failed or invalid parameters #### `dap_chain_cs_esbocs_proposal_validate()` Validates received block proposal. ```c int dap_chain_cs_esbocs_proposal_validate(dap_chain_cs_esbocs_t *a_esbocs, dap_chain_cs_esbocs_proposal_t *a_proposal); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_proposal` (dap_chain_cs_esbocs_proposal_t*) - Proposal to validate **Returns:** - `0` - Proposal is valid - `-1` - Invalid parameters - `-2` - Proposal validation failed - `-3` - Invalid proposer - `-4` - Block validation failed ### Vote Handling #### `dap_chain_cs_esbocs_vote_create()` Creates validator vote for proposal. ```c dap_chain_cs_esbocs_vote_t* dap_chain_cs_esbocs_vote_create( dap_chain_cs_esbocs_t *a_esbocs, dap_chain_hash_fast_t *a_proposal_hash, dap_chain_cs_esbocs_vote_type_t a_vote_type); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_proposal_hash` (dap_chain_hash_fast_t*) - Proposal to vote for - `a_vote_type` (dap_chain_cs_esbocs_vote_type_t) - Vote type **Returns:** - `dap_chain_cs_esbocs_vote_t*` - New vote - `NULL` - Creation failed or invalid parameters #### `dap_chain_cs_esbocs_vote_add()` Adds received vote to consensus. ```c int dap_chain_cs_esbocs_vote_add(dap_chain_cs_esbocs_t *a_esbocs, dap_chain_cs_esbocs_vote_t *a_vote); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_vote` (dap_chain_cs_esbocs_vote_t*) - Vote to add **Returns:** - `0` - Vote added successfully - `-1` - Invalid parameters - `-2` - Vote validation failed - `-3` - Duplicate vote - `-4` - Round not accepting votes #### `dap_chain_cs_esbocs_vote_verify()` Verifies vote signature and validity. ```c int dap_chain_cs_esbocs_vote_verify(dap_chain_cs_esbocs_t *a_esbocs, dap_chain_cs_esbocs_vote_t *a_vote); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_vote` (dap_chain_cs_esbocs_vote_t*) - Vote to verify **Returns:** - `0` - Vote is valid - `-1` - Invalid parameters - `-2` - Signature verification failed - `-3` - Validator not authorized - `-4` - Vote format invalid #### `dap_chain_cs_esbocs_check_majority()` Checks if majority vote achieved. ```c bool dap_chain_cs_esbocs_check_majority(dap_chain_cs_esbocs_t *a_esbocs, dap_chain_hash_fast_t *a_proposal_hash); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_proposal_hash` (dap_chain_hash_fast_t*) - Proposal to check **Returns:** - `true` - Majority achieved for proposal - `false` - Majority not achieved or invalid parameters #### `dap_chain_cs_esbocs_finalize_block()` Finalizes block after achieving consensus. ```c int dap_chain_cs_esbocs_finalize_block(dap_chain_cs_esbocs_t *a_esbocs, dap_chain_cs_esbocs_proposal_t *a_proposal); ``` **Parameters:** - `a_esbocs` (dap_chain_cs_esbocs_t*) - ESBOCS instance - `a_proposal` (dap_chain_cs_esbocs_proposal_t*) - Winning proposal **Returns:** - `0` - Block finalized successfully - `-1` - Invalid parameters - `-2` - Insufficient votes - `-3` - Block finalization failed ## Error Codes ### ESBOCS Consensus Error Codes ```c typedef enum dap_chain_cs_esbocs_error { DAP_CHAIN_CS_ESBOCS_ERROR_SUCCESS = 0, // Operation successful DAP_CHAIN_CS_ESBOCS_ERROR_INVALID_PARAM, // Invalid parameter DAP_CHAIN_CS_ESBOCS_ERROR_NO_MEMORY, // Memory allocation failed DAP_CHAIN_CS_ESBOCS_ERROR_ALREADY_RUNNING, // Consensus already running DAP_CHAIN_CS_ESBOCS_ERROR_NOT_RUNNING, // Consensus not running DAP_CHAIN_CS_ESBOCS_ERROR_INSUFFICIENT_VALIDATORS, // Not enough validators DAP_CHAIN_CS_ESBOCS_ERROR_VALIDATOR_EXISTS, // Validator already exists DAP_CHAIN_CS_ESBOCS_ERROR_VALIDATOR_NOT_FOUND, // Validator not found DAP_CHAIN_CS_ESBOCS_ERROR_INVALID_STAKE, // Invalid stake amount DAP_CHAIN_CS_ESBOCS_ERROR_ROUND_ACTIVE, // Round already active DAP_CHAIN_CS_ESBOCS_ERROR_NO_ROUND, // No active round DAP_CHAIN_CS_ESBOCS_ERROR_INVALID_PROPOSAL, // Invalid block proposal DAP_CHAIN_CS_ESBOCS_ERROR_VOTE_INVALID, // Invalid vote DAP_CHAIN_CS_ESBOCS_ERROR_SIGNATURE_INVALID, // Invalid signature DAP_CHAIN_CS_ESBOCS_ERROR_MAJORITY_NOT_REACHED, // Majority not achieved DAP_CHAIN_CS_ESBOCS_ERROR_TIMEOUT // Round timeout reached } dap_chain_cs_esbocs_error_t; ``` ## Typical Examples ### Basic ESBOCS Consensus Setup Example ```c #include <dap_chain_cs_esbocs.h> void esbocs_consensus_setup_example() { log_it_info("=== ESBOCS Consensus Setup Example ==="); // Create blockchain instance (assume already created) dap_chain_t *chain = dap_chain_find_by_id(dap_config_get_item_str_default(NULL, "chain", "chain_id", "testchain")); if (!chain) { log_it_error("✗ Chain not found for ESBOCS consensus"); return; } // Configure ESBOCS parameters dap_chain_cs_esbocs_config_t config = { .min_validators = 4, // Minimum validators required .max_validators = 100, // Maximum validators allowed .min_stake_amount = 1000, // Minimum stake requirement .round_timeout_ms = 10000, // Round timeout (10 seconds) .proposal_timeout_ms = 5000, // Proposal timeout (5 seconds) .vote_timeout_ms = 3000, // Vote timeout (3 seconds) .finality_confirmations = 1, // Immediate finality .byzantine_threshold = 0.33, // 1/3 Byzantine tolerance .enable_signature_aggregation = true, // Enable signature aggregation .enable_fast_finality = true // Enable fast finality }; // Create ESBOCS consensus instance dap_chain_cs_esbocs_t *esbocs = dap_chain_cs_esbocs_new(chain, &config); if (!esbocs) { log_it_error("✗ Failed to create ESBOCS consensus instance"); return; } log_it_info("✓ ESBOCS consensus instance created"); log_it_info(" Chain: %s", chain->name); log_it_info(" Min validators: %d", config.min_validators); log_it_info(" Max validators: %d", config.max_validators); log_it_info(" Round timeout: %d ms", config.round_timeout_ms); log_it_info(" Byzantine threshold: %.2f", config.byzantine_threshold); // Create sample validators struct { const char *name; uint256_t stake; bool is_local; } validator_configs[] = { {"validator_1", uint256_from_uint64(5000), true}, {"validator_2", uint256_from_uint64(3000), false}, {"validator_3", uint256_from_uint64(4000), false}, {"validator_4", uint256_from_uint64(2000), false}, {"validator_5", uint256_from_uint64(6000), false} }; const int num_validators = sizeof(validator_configs) / sizeof(validator_configs[0]); // Add validators to consensus for (int i = 0; i < num_validators; i++) { // Create validator address dap_chain_addr_t *validator_addr = dap_chain_addr_from_str(validator_configs[i].name); if (!validator_addr) { log_it_error("✗ Failed to create validator address: %s", validator_configs[i].name); continue; } // Generate validator key pair dap_enc_key_t *signing_key = dap_enc_key_new_generate(DAP_ENC_KEY_TYPE_SIG_PICNIC, NULL, 0, NULL, 0, 0); if (!signing_key) { log_it_error("✗ Failed to generate signing key for validator: %s", validator_configs[i].name); DAP_DELETE(validator_addr); continue; } // Extract public key dap_pkey_t *public_key = dap_pkey_from_enc_key(signing_key); if (!public_key) { log_it_error("✗ Failed to extract public key for validator: %s", validator_configs[i].name); dap_enc_key_delete(signing_key); DAP_DELETE(validator_addr); continue; } // Create validator structure dap_chain_cs_esbocs_validator_t validator = { .pub.addr = validator_addr, .pub.pkey = public_key, .pub.stake_amount = validator_configs[i].stake, .pub.state = DAP_CHAIN_CS_ESBOCS_VALIDATOR_STATE_ACTIVE, .pub.last_activity = dap_time_now(), .pub.is_online = true, .priv.signing_key = validator_configs[i].is_local ? signing_key : NULL, .priv.rounds_participated = 0, .priv.votes_cast = 0, .priv.blocks_proposed = 0, .priv.stake_time = dap_time_now(), .priv.reputation_score = 1000 }; // Calculate voting power based on stake validator.pub.voting_power = dap_uint256_to_double(validator_configs[i].stake) / 100.0; // Add validator to consensus int result = dap_chain_cs_esbocs_validator_add(esbocs, &validator); switch (result) { case 0: log_it_info("✓ Validator added: %s", validator_configs[i].name); log_it_info(" Stake: %s", dap_uint256_to_char(validator_configs[i].stake, NULL)); log_it_info(" Voting power: %.2f", validator.pub.voting_power); log_it_info(" Is local: %s", validator_configs[i].is_local ? "Yes" : "No"); break; case -1: log_it_error("✗ Invalid parameters for validator: %s", validator_configs[i].name); break; case -2: log_it_error("✗ Validator already exists: %s", validator_configs[i].name); break; case -3: log_it_error("✗ Insufficient stake for validator: %s", validator_configs[i].name); break; case -4: log_it_error("✗ Maximum validators reached"); break; default: log_it_error("✗ Unknown error adding validator %s: %d", validator_configs[i].name, result); break; } // Cleanup on failure if (result != 0) { if (!validator_configs[i].is_local) { dap_enc_key_delete(signing_key); } dap_pkey_delete(public_key); DAP_DELETE(validator_addr); } } // Check validator count log_it_info("Total validators added: %d", esbocs->priv.validators ? dap_list_length(esbocs->priv.validators) : 0); // Start ESBOCS consensus int result = dap_chain_cs_esbocs_start(esbocs); switch (result) { case 0: log_it_info("✓ ESBOCS consensus started successfully"); log_it_info(" Current state: %d", esbocs->pub.state); log_it_info(" Current height: %lu", esbocs->pub.current_height); log_it_info(" Is validator: %s", esbocs->pub.is_validator ? "Yes" : "No"); break; case -1: log_it_error("✗ Invalid ESBOCS parameter"); break; case -2: log_it_error("✗ Consensus already running"); break; case -3: log_it_error("✗ Insufficient validators to start consensus"); break; case -4: log_it_error("✗ Consensus startup failed"); break; default: log_it_error("✗ Unknown consensus start error: %d", result); break; } if (result == 0) { log_it_info("ESBOCS consensus is now running and ready to process blocks"); log_it_info(" Minimum validators: %d", config.min_validators); log_it_info(" Round timeout: %d ms", config.round_timeout_ms); log_it_info(" Byzantine fault tolerance: %.1f%%", config.byzantine_threshold * 100); } log_it_info("✓ ESBOCS consensus setup example completed"); // Cleanup if (esbocs) { if (esbocs->pub.state != DAP_CHAIN_CS_ESBOCS_STATE_STOPPED) { dap_chain_cs_esbocs_stop(esbocs); } dap_chain_cs_esbocs_delete(esbocs); } log_it_info("ESBOCS consensus setup example completed"); } ``` ### ESBOCS Voting and Consensus Example ```c #include <dap_chain_cs_esbocs.h> void esbocs_voting_consensus_example() { log_it_info("=== ESBOCS Voting and Consensus Example ==="); // Assume ESBOCS is already initialized from previous example dap_chain_t *chain = dap_chain_find_by_id("testchain"); if (!chain) { log_it_error("✗ Test chain not found"); return; } dap_chain_cs_esbocs_config_t config = { .min_validators = 3, .round_timeout_ms = 15000, .proposal_timeout_ms = 5000, .vote_timeout_ms = 3000 }; dap_chain_cs_esbocs_t *esbocs = dap_chain_cs_esbocs_new(chain, &config); if (!esbocs) { log_it_error("✗ Failed to create ESBOCS instance"); return; } // Add minimal validators (simplified for example) // In practice, this would be done during initialization log_it_info("Setting up validators for consensus simulation..."); // Simulate consensus round uint64_t target_height = chain->last_block_height + 1; log_it_info("Starting consensus round for height: %lu", target_height); // Start new consensus round int result = dap_chain_cs_esbocs_round_start(esbocs, target_height); switch (result) { case 0: log_it_info("✓ Consensus round started successfully"); log_it_info(" Round number: %lu", esbocs->pub.current_round); log_it_info(" Target height: %lu", target_height); log_it_info(" Round start time: %lu", esbocs->pub.round_start_time); break; case -1: log_it_error("✗ Invalid parameters for round start"); goto cleanup; case -2: log_it_error("✗ Previous round not finished"); goto cleanup; case -3: log_it_error("✗ No validators available"); goto cleanup; case -4: log_it_error("✗ Round start failed"); goto cleanup; default: log_it_error("✗ Unknown round start error: %d", result); goto cleanup; } // Create sample block for proposal dap_chain_block_t *sample_block = dap_chain_block_new(); if (!sample_block) { log_it_error("✗ Failed to create sample block"); goto cleanup; } // Set block properties sample_block->hdr.height = target_height; sample_block->hdr.timestamp = dap_time_now(); sample_block->hdr.transactions_count = 3; // Sample transaction count // Create block proposal dap_chain_cs_esbocs_proposal_t *proposal = dap_chain_cs_esbocs_proposal_create(esbocs, sample_block); if (!proposal) { log_it_error("✗ Failed to create block proposal"); goto cleanup_block; } log_it_info("✓ Block proposal created"); log_it_info(" Proposal hash: %s", dap_chain_hash_fast_to_str_new(&proposal->pub.hash)); log_it_info(" Block height: %lu", proposal->pub.height); log_it_info(" Transaction count: %d", proposal->pub.transactions_count); log_it_info(" Block size: %zu bytes", proposal->pub.block_size); // Validate proposal result = dap_chain_cs_esbocs_proposal_validate(esbocs, proposal); switch (result) { case 0: log_it_info("✓ Block proposal validation successful"); break; case -1: log_it_error("✗ Invalid parameters for proposal validation"); goto cleanup_proposal; case -2: log_it_error("✗ Proposal validation failed"); goto cleanup_proposal; case -3: log_it_error("✗ Invalid proposer"); goto cleanup_proposal; case -4: log_it_error("✗ Block validation failed"); goto cleanup_proposal; default: log_it_error("✗ Unknown validation error: %d", result); goto cleanup_proposal; } // Simulate validator voting process log_it_info("Simulating validator voting process..."); // Create votes from different validators dap_chain_cs_esbocs_vote_type_t vote_types[] = { DAP_CHAIN_CS_ESBOCS_VOTE_TYPE_PREVOTE, DAP_CHAIN_CS_ESBOCS_VOTE_TYPE_PRECOMMIT }; for (int vote_phase = 0; vote_phase < 2; vote_phase++) { log_it_info("--- Vote Phase %d (%s) ---", vote_phase + 1, vote_phase == 0 ? "PREVOTE" : "PRECOMMIT"); // Simulate votes from multiple validators for (int i = 0; i < 4; i++) { // Create vote dap_chain_cs_esbocs_vote_t *vote = dap_chain_cs_esbocs_vote_create( esbocs, &proposal->pub.hash, vote_types[vote_phase] ); if (!vote) { log_it_error("✗ Failed to create vote %d", i + 1); continue; } // Simulate vote properties vote->pub.voting_power = 1000.0 + (i * 500.0); // Different voting powers vote->pub.timestamp = dap_time_now(); log_it_info(" Vote %d created:", i + 1); log_it_info(" Voting power: %.1f", vote->pub.voting_power); log_it_info(" Vote type: %s", vote_phase == 0 ? "PREVOTE" : "PRECOMMIT"); // Verify vote result = dap_chain_cs_esbocs_vote_verify(esbocs, vote); switch (result) { case 0: log_it_info(" ✓ Vote verification successful"); break; case -1: log_it_error(" ✗ Invalid vote parameters"); continue; case -2: log_it_error(" ✗ Signature verification failed"); continue; case -3: log_it_error(" ✗ Validator not authorized"); continue; case -4: log_it_error(" ✗ Vote format invalid"); continue; default: log_it_error(" ✗ Unknown verification error: %d", result); continue; } // Add vote to consensus result = dap_chain_cs_esbocs_vote_add(esbocs, vote); switch (result) { case 0: log_it_info(" ✓ Vote added to consensus"); break; case -1: log_it_error(" ✗ Invalid vote parameters"); break; case -2: log_it_error(" ✗ Vote validation failed"); break; case -3: log_it_error(" ✗ Duplicate vote"); break; case -4: log_it_error(" ✗ Round not accepting votes"); break; default: log_it_error(" ✗ Unknown vote add error: %d", result); break; } } // Check if majority is achieved bool has_majority = dap_chain_cs_esbocs_check_majority(esbocs, &proposal->pub.hash); log_it_info(" Majority check result: %s", has_majority ? "ACHIEVED" : "NOT ACHIEVED"); if (has_majority && vote_phase == 1) { // Precommit phase log_it_info(" ✓ Consensus achieved! Proceeding to finalization"); break; } } // Finalize block if consensus achieved result = dap_chain_cs_esbocs_finalize_block(esbocs, proposal); switch (result) { case 0: log_it_info("✓ Block finalized successfully"); log_it_info(" Finalized height: %lu", proposal->pub.height); log_it_info(" Finalized hash: %s", dap_chain_hash_fast_to_str_new(&proposal->pub.hash)); break; case -1: log_it_error("✗ Invalid parameters for finalization"); break; case -2: log_it_error("✗ Insufficient votes for finalization"); break; case -3: log_it_error("✗ Block finalization failed"); break; default: log_it_error("✗ Unknown finalization error: %d", result); break; } // Finish consensus round result = dap_chain_cs_esbocs_round_finish(esbocs); if (result == 0) { log_it_info("✓ Consensus round finished successfully"); } else { log_it_error("✗ Failed to finish consensus round: %d", result); } log_it_info("✓ ESBOCS voting and consensus example completed"); cleanup_proposal: if (proposal) { dap_chain_cs_esbocs_proposal_delete(proposal); } cleanup_block: if (sample_block) { dap_chain_block_delete(sample_block); } cleanup: if (esbocs) { dap_chain_cs_esbocs_stop(esbocs); dap_chain_cs_esbocs_delete(esbocs); } log_it_info("ESBOCS voting and consensus example completed"); } ``` --- *See also: [[Module Consensus|Consensus Overview]], [[Module Consensus - CS None|Simple Consensus]], [[Module Consensus - DAG PoA|DAG Proof of Authority]], [[ETC/Architecture Overview|System Architecture]]*