Comprehensive development methodology and best practices guide for building production-grade applications with the Cellframe SDK. This guide covers advanced programming patterns, security considerations, performance optimization, and professional development workflows for blockchain applications.
## Overview
This development guide provides essential methodologies, design patterns, and best practices for creating robust, scalable, and secure applications using the Cellframe SDK. It covers the complete development lifecycle from project planning to deployment and maintenance.
**Development Focus Areas:**
- Professional project architecture and organization
- Secure coding practices and cryptographic integration
- Performance optimization and scalability patterns
- Comprehensive testing and quality assurance
- Production deployment and monitoring strategies
- Team collaboration and code maintenance workflows
## Table of Contents
- [[#Development Philosophy|Development Philosophy]]
- [[#Complete Module Reference|Complete Module Reference]]
- [[#Project Structure|Project Structure]]
- [[#Coding Standards|Coding Standards]]
- [[#Design Patterns|Design Patterns]]
- [[#Error Handling|Error Handling]]
- [[#Memory Management|Memory Management]]
- [[#Concurrency and Threading|Concurrency and Threading]]
- [[#Testing Strategies|Testing Strategies]]
- [[#Performance Optimization|Performance Optimization]]
- [[#Security Best Practices|Security Best Practices]]
- [[#Documentation|Documentation]]
## Development Philosophy
### Core Principles
1. **Reliability First** - Prioritize stability and fault tolerance
2. **Security by Design** - Integrate security considerations from the start
3. **Performance Awareness** - Write efficient code that scales
4. **Maintainability** - Code should be readable and modifiable
5. **Modularity** - Build reusable, composable components
### Development Methodology
```
┌─────────────────────────────────────────────────────────────┐
│ Plan & Design │
├─────────────────────────────────────────────────────────────┤
│ Implement & Test │
├─────────────────────────────────────────────────────────────┤
│ Review & Refactor │
├─────────────────────────────────────────────────────────────┤
│ Deploy & Monitor │
└─────────────────────────────────────────────────────────────┘
```
## Complete Module Reference
All Cellframe SDK modules are now fully documented with practical examples and integration patterns:
### Core Foundation Modules
- **[[Modules/Module DAP Core|Module DAP Core]]** - System initialization, configuration, and utilities
- **[[Modules/Module DAP Crypto|Module DAP Crypto]]** - Cryptographic primitives and post-quantum algorithms
- **[[Modules/Module Common|Module Common]]** - Blockchain data structures and operations
- **[[Modules/Module Chain Network|Module Chain Network]]** - P2P networking and communication
- **[[Modules/Module Wallet|Module Wallet]]** - Wallet operations and key management
- **[[Modules/Module Chain|Module Chain]]** - Core blockchain operations and coordination
- **[[Modules/Module Mempool|Module Mempool]]** - Transaction pool management
### Consensus Mechanisms
- **[[Modules/Module Consensus - DAG PoA|Module Consensus - DAG PoA]]** - DAG Proof of Authority consensus
- **[[Modules/Module Consensus - ESBOCS|Module Consensus - ESBOCS]]** - Enhanced Scalable Byzantine consensus
- **[[Modules/Module Consensus - CS None|Module Consensus - CS None]]** - No consensus mode for testing
### Infrastructure Modules
- **[[Modules/Module Mining|Module Mining]]** - Mining operations and proof-of-work algorithms
- **[[Modules/Module DHT|Module DHT]]** - Distributed hash table for peer discovery
### Complete Service Suite
- **[[Modules/Module Service - Staking|Module Service - Staking]]** - Staking and proof-of-stake functionality
- **[[Modules/Module Service - Voting|Module Service - Voting]]** - Decentralized governance and voting
- **[[Modules/Module Service - Bridge|Module Service - Bridge]]** - Cross-chain bridges and interoperability
- **[[Modules/Module Service - Exchange|Module Service - Exchange]]** - Decentralized exchange and AMM
- **[[Modules/Module Service - VPN|Module Service - VPN]]** - Decentralized VPN with monetization
### Development Resources
- **[[Services Overview]]** - Service architecture and integration patterns
- **[[First Application|First Application]]** - Step-by-step tutorial and integration guide
- **[[Core Components|Core Components]]** - Essential system components and data structures
- **[[ETC/Services Overview|Services Overview]]** - Service configuration and management
- **[[Troubleshooting|Troubleshooting]]** - Common issues and solutions
## Project Structure
### Recommended Directory Layout
```
my-cellframe-project/
├── CMakeLists.txt # Build configuration
├── README.md # Project documentation
├── LICENSE # License information
├── .gitignore # Git ignore rules
├── src/ # Source code
│ ├── main.c # Application entry point
│ ├── core/ # Core application logic
│ │ ├── app.h
│ │ ├── app.c
│ │ └── config.h
│ ├── services/ # Custom services
│ │ ├── my_service.h
│ │ └── my_service.c
│ ├── utils/ # Utility functions
│ │ ├── helpers.h
│ │ └── helpers.c
│ └── tests/ # Unit tests
│ ├── test_main.c
│ └── test_utils.c
├── include/ # Public headers
│ └── my_project.h
├── config/ # Configuration files
│ ├── app.cfg
│ └── logging.cfg
├── scripts/ # Build and utility scripts
│ ├── build.sh
│ └── deploy.sh
├── docs/ # Documentation
│ ├── api.md
│ └── architecture.md
└── third_party/ # External dependencies
└── libs/
```
### CMakeLists.txt Structure
```cmake
cmake_minimum_required(VERSION 3.10)
project(MyCellframeProject VERSION 1.0.0)
# Compiler settings
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -O2")
# Debug build settings
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -DDAP_DEBUG")
add_definitions(-DDAP_SYS_DEBUG)
endif()
# Find dependencies
find_package(PkgConfig REQUIRED)
pkg_check_modules(CELLFRAME REQUIRED cellframe-sdk)
# Include directories
include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/include
${CMAKE_CURRENT_SOURCE_DIR}/src
${CELLFRAME_INCLUDE_DIRS}
)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.c"
"src/*.h"
)
# Create executable
add_executable(${PROJECT_NAME} ${SOURCES})
# Link libraries
target_link_libraries(${PROJECT_NAME} ${CELLFRAME_LIBRARIES})
# Compiler flags
target_compile_options(${PROJECT_NAME} PRIVATE ${CELLFRAME_CFLAGS_OTHER})
# Install targets
install(TARGETS ${PROJECT_NAME} DESTINATION bin)
install(DIRECTORY config/ DESTINATION etc/${PROJECT_NAME})
```
## Coding Standards
### Code Style Guidelines
1. **Naming Conventions**
```c
// Constants: ALL_CAPS with underscores
#define MAX_BUFFER_SIZE 1024
#define DEFAULT_TIMEOUT_MS 5000
// Functions: lowercase with underscores
int process_transaction(dap_chain_datum_tx_t *tx);
void cleanup_resources(void);
// Variables: lowercase with underscores
uint64_t transaction_count = 0;
char *config_file_path = NULL;
// Types: lowercase with _t suffix
typedef struct my_data {
int id;
char name[64];
} my_data_t;
// Enums: uppercase prefix
typedef enum my_state {
MY_STATE_IDLE = 0,
MY_STATE_PROCESSING,
MY_STATE_COMPLETE
} my_state_t;
```
2. **Code Formatting**
```c
// Function definitions
int my_function(int param1, const char *param2)
{
// 4-space indentation
if (param1 < 0) {
log_it_error("Invalid parameter: %d", param1);
return -1;
}
// Local variables grouped at top
size_t data_size = 0;
char *buffer = NULL;
// Logic with clear separation
buffer = DAP_NEW_Z_SIZE(char, MAX_BUFFER_SIZE);
if (!buffer) {
return -ENOMEM;
}
// Cleanup section
DAP_DELETE(buffer);
return 0;
}
```
3. **Header Organization**
```c
// my_module.h
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <dap_common.h>
// Public constants
#define MY_MODULE_VERSION "1.0.0"
// Public types
typedef struct my_module_config {
bool enabled;
uint16_t port;
char *log_file;
} my_module_config_t;
// Public function declarations
int my_module_init(my_module_config_t *config);
int my_module_start(void);
void my_module_stop(void);
void my_module_deinit(void);
```
### Documentation Standards
```c
/**
* @brief Process a blockchain transaction
*
* This function validates and processes a transaction, updating
* the blockchain state and notifying relevant services.
*
* @param tx Pointer to transaction data structure
* @param chain_id Target chain identifier
* @param validate_only If true, only validate without processing
*
* @return 0 on success, negative error code on failure
* @retval -EINVAL Invalid transaction format
* @retval -ENOENT Chain not found
* @retval -ENOMEM Insufficient memory
*
* @note This function is thread-safe
* @warning Transaction must be properly signed
*
* @see dap_chain_datum_tx_verify()
* @see dap_chain_tx_add()
*/
int process_blockchain_transaction(dap_chain_datum_tx_t *tx,
dap_chain_id_t chain_id,
bool validate_only);
```
## Design Patterns
### 1. Service Pattern
```c
// service_template.h
typedef struct my_service {
bool initialized;
bool running;
pthread_mutex_t mutex;
my_service_config_t config;
} my_service_t;
// Service lifecycle functions
int my_service_init(my_service_config_t *config);
int my_service_start(void);
int my_service_stop(void);
void my_service_deinit(void);
// service_template.c
static my_service_t s_service = {0};
int my_service_init(my_service_config_t *config) {
if (s_service.initialized) {
return -EALREADY;
}
if (!config) {
return -EINVAL;
}
// Initialize mutex
if (pthread_mutex_init(&s_service.mutex, NULL) != 0) {
return -1;
}
// Copy configuration
memcpy(&s_service.config, config, sizeof(*config));
s_service.initialized = true;
return 0;
}
```
### 2. Factory Pattern
```c
// crypto_factory.h
typedef enum crypto_type {
CRYPTO_TYPE_HASH,
CRYPTO_TYPE_SIGN,
CRYPTO_TYPE_ENCRYPT
} crypto_type_t;
typedef struct crypto_handler {
crypto_type_t type;
int (*init)(void);
int (*process)(const void *input, size_t input_size, void *output);
void (*cleanup)(void);
} crypto_handler_t;
crypto_handler_t *crypto_factory_create(crypto_type_t type);
void crypto_factory_destroy(crypto_handler_t *handler);
// crypto_factory.c
crypto_handler_t *crypto_factory_create(crypto_type_t type) {
crypto_handler_t *handler = DAP_NEW_Z(crypto_handler_t);
if (!handler) {
return NULL;
}
handler->type = type;
switch (type) {
case CRYPTO_TYPE_HASH:
handler->init = hash_init;
handler->process = hash_process;
handler->cleanup = hash_cleanup;
break;
case CRYPTO_TYPE_SIGN:
handler->init = sign_init;
handler->process = sign_process;
handler->cleanup = sign_cleanup;
break;
default:
DAP_DELETE(handler);
return NULL;
}
return handler;
}
```
### 3. Observer Pattern
```c
// event_system.h
typedef enum event_type {
EVENT_TRANSACTION_RECEIVED,
EVENT_BLOCK_CREATED,
EVENT_CONSENSUS_REACHED
} event_type_t;
typedef struct event_data {
event_type_t type;
void *data;
size_t data_size;
uint64_t timestamp;
} event_data_t;
typedef void (*event_callback_t)(const event_data_t *event, void *user_data);
int event_system_subscribe(event_type_t type, event_callback_t callback, void *user_data);
int event_system_unsubscribe(event_type_t type, event_callback_t callback);
int event_system_publish(const event_data_t *event);
// Usage example
void on_transaction_received(const event_data_t *event, void *user_data) {
dap_chain_datum_tx_t *tx = (dap_chain_datum_tx_t *)event->data;
log_it_info("Received transaction with %zu items", tx->header.tx_items_size);
// Process transaction...
}
// Subscribe to events
event_system_subscribe(EVENT_TRANSACTION_RECEIVED, on_transaction_received, NULL);
```
## Error Handling
### Error Code Standards
```c
// error_codes.h
typedef enum app_error {
APP_ERROR_OK = 0,
APP_ERROR_INVALID_PARAM = -1,
APP_ERROR_NO_MEMORY = -2,
APP_ERROR_NOT_FOUND = -3,
APP_ERROR_ALREADY_EXISTS = -4,
APP_ERROR_NETWORK_ERROR = -5,
APP_ERROR_CRYPTO_ERROR = -6,
APP_ERROR_CONFIG_ERROR = -7,
APP_ERROR_INTERNAL = -100
} app_error_t;
const char *app_error_to_string(app_error_t error);
```
### Error Handling Patterns
1. **Function Return Codes**
```c
int process_data(const char *input, char **output) {
if (!input || !output) {
return APP_ERROR_INVALID_PARAM;
}
*output = DAP_NEW_Z_SIZE(char, strlen(input) + 1);
if (!*output) {
return APP_ERROR_NO_MEMORY;
}
if (process_internal(input, *output) != 0) {
DAP_DELETE(*output);
*output = NULL;
return APP_ERROR_INTERNAL;
}
return APP_ERROR_OK;
}
```
2. **Error Context**
```c
typedef struct error_context {
app_error_t code;
char message[256];
const char *file;
int line;
const char *function;
} error_context_t;
#define SET_ERROR(ctx, err_code, fmt, ...) do { \
(ctx)->code = (err_code); \
snprintf((ctx)->message, sizeof((ctx)->message), fmt, ##__VA_ARGS__); \
(ctx)->file = __FILE__; \
(ctx)->line = __LINE__; \
(ctx)->function = __func__; \
} while(0)
int operation_with_context(const char *data, error_context_t *error) {
if (!data) {
SET_ERROR(error, APP_ERROR_INVALID_PARAM, "Input data is NULL");
return -1;
}
if (strlen(data) == 0) {
SET_ERROR(error, APP_ERROR_INVALID_PARAM, "Input data is empty");
return -1;
}
return 0;
}
```
3. **Resource Cleanup**
```c
int complex_operation(const char *input) {
int ret = 0;
char *buffer = NULL;
FILE *file = NULL;
dap_enc_key_t *key = NULL;
// Resource allocation
buffer = DAP_NEW_Z_SIZE(char, 1024);
if (!buffer) {
ret = -ENOMEM;
goto cleanup;
}
file = fopen("temp.dat", "w");
if (!file) {
ret = -errno;
goto cleanup;
}
key = dap_enc_key_new(DAP_ENC_KEY_TYPE_SIG_DILITHIUM);
if (!key) {
ret = -ENOMEM;
goto cleanup;
}
// Main operation
ret = perform_operation(input, buffer, file, key);
cleanup:
// Cleanup in reverse order
if (key) dap_enc_key_delete(key);
if (file) fclose(file);
if (buffer) DAP_DELETE(buffer);
return ret;
}
```
## Memory Management
### Best Practices
1. **Use SDK Memory Functions**
```c
// Preferred: Use DAP SDK memory functions
void *data = DAP_NEW_Z_SIZE(char, size);
if (data) {
// Use data...
DAP_DELETE(data);
}
// Avoid: Direct malloc/free
void *data = malloc(size); // Avoid this
```
2. **Memory Pool Usage**
```c
// For frequent allocations
typedef struct data_processor {
dap_mempool_t *pool;
size_t max_items;
} data_processor_t;
data_processor_t *processor_create(size_t max_items) {
data_processor_t *proc = DAP_NEW_Z(data_processor_t);
if (!proc) return NULL;
proc->pool = dap_mempool_create(sizeof(my_data_t), max_items);
if (!proc->pool) {
DAP_DELETE(proc);
return NULL;
}
proc->max_items = max_items;
return proc;
}
my_data_t *processor_alloc_data(data_processor_t *proc) {
return (my_data_t *)dap_mempool_alloc(proc->pool);
}
void processor_free_data(data_processor_t *proc, my_data_t *data) {
dap_mempool_free(proc->pool, data);
}
```
3. **Reference Counting**
```c
typedef struct ref_counted_data {
atomic_int ref_count;
size_t data_size;
char data[];
} ref_counted_data_t;
ref_counted_data_t *ref_data_create(size_t size) {
ref_counted_data_t *ref_data = DAP_NEW_Z_SIZE(ref_counted_data_t,
sizeof(ref_counted_data_t) + size);
if (ref_data) {
atomic_init(&ref_data->ref_count, 1);
ref_data->data_size = size;
}
return ref_data;
}
void ref_data_retain(ref_counted_data_t *ref_data) {
if (ref_data) {
atomic_fetch_add(&ref_data->ref_count, 1);
}
}
void ref_data_release(ref_counted_data_t *ref_data) {
if (ref_data && atomic_fetch_sub(&ref_data->ref_count, 1) == 1) {
DAP_DELETE(ref_data);
}
}
```
## Concurrency and Threading
### Thread Safety Patterns
1. **Mutex Protection**
```c
typedef struct thread_safe_counter {
pthread_mutex_t mutex;
uint64_t value;
} thread_safe_counter_t;
thread_safe_counter_t *counter_create(void) {
thread_safe_counter_t *counter = DAP_NEW_Z(thread_safe_counter_t);
if (counter && pthread_mutex_init(&counter->mutex, NULL) != 0) {
DAP_DELETE(counter);
return NULL;
}
return counter;
}
uint64_t counter_increment(thread_safe_counter_t *counter) {
uint64_t new_value;
pthread_mutex_lock(&counter->mutex);
new_value = ++counter->value;
pthread_mutex_unlock(&counter->mutex);
return new_value;
}
```
2. **Atomic Operations**
```c
typedef struct atomic_stats {
atomic_uint64_t requests_processed;
atomic_uint64_t errors_count;
atomic_uint64_t bytes_transferred;
} atomic_stats_t;
void stats_increment_requests(atomic_stats_t *stats) {
atomic_fetch_add(&stats->requests_processed, 1);
}
void stats_add_bytes(atomic_stats_t *stats, uint64_t bytes) {
atomic_fetch_add(&stats->bytes_transferred, bytes);
}
uint64_t stats_get_requests(atomic_stats_t *stats) {
return atomic_load(&stats->requests_processed);
}
```
3. **Worker Thread Pattern**
```c
typedef struct worker_pool {
dap_worker_t **workers;
size_t worker_count;
bool running;
} worker_pool_t;
worker_pool_t *worker_pool_create(size_t worker_count) {
worker_pool_t *pool = DAP_NEW_Z(worker_pool_t);
if (!pool) return NULL;
pool->workers = DAP_NEW_Z_SIZE(dap_worker_t*, worker_count * sizeof(dap_worker_t*));
if (!pool->workers) {
DAP_DELETE(pool);
return NULL;
}
for (size_t i = 0; i < worker_count; i++) {
pool->workers[i] = dap_worker_new();
if (!pool->workers[i]) {
worker_pool_destroy(pool);
return NULL;
}
}
pool->worker_count = worker_count;
return pool;
}
void worker_pool_submit_task(worker_pool_t *pool, dap_worker_callback_t callback, void *arg) {
static atomic_size_t worker_index = 0;
size_t index = atomic_fetch_add(&worker_index, 1) % pool->worker_count;
dap_worker_exec_callback(pool->workers[index], callback, arg);
}
```
## Testing Strategies
### Unit Testing Framework
```c
// test_framework.h
#define TEST_ASSERT(condition) \
do { \
if (!(condition)) { \
fprintf(stderr, "ASSERTION FAILED: %s at %s:%d\n", \
#condition, __FILE__, __LINE__); \
return -1; \
} \
} while(0)
#define TEST_ASSERT_EQ(expected, actual) \
TEST_ASSERT((expected) == (actual))
#define TEST_ASSERT_NULL(ptr) \
TEST_ASSERT((ptr) == NULL)
#define TEST_ASSERT_NOT_NULL(ptr) \
TEST_ASSERT((ptr) != NULL)
typedef int (*test_function_t)(void);
typedef struct test_case {
const char *name;
test_function_t function;
} test_case_t;
int run_tests(test_case_t *tests, size_t count);
// Example test
int test_memory_allocation(void) {
void *ptr = DAP_NEW_Z_SIZE(char, 1024);
TEST_ASSERT_NOT_NULL(ptr);
memset(ptr, 0xAA, 1024);
TEST_ASSERT_EQ(((char*)ptr)[0], 0xAA);
DAP_DELETE(ptr);
return 0;
}
test_case_t crypto_tests[] = {
{"Memory Allocation", test_memory_allocation},
{"Hash Function", test_hash_function},
{"Signature Verification", test_signature_verification}
};
```
### Integration Testing
```c
// integration_test.c
int test_full_transaction_flow(void) {
// Setup test environment
dap_common_init("test", NULL);
dap_enc_key_init();
// Create test transaction
dap_enc_key_t *key = dap_enc_key_new(DAP_ENC_KEY_TYPE_SIG_DILITHIUM);
TEST_ASSERT_NOT_NULL(key);
dap_chain_datum_tx_t *tx = create_test_transaction(key);
TEST_ASSERT_NOT_NULL(tx);
// Process transaction
int result = process_transaction(tx);
TEST_ASSERT_EQ(0, result);
// Verify state changes
uint64_t balance = get_account_balance(test_address);
TEST_ASSERT_EQ(expected_balance, balance);
// Cleanup
dap_chain_datum_tx_delete(tx);
dap_enc_key_delete(key);
dap_enc_key_deinit();
dap_common_deinit();
return 0;
}
```
### Performance Testing
```c
// benchmark.c
typedef struct benchmark_result {
double avg_time_ms;
double min_time_ms;
double max_time_ms;
uint64_t operations_per_second;
} benchmark_result_t;
benchmark_result_t benchmark_function(void (*func)(void), size_t iterations) {
benchmark_result_t result = {0};
double total_time = 0;
double min_time = DBL_MAX;
double max_time = 0;
for (size_t i = 0; i < iterations; i++) {
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
func();
clock_gettime(CLOCK_MONOTONIC, &end);
double elapsed = (end.tv_sec - start.tv_sec) * 1000.0 +
(end.tv_nsec - start.tv_nsec) / 1000000.0;
total_time += elapsed;
if (elapsed < min_time) min_time = elapsed;
if (elapsed > max_time) max_time = elapsed;
}
result.avg_time_ms = total_time / iterations;
result.min_time_ms = min_time;
result.max_time_ms = max_time;
result.operations_per_second = (uint64_t)(1000.0 / result.avg_time_ms);
return result;
}
```
## Performance Optimization
### Profiling and Measurement
```c
// profiler.h
typedef struct profiler_section {
const char *name;
uint64_t call_count;
uint64_t total_time_ns;
uint64_t min_time_ns;
uint64_t max_time_ns;
} profiler_section_t;
#define PROFILE_START(name) \
struct timespec profile_start_##name; \
clock_gettime(CLOCK_MONOTONIC, &profile_start_##name)
#define PROFILE_END(name) \
do { \
struct timespec profile_end_##name; \
clock_gettime(CLOCK_MONOTONIC, &profile_end_##name); \
uint64_t elapsed = (profile_end_##name.tv_sec - profile_start_##name.tv_sec) * 1000000000ULL + \
(profile_end_##name.tv_nsec - profile_start_##name.tv_nsec); \
profiler_record(#name, elapsed); \
} while(0)
void profiler_record(const char *section_name, uint64_t elapsed_ns);
void profiler_report(void);
```
### Optimization Techniques
1. **Memory Access Optimization**
```c
// Cache-friendly data structure
typedef struct soa_particles { // Structure of Arrays
float *positions_x;
float *positions_y;
float *positions_z;
float *velocities_x;
float *velocities_y;
float *velocities_z;
size_t count;
} soa_particles_t;
// Versus Array of Structures (less cache-friendly)
typedef struct aos_particle {
float position[3];
float velocity[3];
} aos_particle_t;
```
2. **Algorithmic Optimization**
```c
// Hash table for O(1) lookups instead of linear search
typedef struct fast_lookup {
dap_hash_table_t *hash_table;
size_t capacity;
} fast_lookup_t;
fast_lookup_t *lookup_create(size_t capacity) {
fast_lookup_t *lookup = DAP_NEW_Z(fast_lookup_t);
if (lookup) {
lookup->hash_table = dap_hash_table_new(capacity);
lookup->capacity = capacity;
}
return lookup;
}
void lookup_insert(fast_lookup_t *lookup, const char *key, void *value) {
dap_hash_table_insert(lookup->hash_table, key, value);
}
void *lookup_find(fast_lookup_t *lookup, const char *key) {
return dap_hash_table_lookup(lookup->hash_table, key);
}
```
## Security Best Practices
### Input Validation
```c
// Input sanitization
int validate_address_string(const char *addr_str) {
if (!addr_str) {
return -EINVAL;
}
size_t len = strlen(addr_str);
if (len < MIN_ADDRESS_LENGTH || len > MAX_ADDRESS_LENGTH) {
return -EINVAL;
}
// Check for valid characters only
for (size_t i = 0; i < len; i++) {
if (!dap_is_alpha_and_(addr_str[i]) && !dap_is_digit(addr_str[i])) {
return -EINVAL;
}
}
return 0;
}
// Buffer overflow prevention
int safe_string_copy(char *dest, size_t dest_size, const char *src) {
if (!dest || !src || dest_size == 0) {
return -EINVAL;
}
size_t src_len = strlen(src);
if (src_len >= dest_size) {
return -ENOSPC;
}
dap_strncpy(dest, src, dest_size - 1);
dest[dest_size - 1] = '\0';
return 0;
}
```
### Cryptographic Security
```c
// Secure random number generation
int generate_secure_random(uint8_t *buffer, size_t size) {
if (!buffer || size == 0) {
return -EINVAL;
}
// Use system random source
FILE *urandom = fopen("/dev/urandom", "rb");
if (!urandom) {
return -errno;
}
size_t bytes_read = fread(buffer, 1, size, urandom);
fclose(urandom);
if (bytes_read != size) {
// Clear partial data
memset(buffer, 0, bytes_read);
return -EIO;
}
return 0;
}
// Secure memory cleanup
void secure_cleanup(void *ptr, size_t size) {
if (ptr && size > 0) {
// Overwrite with random data
volatile uint8_t *p = (volatile uint8_t *)ptr;
for (size_t i = 0; i < size; i++) {
p[i] = 0;
}
}
}
```
## Documentation
### Code Documentation
1. **API Documentation**
```c
/**
* @defgroup crypto Cryptographic Functions
* @brief High-level cryptographic operations
* @{
*/
/**
* @brief Create a digital signature for data
*
* This function creates a cryptographic signature using the specified
* private key and signature algorithm. The signature can later be
* verified using the corresponding public key.
*
* @param[in] key Private key for signing
* @param[in] data Data to be signed
* @param[in] data_size Size of data in bytes
* @param[in] sig_type Signature algorithm type
* @param[out] signature_out Pointer to store created signature
*
* @return 0 on success, negative error code on failure
* @retval 0 Signature created successfully
* @retval -EINVAL Invalid parameters
* @retval -ENOMEM Insufficient memory
* @retval -ENOSYS Signature type not supported
*
* @pre key must be a valid private key
* @pre data must not be NULL if data_size > 0
* @pre signature_out must not be NULL
*
* @post On success, *signature_out contains a valid signature
* @post On failure, *signature_out is set to NULL
*
* @note Caller is responsible for freeing the returned signature
* @warning Private key must be kept secure
*
* @see verify_signature()
* @see dap_enc_key_new()
*/
int create_signature(dap_enc_key_t *key,
const void *data,
size_t data_size,
dap_sign_type_t sig_type,
dap_sign_t **signature_out);
/** @} */ // end of crypto group
```
2. **Architecture Documentation**
```markdown
# Module Architecture
## Overview
This module implements the transaction processing pipeline for the Cellframe blockchain.
## Components
- **Transaction Validator**: Validates transaction format and signatures
- **State Manager**: Manages blockchain state transitions
- **Event Publisher**: Publishes transaction events to subscribers
## Data Flow
```
Incoming TX → Validator → State Manager → Event Publisher → Completion
```
## Threading Model
- Main thread: Receives transactions from network
- Validator threads: Process transaction validation (CPU-bound)
- State thread: Applies state changes (single-threaded for consistency)
- Event thread: Publishes events asynchronously
## Error Handling
All errors are logged with appropriate severity levels and returned as
negative error codes following the POSIX convention.
```
### Best Practices
1. **Keep documentation up-to-date** with code changes
2. **Use clear, concise language** in comments
3. **Document the "why"**, not just the "what"
4. **Include examples** for complex APIs
5. **Document error conditions** and recovery strategies
6. **Use consistent formatting** and style
## Next Steps
- [[First Application|Create your first application]]
- [[Services Overview|Understand SDK services]]
- [[Troubleshooting|Debug common issues]]
- [[Architecture Overview|Learn the architecture]]
---
*See also: [[../Cellframe SDK Reference|Main Page]], [[Building from Source|Building]], [[Troubleshooting|Troubleshooting Guide]]*