## Overview
The Mempool module implements transaction memory pool functionality for the Cellframe SDK, providing efficient storage, validation, and management of pending transactions before they are included in blocks. This module handles transaction queueing, prioritization, conflict resolution, and memory management for optimal performance.
*Based on: `dap_chain_mempool.h`, `dap_chain_mempool.c`*
## Document Structure
- [[#Overview|Overview]]
- [[#Module Structures|Module Structures]]
- [[#dap_datum_mempool_t|dap_datum_mempool_t - Mempool Data Structure]]
- [[#Module Functions|Module Functions]]
- [[#Core Mempool Functions|Core Mempool Functions]]
- [[#Transaction Creation Functions|Transaction Creation Functions]]
- [[#Mempool RPC Functions|Mempool RPC Functions]]
- [[#Error Codes|Error Codes]]
- [[#Typical Examples|Typical Examples]]
## Module Structures
### dap_datum_mempool_t
Core mempool structure for storing pending datums and transactions.
```c
typedef struct dap_datum_mempool {
uint16_t version; // Structure version
uint16_t datum_count; // Number of datums in mempool
dap_chain_datum_t **data; // Array of datum pointers
} DAP_ALIGN_PACKED dap_datum_mempool_t;
```
**Public Fields:**
- `version` - Structure version for compatibility
- `datum_count` - Current number of datums stored in mempool
- `data` - Array of pointers to chain datums
**Mempool Constants:**
- `DAP_DATUM_MEMPOOL_VERSION` - Current mempool version ("01")
## Module Functions
### Core Mempool Functions
#### `dap_datum_mempool_init()`
Initialize the mempool subsystem.
```c
int dap_datum_mempool_init(void);
```
**Returns:**
- `0` - Success
- `negative value` - Error code
**Error Conditions:**
- Returns non-zero if mempool initialization fails
**Description:** Initializes the mempool module, sets up data structures, and prepares the system for mempool operations.
#### `dap_chain_mempool_datum_add()`
Add a datum to the mempool.
```c
char *dap_chain_mempool_datum_add(const dap_chain_datum_t *a_datum,
dap_chain_t *a_chain,
const char *a_hash_out_type);
```
**Parameters:**
- `a_datum` (const dap_chain_datum_t*) - Datum to add to mempool
- `a_chain` (dap_chain_t*) - Target chain for the datum
- `a_hash_out_type` (const char*) - Hash output type format
**Returns:**
- `hash string` - Hash of added datum
- `NULL` - Addition failed
**Error Conditions:**
- Returns NULL if datum is invalid
- Returns NULL if chain is not accessible
- Returns NULL if mempool is full
**Description:** Adds a new datum to the mempool and returns its hash for reference.
#### `dap_chain_mempool_filter()`
Filter and clean the mempool.
```c
void dap_chain_mempool_filter(dap_chain_t *a_chain, int *a_removed);
```
**Parameters:**
- `a_chain` (dap_chain_t*) - Chain to filter mempool for
- `a_removed` (int*) - Output parameter for number of removed items
**Returns:**
- No return value (void function)
**Error Conditions:**
- Function handles errors internally
**Description:** Filters the mempool by removing invalid, expired, or processed transactions.
#### `dap_datum_mempool_serialize()`
Serialize mempool data for storage or transmission.
```c
uint8_t* dap_datum_mempool_serialize(dap_datum_mempool_t *datum_mempool,
size_t *size);
```
**Parameters:**
- `datum_mempool` (dap_datum_mempool_t*) - Mempool structure to serialize
- `size` (size_t*) - Output parameter for serialized size
**Returns:**
- `byte array` - Serialized mempool data
- `NULL` - Serialization failed
**Error Conditions:**
- Returns NULL if mempool structure is invalid
- Returns NULL if memory allocation fails
**Description:** Serializes the mempool structure into a byte array for storage or network transmission.
### Transaction Creation Functions
#### `dap_chain_mempool_tx_create()`
Create a standard transaction in the mempool.
```c
char *dap_chain_mempool_tx_create(dap_chain_t *a_chain,
dap_enc_key_t *a_key_from,
const dap_chain_addr_t *a_addr_from,
const dap_chain_addr_t **a_addr_to,
const char a_token_ticker[DAP_CHAIN_TICKER_SIZE_MAX],
uint256_t* a_value,
uint256_t a_value_fee,
const char *a_hash_out_type,
size_t a_tx_num,
dap_time_t a_time_unlock);
```
**Parameters:**
- `a_chain` (dap_chain_t*) - Target chain for transaction
- `a_key_from` (dap_enc_key_t*) - Source address private key
- `a_addr_from` (const dap_chain_addr_t*) - Source address
- `a_addr_to` (const dap_chain_addr_t**) - Array of destination addresses
- `a_token_ticker` (const char[]) - Token ticker symbol
- `a_value` (uint256_t*) - Array of values to transfer
- `a_value_fee` (uint256_t) - Transaction fee
- `a_hash_out_type` (const char*) - Hash output format
- `a_tx_num` (size_t) - Number of transactions to create
- `a_time_unlock` (dap_time_t) - Time when transaction unlocks
**Returns:**
- `transaction hash` - Hash of created transaction
- `NULL` - Creation failed
**Error Conditions:**
- Returns NULL if insufficient funds
- Returns NULL if invalid addresses
- Returns NULL if unsupported token
**Description:** Creates a standard transfer transaction and adds it to the mempool.
#### `dap_chain_mempool_tx_create_cond()`
Create a conditional transaction with service requirements.
```c
char* dap_chain_mempool_tx_create_cond(dap_chain_net_t *a_net,
dap_enc_key_t *a_key_from,
dap_pkey_t *a_key_cond,
const char a_token_ticker[DAP_CHAIN_TICKER_SIZE_MAX],
uint256_t a_value,
uint256_t a_value_per_unit_max,
dap_chain_net_srv_price_unit_uid_t a_unit,
dap_chain_net_srv_uid_t a_srv_uid,
uint256_t a_value_fee,
const void *a_cond,
size_t a_cond_size,
const char *a_hash_out_type);
```
**Parameters:**
- `a_net` (dap_chain_net_t*) - Network context
- `a_key_from` (dap_enc_key_t*) - Source private key
- `a_key_cond` (dap_pkey_t*) - Conditional public key
- `a_token_ticker` (const char[]) - Token ticker symbol
- `a_value` (uint256_t) - Value to transfer
- `a_value_per_unit_max` (uint256_t) - Maximum value per unit
- `a_unit` (dap_chain_net_srv_price_unit_uid_t) - Price unit identifier
- `a_srv_uid` (dap_chain_net_srv_uid_t) - Service identifier
- `a_value_fee` (uint256_t) - Transaction fee
- `a_cond` (const void*) - Condition data
- `a_cond_size` (size_t) - Size of condition data
- `a_hash_out_type` (const char*) - Hash output format
**Returns:**
- `transaction hash` - Hash of created conditional transaction
- `NULL` - Creation failed
**Error Conditions:**
- Returns NULL if condition is invalid
- Returns NULL if service not available
- Returns NULL if insufficient funds
**Description:** Creates a conditional transaction linked to service requirements and adds it to the mempool.
#### `dap_chain_mempool_base_tx_create()`
Create a base transaction from token emission.
```c
char *dap_chain_mempool_base_tx_create(dap_chain_t *a_chain,
dap_chain_hash_fast_t *a_emission_hash,
dap_chain_id_t a_emission_chain_id,
uint256_t a_emission_value,
const char *a_ticker,
dap_chain_addr_t *a_addr_to,
dap_enc_key_t *a_private_key,
const char *a_hash_out_type,
uint256_t a_value_fee);
```
**Parameters:**
- `a_chain` (dap_chain_t*) - Target chain
- `a_emission_hash` (dap_chain_hash_fast_t*) - Emission transaction hash
- `a_emission_chain_id` (dap_chain_id_t) - Emission chain identifier
- `a_emission_value` (uint256_t) - Value from emission
- `a_ticker` (const char*) - Token ticker symbol
- `a_addr_to` (dap_chain_addr_t*) - Destination address
- `a_private_key` (dap_enc_key_t*) - Private key for signing
- `a_hash_out_type` (const char*) - Hash output format
- `a_value_fee` (uint256_t) - Transaction fee
**Returns:**
- `transaction hash` - Hash of created base transaction
- `NULL` - Creation failed
**Error Conditions:**
- Returns NULL if emission hash is invalid
- Returns NULL if insufficient emission value
- Returns NULL if private key is invalid
**Description:** Creates a base transaction from a token emission and adds it to the mempool.
### Mempool RPC Functions
#### `dap_chain_mempool_rpc_init()`
Initialize the mempool RPC interface.
```c
int dap_chain_mempool_rpc_init(void);
```
**Returns:**
- `0` - Success
- `negative value` - Error code
**Error Conditions:**
- Returns non-zero if RPC initialization fails
**Description:** Initializes the RPC interface for mempool operations and queries.
#### `dap_chain_mempool_rpc_handler_list()`
Handle RPC request to list mempool contents.
```c
void dap_chain_mempool_rpc_handler_list(dap_json_rpc_params_t *a_params,
dap_json_rpc_response_t *a_response,
const char *a_method);
```
**Parameters:**
- `a_params` (dap_json_rpc_params_t*) - RPC request parameters
- `a_response` (dap_json_rpc_response_t*) - RPC response object
- `a_method` (const char*) - RPC method name
**Returns:**
- No return value (void function)
**Error Conditions:**
- Sets error in response if parameters are invalid
**Description:** Handles RPC requests to list current mempool contents and statistics.
## Error Codes
### Mempool Operation Error Codes
```c
#define DAP_CHAIN_MEMPOOl_RET_STATUS_SUCCESS 0 // Operation successful
#define DAP_CHAIN_MEMPOOL_RET_STATUS_BAD_ARGUMENTS -100 // Invalid arguments
#define DAP_CHAIN_MEMPOOl_RET_STATUS_WRONG_ADDR -101 // Wrong address format
#define DAP_CHAIN_MEMPOOl_RET_STATUS_CANT_FIND_FINAL_TX_HASH -102 // Cannot find final tx hash
#define DAP_CHAIN_MEMPOOl_RET_STATUS_NOT_NATIVE_TOKEN -103 // Not a native token
#define DAP_CHAIN_MEMPOOl_RET_STATUS_NO_COND_OUT -104 // No conditional output
#define DAP_CHAIN_MEMPOOl_RET_STATUS_NOT_ENOUGH -105 // Insufficient funds
#define DAP_CHAIN_MEMPOOl_RET_STATUS_CANT_ADD_TX_OUT -106 // Cannot add transaction output
#define DAP_CHAIN_MEMPOOl_RET_STATUS_CANT_ADD_SIGN -107 // Cannot add signature
```
### Mempool Action Types
```c
enum {
DAP_DATUM_MEMPOOL_NONE = 0, // No action
DAP_DATUM_MEMPOOL_ADD, // Add datum to mempool
DAP_DATUM_MEMPOOL_CHECK, // Check datum in mempool
DAP_DATUM_MEMPOOL_DEL // Delete datum from mempool
};
```
## Typical Examples
### Basic Mempool Operations Example
```c
#include <dap_chain_mempool.h>
void mempool_basic_example() {
log_it_info("=== Basic Mempool Operations ===");
// Step 1: Initialize mempool
int result = dap_datum_mempool_init();
if (result != 0) {
log_it_error("✗ Failed to initialize mempool: %d", result);
return;
}
log_it_info("✓ Mempool initialized successfully");
// Step 2: Create sample transaction
dap_chain_t *chain = dap_chain_find_by_id(0x0001);
if (!chain) {
log_it_error("✗ Failed to find chain");
return;
}
dap_enc_key_t *key_from = dap_enc_key_new_generate(DAP_ENC_KEY_TYPE_SIG_DILITHIUM, NULL, 0, NULL, 0);
if (!key_from) {
log_it_error("✗ Failed to generate key");
return;
}
log_it_info("✓ Generated source key");
// Step 3: Set up transaction parameters
dap_chain_addr_t addr_from = {0};
dap_chain_addr_t addr_to = {0};
dap_chain_addr_t *addrs_to[] = {&addr_to};
uint256_t values[] = {uint256_from(1000000)}; // 1M units
uint256_t fee = uint256_from(1000); // 1K fee
// Step 4: Create transaction
char *tx_hash = dap_chain_mempool_tx_create(
chain, key_from, &addr_from, (const dap_chain_addr_t**)addrs_to,
"CELL", values, fee, "hex", 1, 0);
if (tx_hash) {
log_it_info("✓ Transaction created: %s", tx_hash);
DAP_DELETE(tx_hash);
} else {
log_it_error("✗ Failed to create transaction");
}
// Step 5: Filter mempool
int removed_count = 0;
dap_chain_mempool_filter(chain, &removed_count);
log_it_info("✓ Mempool filtered, removed %d items", removed_count);
// Step 6: Cleanup
dap_enc_key_delete(key_from);
log_it_info("✓ Cleanup completed");
log_it_info("Basic mempool example completed");
}
```
### Conditional Transaction Example
```c
#include <dap_chain_mempool.h>
void mempool_conditional_example() {
log_it_info("=== Conditional Transaction Example ===");
// Step 1: Get network context
dap_chain_net_t *net = dap_chain_net_by_id(0x0001);
if (!net) {
log_it_error("✗ Failed to get network context");
return;
}
log_it_info("✓ Network context obtained");
// Step 2: Generate keys
dap_enc_key_t *key_from = dap_enc_key_new_generate(DAP_ENC_KEY_TYPE_SIG_DILITHIUM, NULL, 0, NULL, 0);
dap_pkey_t *key_cond = dap_pkey_new_generate(DAP_ENC_KEY_TYPE_SIG_DILITHIUM);
if (!key_from || !key_cond) {
log_it_error("✗ Failed to generate keys");
return;
}
log_it_info("✓ Keys generated successfully");
// Step 3: Set up conditional transaction parameters
uint256_t value = uint256_from(5000000); // 5M units
uint256_t max_per_unit = uint256_from(100); // Max 100 per unit
uint256_t fee = uint256_from(2000); // 2K fee
dap_chain_net_srv_uid_t srv_uid = {.uint64 = 0x01};
dap_chain_net_srv_price_unit_uid_t unit = {.uint32 = 1};
// Step 4: Create condition data
const char condition_data[] = "service_access_condition";
size_t cond_size = strlen(condition_data);
// Step 5: Create conditional transaction
char *tx_hash = dap_chain_mempool_tx_create_cond(
net, key_from, key_cond, "CELL", value, max_per_unit,
unit, srv_uid, fee, condition_data, cond_size, "hex");
if (tx_hash) {
log_it_info("✓ Conditional transaction created: %s", tx_hash);
DAP_DELETE(tx_hash);
} else {
log_it_error("✗ Failed to create conditional transaction");
}
// Step 6: Cleanup
dap_enc_key_delete(key_from);
dap_pkey_delete(key_cond);
log_it_info("✓ Keys deleted");
log_it_info("Conditional transaction example completed");
}
```
### Mempool RPC Example
```c
#include <dap_chain_mempool_rpc.h>
void mempool_rpc_example() {
log_it_info("=== Mempool RPC Example ===");
// Step 1: Initialize mempool RPC
int result = dap_chain_mempool_rpc_init();
if (result != 0) {
log_it_error("✗ Failed to initialize mempool RPC: %d", result);
return;
}
log_it_info("✓ Mempool RPC initialized successfully");
// Step 2: Prepare RPC parameters
dap_json_rpc_params_t params = {0};
dap_json_rpc_response_t response = {0};
const char *method = "mempool.list";
// Step 3: Call RPC handler
dap_chain_mempool_rpc_handler_list(¶ms, &response, method);
// Step 4: Check response
if (response.error.code == 0) {
log_it_info("✓ RPC call successful");
if (response.result) {
log_it_info("✓ Response data received");
}
} else {
log_it_error("✗ RPC call failed: %s", response.error.message);
}
// Step 5: Test RPC handler
const char *test_method = "mempool.test";
dap_json_rpc_response_t test_response = {0};
dap_chain_mempool_rpc_handler_test(¶ms, &test_response, test_method);
if (test_response.error.code == 0) {
log_it_info("✓ Test RPC call successful");
} else {
log_it_error("✗ Test RPC call failed: %s", test_response.error.message);
}
log_it_info("Mempool RPC example completed");
}
```
---
*See also: [[Modules/Module Chain|Module Chain]], [[Modules/Module Wallet|Module Wallet]], [[ETC/Development Guide|Development Guide]]*