Complete step-by-step tutorial for creating your first Cellframe SDK application. This comprehensive guide covers project setup, core concepts, cryptographic operations, and advanced features with detailed examples and troubleshooting.
## Overview
This tutorial guides you through building a complete Cellframe SDK application from scratch. You'll learn essential concepts, implement key features, and understand best practices for SDK development.
**What You'll Build:**
- Complete SDK application with initialization and cleanup
- Cryptographic operations (hashing, signatures, addresses)
- Configuration management system
- Network integration with event handling
- Professional error handling and logging
## Document Structure
- [[#Overview|Overview]]
- [[#Prerequisites|Prerequisites]]
- [[#System Requirements|System Requirements]]
- [[#Development Environment|Development Environment]]
- [[#SDK Installation|SDK Installation]]
- [[#Project Setup|Project Setup]]
- [[#Project Structure|Project Structure]]
- [[#Build Configuration|Build Configuration]]
- [[#Configuration Management|Configuration Management]]
- [[#Core Application|Core Application]]
- [[#Application Initialization|Application Initialization]]
- [[#Logging System|Logging System]]
- [[#Error Handling|Error Handling]]
- [[#Cryptographic Features|Cryptographic Features]]
- [[#Hash Operations|Hash Operations]]
- [[#Digital Signatures|Digital Signatures]]
- [[#Address Generation|Address Generation]]
- [[#Network Integration|Network Integration]]
- [[#Event System|Event System]]
- [[#Network Operations|Network Operations]]
- [[#Client Connectivity|Client Connectivity]]
- [[#Complete Application|Complete Application]]
- [[#Building & Testing|Building & Testing]]
- [[#Troubleshooting|Troubleshooting]]
## Prerequisites
### System Requirements
#### Development Environment
- **Operating System:** Linux (Ubuntu 18.04+), macOS (10.14+), or Windows 10+
- **Architecture:** x86_64 or ARM64
- **Memory:** 4GB RAM minimum, 8GB recommended
- **Storage:** 2GB free space for development tools and SDK
#### Required Tools
- **C Compiler:** GCC 7+, Clang 8+, or MSVC 2019+
- **CMake:** 3.10+ (3.16+ recommended)
- **Git:** 2.20+ for version control
- **Text Editor:** VS Code, CLion, or preferred IDE
### Development Environment
#### Linux Setup Script
```bash
#!/bin/bash
# Development Environment Setup
setup_development_environment() {
log_it "=== Setting Up Development Environment ==="
# Detect distribution
if [ -f /etc/os-release ]; then
. /etc/os-release
DISTRO=$ID
else
log_it "ERROR: Cannot detect Linux distribution"
return 1
fi
case "$DISTRO" in
"ubuntu"|"debian")
setup_debian_development
;;
"fedora"|"rhel"|"centos")
setup_redhat_development
;;
*)
log_it "WARNING: Unsupported distribution, using generic setup"
setup_generic_development
;;
esac
}
setup_debian_development() {
log_it "Setting up Debian/Ubuntu development environment..."
# Update package database
sudo apt-get update
# Install essential development tools
sudo apt-get install -y \
build-essential \
cmake \
git \
pkg-config \
gdb \
valgrind
# Install development libraries
sudo apt-get install -y \
libssl-dev \
libjson-c-dev \
libsqlite3-dev \
libcurl4-openssl-dev
# Install optional tools
sudo apt-get install -y \
clang-format \
cppcheck \
doxygen
log_it "✓ Development environment ready"
}
log_it() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
```
### SDK Installation
#### Verify SDK Installation
```bash
verify_sdk_installation() {
log_it "=== Verifying Cellframe SDK Installation ==="
# Check pkg-config
if ! command -v pkg-config &> /dev/null; then
log_it "ERROR: pkg-config not found"
return 1
fi
# Check for SDK package
if ! pkg-config --exists cellframe-sdk; then
log_it "ERROR: Cellframe SDK not found in pkg-config"
log_it "Install the SDK using: [[Installation Guide|Installation Guide]]"
return 1
fi
# Show SDK information
local sdk_version=$(pkg-config --modversion cellframe-sdk)
local sdk_cflags=$(pkg-config --cflags cellframe-sdk)
local sdk_libs=$(pkg-config --libs cellframe-sdk)
log_it "SDK Version: $sdk_version"
log_it "SDK CFLAGS: $sdk_cflags"
log_it "SDK Libraries: $sdk_libs"
log_it "✓ SDK installation verified"
return 0
}
```
## Project Setup
### Project Structure
#### Creating Project Directory
```bash
create_project_structure() {
log_it "=== Creating Project Structure ==="
local project_name="${1:-my-cellframe-app}"
# Create main project directory
mkdir -p "$project_name"
cd "$project_name"
# Create subdirectories
mkdir -p src include config tests docs
# Create initial files
touch README.md
touch CMakeLists.txt
touch src/main.c
touch config/app.cfg
touch .gitignore
log_it "Project structure created: $project_name"
log_it "Directory structure:"
tree "$project_name" 2>/dev/null || find "$project_name" -type d | sed 's|[^/]*/| |g'
}
```
#### Complete Project Template
```
my-cellframe-app/
├── CMakeLists.txt # Build configuration
├── README.md # Project documentation
├── .gitignore # Git ignore rules
├── src/ # Source code
│ ├── main.c # Main application
│ ├── app_config.c # Configuration management
│ ├── app_crypto.c # Cryptographic operations
│ └── app_network.c # Network operations
├── include/ # Header files
│ ├── app_config.h
│ ├── app_crypto.h
│ └── app_network.h
├── config/ # Configuration files
│ ├── app.cfg # Main configuration
│ └── logging.cfg # Logging configuration
├── tests/ # Test files
│ └── test_main.c
└── docs/ # Documentation
└── API.md
```
### Build Configuration
#### Professional CMakeLists.txt
```cmake
# CMakeLists.txt - Professional Build Configuration
cmake_minimum_required(VERSION 3.10)
project(MyCellframeApp VERSION 1.0.0 LANGUAGES C)
# Set C standard
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
# Build type
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
# Compiler flags
set(CMAKE_C_FLAGS_DEBUG "-g -O0 -DDEBUG -Wall -Wextra -Wpedantic")
set(CMAKE_C_FLAGS_RELEASE "-O3 -DNDEBUG -Wall")
# Find required packages
find_package(PkgConfig REQUIRED)
pkg_check_modules(CELLFRAME REQUIRED cellframe-sdk)
# Include directories
include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/include
${CELLFRAME_INCLUDE_DIRS}
)
# Source files
set(SOURCES
src/main.c
src/app_config.c
src/app_crypto.c
src/app_network.c
)
# Create executable
add_executable(${PROJECT_NAME} ${SOURCES})
# Link libraries
target_link_libraries(${PROJECT_NAME}
${CELLFRAME_LIBRARIES}
pthread
m
)
# Compiler options
target_compile_options(${PROJECT_NAME} PRIVATE ${CELLFRAME_CFLAGS_OTHER})
# Install configuration
install(TARGETS ${PROJECT_NAME} DESTINATION bin)
install(DIRECTORY config/ DESTINATION etc/${PROJECT_NAME})
# Enable testing
enable_testing()
add_subdirectory(tests)
# Print configuration summary
message(STATUS "Build Configuration:")
message(STATUS " Build Type: ${CMAKE_BUILD_TYPE}")
message(STATUS " C Compiler: ${CMAKE_C_COMPILER}")
message(STATUS " SDK Version: ${CELLFRAME_VERSION}")
message(STATUS " Install Prefix: ${CMAKE_INSTALL_PREFIX}")
```
### Configuration Management
#### Application Configuration File
```ini
# config/app.cfg - Main Application Configuration
[general]
# Application metadata
name=MyCellframeApp
version=1.0.0
author=Your Name
description=My First Cellframe SDK Application
# Runtime configuration
debug_mode=false
log_level=INFO
max_threads=4
[network]
# Network configuration
enabled=true
listen_port=8080
max_connections=100
timeout_seconds=30
[crypto]
# Cryptographic settings
enable_post_quantum=true
default_sign_type=DILITHIUM
key_storage_path=./keys
auto_generate_keys=true
[logging]
# Logging configuration
log_to_file=true
log_file_path=./logs/app.log
log_rotation=true
max_log_size_mb=10
max_log_files=5
[features]
# Feature flags
enable_hashing=true
enable_signatures=true
enable_addresses=true
enable_network_demo=true
```
## Core Application
### Application Initialization
#### Complete Initialization System
```c
// src/main.c - Main Application File
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
// Cellframe SDK headers
#include <dap_common.h>
#include <dap_config.h>
#include <dap_enc_key.h>
#include <dap_crypto.h>
#include <dap_hash.h>
#include <dap_chain_addr.h>
#include <dap_events.h>
// Application headers
#include "app_config.h"
#include "app_crypto.h"
#include "app_network.h"
#define LOG_TAG "MyApp"
// Global application state
typedef struct app_context {
bool initialized;
bool crypto_initialized;
bool network_initialized;
bool config_loaded;
app_config_t *config;
} app_context_t;
static app_context_t g_app_context = {0};
static volatile bool g_app_running = true;
// Function prototypes
static int app_init(void);
static void app_cleanup(void);
static void signal_handler(int sig);
static int run_application(void);
int main(int argc, char *argv[]) {
printf("=== My First Cellframe Application ===\n");
// Install signal handlers
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
// Initialize application
if (app_init() != 0) {
fprintf(stderr, "Failed to initialize application\n");
app_cleanup();
return EXIT_FAILURE;
}
log_it_info("Application initialized successfully");
// Run main application loop
int result = run_application();
// Cleanup and exit
app_cleanup();
printf("=== Application Finished ===\n");
return result;
}
static int app_init(void) {
log_it_info("=== Initializing Application ===");
// Initialize DAP Core
int ret = dap_common_init("MyCellframeApp", "app.log");
if (ret != 0) {
log_it_error("Failed to initialize DAP Core: %d", ret);
return -1;
}
g_app_context.initialized = true;
// Initialize configuration
ret = dap_config_init("./config");
if (ret != 0) {
log_it_error("Failed to initialize configuration: %d", ret);
return -1;
}
// Load application configuration
g_app_context.config = load_app_config();
if (!g_app_context.config) {
log_it_error("Failed to load application configuration");
return -1;
}
g_app_context.config_loaded = true;
// Configure logging
configure_logging(g_app_context.config);
// Initialize cryptography
ret = dap_enc_key_init();
if (ret != 0) {
log_it_error("Failed to initialize cryptography: %d", ret);
return -1;
}
g_app_context.crypto_initialized = true;
// Initialize network if enabled
if (g_app_context.config->network_enabled) {
ret = app_network_init(g_app_context.config);
if (ret != 0) {
log_it_error("Failed to initialize network: %d", ret);
return -1;
}
g_app_context.network_initialized = true;
}
log_it_info("✓ Application initialization complete");
return 0;
}
static void app_cleanup(void) {
log_it_info("=== Cleaning Up Application ===");
// Cleanup in reverse order of initialization
if (g_app_context.network_initialized) {
app_network_cleanup();
g_app_context.network_initialized = false;
}
if (g_app_context.crypto_initialized) {
dap_enc_key_deinit();
g_app_context.crypto_initialized = false;
}
if (g_app_context.config_loaded) {
free_app_config(g_app_context.config);
g_app_context.config = NULL;
g_app_context.config_loaded = false;
}
if (g_app_context.initialized) {
dap_config_deinit();
dap_common_deinit();
g_app_context.initialized = false;
}
log_it_info("✓ Application cleanup complete");
}
static void signal_handler(int sig) {
log_it_info("Received signal %d, shutting down gracefully...", sig);
g_app_running = false;
}
```
### Logging System
#### Professional Logging Configuration
```c
// Enhanced logging system with multiple levels and outputs
void configure_logging(const app_config_t *config) {
log_it_info("=== Configuring Logging System ===");
// Set log level based on configuration
dap_log_level_t log_level = L_INFO;
if (config->debug_mode) {
log_level = L_DEBUG;
} else if (strcmp(config->log_level, "ERROR") == 0) {
log_level = L_ERROR;
} else if (strcmp(config->log_level, "WARNING") == 0) {
log_level = L_WARNING;
} else if (strcmp(config->log_level, "INFO") == 0) {
log_level = L_INFO;
} else if (strcmp(config->log_level, "DEBUG") == 0) {
log_level = L_DEBUG;
}
dap_log_level_set(log_level);
// Configure application name
dap_set_appname(config->app_name);
log_it_info("Logging configured: Level=%s, Debug=%s",
config->log_level,
config->debug_mode ? "ON" : "OFF");
}
// Custom logging macros for application-specific logging
#define APP_LOG_INFO(fmt, ...) \
log_it_info("[APP] " fmt, ##__VA_ARGS__)
#define APP_LOG_WARNING(fmt, ...) \
log_it_warning("[APP] " fmt, ##__VA_ARGS__)
#define APP_LOG_ERROR(fmt, ...) \
log_it_error("[APP] " fmt, ##__VA_ARGS__)
#define APP_LOG_DEBUG(fmt, ...) \
log_it_debug("[APP] " fmt, ##__VA_ARGS__)
```
## Cryptographic Features
### Hash Operations
#### Comprehensive Hashing Examples
```c
// src/app_crypto.c - Cryptographic Operations
#include "app_crypto.h"
#include <dap_hash.h>
#include <dap_chain_hash.h>
int demonstrate_hash_operations(void) {
APP_LOG_INFO("=== Hash Operations Demonstration ===");
const char *test_data[] = {
"Hello, Cellframe SDK!",
"This is a longer message for testing hash functions",
"Short",
"" // Empty string test
};
size_t test_count = sizeof(test_data) / sizeof(test_data[0]);
for (size_t i = 0; i < test_count; i++) {
if (hash_string_example(test_data[i]) != 0) {
APP_LOG_ERROR("Hash operation failed for test case %zu", i);
return -1;
}
}
// Demonstrate different hash types
if (demonstrate_hash_types() != 0) {
APP_LOG_ERROR("Hash types demonstration failed");
return -1;
}
APP_LOG_INFO("✓ Hash operations completed successfully");
return 0;
}
static int hash_string_example(const char *data) {
if (!data) {
APP_LOG_ERROR("Invalid input data for hashing");
return -1;
}
size_t data_len = strlen(data);
APP_LOG_INFO("Hashing data: '%s' (length: %zu)", data, data_len);
// Fast hash (SHA3-256 variant)
dap_chain_hash_fast_t fast_hash;
dap_hash_fast(data, data_len, &fast_hash);
char *fast_hash_str = dap_chain_hash_fast_to_str_new(&fast_hash);
if (!fast_hash_str) {
APP_LOG_ERROR("Failed to convert fast hash to string");
return -1;
}
APP_LOG_INFO("Fast Hash: %s", fast_hash_str);
// Verify hash consistency
dap_chain_hash_fast_t verify_hash;
dap_hash_fast(data, data_len, &verify_hash);
if (memcmp(&fast_hash, &verify_hash, sizeof(fast_hash)) == 0) {
APP_LOG_INFO("✓ Hash consistency verified");
} else {
APP_LOG_ERROR("Hash consistency check failed");
DAP_DELETE(fast_hash_str);
return -1;
}
DAP_DELETE(fast_hash_str);
return 0;
}
static int demonstrate_hash_types(void) {
APP_LOG_INFO("=== Hash Types Demonstration ===");
const char *test_message = "Cellframe SDK Hash Types Test";
size_t message_len = strlen(test_message);
// SHA256 Hash
uint8_t sha256_hash[32];
if (dap_hash_sha256(test_message, message_len, sha256_hash) == 0) {
char *sha256_str = dap_enc_base64_encode(sha256_hash, 32);
APP_LOG_INFO("SHA256: %s", sha256_str);
DAP_DELETE(sha256_str);
} else {
APP_LOG_ERROR("SHA256 hash failed");
return -1;
}
// SHA512 Hash
uint8_t sha512_hash[64];
if (dap_hash_sha512(test_message, message_len, sha512_hash) == 0) {
char *sha512_str = dap_enc_base64_encode(sha512_hash, 64);
APP_LOG_INFO("SHA512: %s", sha512_str);
DAP_DELETE(sha512_str);
} else {
APP_LOG_ERROR("SHA512 hash failed");
return -1;
}
return 0;
}
```
### Digital Signatures
#### Advanced Signature Operations
```c
int demonstrate_signature_operations(void) {
APP_LOG_INFO("=== Digital Signature Demonstration ===");
// Test different signature algorithms
dap_enc_key_type_t sig_types[] = {
DAP_ENC_KEY_TYPE_SIG_DILITHIUM,
DAP_ENC_KEY_TYPE_SIG_FALCON,
DAP_ENC_KEY_TYPE_SIG_SPHINCS
};
const char *sig_names[] = {
"Dilithium (Post-Quantum)",
"Falcon (Post-Quantum)",
"SPHINCS+ (Post-Quantum)"
};
size_t sig_count = sizeof(sig_types) / sizeof(sig_types[0]);
for (size_t i = 0; i < sig_count; i++) {
APP_LOG_INFO("Testing signature algorithm: %s", sig_names[i]);
if (test_signature_algorithm(sig_types[i]) != 0) {
APP_LOG_ERROR("Signature test failed for %s", sig_names[i]);
return -1;
}
APP_LOG_INFO("✓ %s test completed", sig_names[i]);
}
return 0;
}
static int test_signature_algorithm(dap_enc_key_type_t key_type) {
// Create signing key
dap_enc_key_t *key = dap_enc_key_new(key_type);
if (!key) {
APP_LOG_ERROR("Failed to create key for type %d", key_type);
return -1;
}
// Test messages
const char *test_messages[] = {
"Simple test message",
"Complex message with special characters: !@#$%^&*()",
"Very long message that tests the signature algorithm with a substantial amount of data to ensure it handles large inputs correctly and maintains security properties across various message sizes and content types."
};
size_t message_count = sizeof(test_messages) / sizeof(test_messages[0]);
for (size_t i = 0; i < message_count; i++) {
if (sign_and_verify_message(key, test_messages[i]) != 0) {
APP_LOG_ERROR("Sign/verify failed for message %zu", i);
dap_enc_key_delete(key);
return -1;
}
}
dap_enc_key_delete(key);
return 0;
}
static int sign_and_verify_message(dap_enc_key_t *key, const char *message) {
size_t message_len = strlen(message);
// Create signature
dap_sign_t *signature = dap_sign_create(key, message, message_len, 0);
if (!signature) {
APP_LOG_ERROR("Failed to create signature");
return -1;
}
size_t sig_size = dap_sign_get_size(signature);
APP_LOG_DEBUG("Created signature: %zu bytes", sig_size);
// Verify signature
int verify_result = dap_sign_verify(signature, key, message, message_len);
if (verify_result != 1) {
APP_LOG_ERROR("Signature verification failed: %d", verify_result);
dap_sign_delete(signature);
return -1;
}
APP_LOG_DEBUG("✓ Signature verified successfully");
// Test with modified message (should fail)
char *modified_message = dap_strdup(message);
if (strlen(modified_message) > 0) {
modified_message[0] = (modified_message[0] == 'A') ? 'B' : 'A';
int invalid_verify = dap_sign_verify(signature, key, modified_message, strlen(modified_message));
if (invalid_verify == 1) {
APP_LOG_ERROR("Signature verification should have failed for modified message");
DAP_DELETE(modified_message);
dap_sign_delete(signature);
return -1;
}
APP_LOG_DEBUG("✓ Modified message correctly rejected");
}
DAP_DELETE(modified_message);
dap_sign_delete(signature);
return 0;
}
```
### Address Generation
#### Comprehensive Address Management
```c
int demonstrate_address_operations(void) {
APP_LOG_INFO("=== Address Generation Demonstration ===");
// Test different network IDs
uint16_t network_ids[] = {0x0001, 0x0002, 0x0003, 0x1234};
size_t network_count = sizeof(network_ids) / sizeof(network_ids[0]);
for (size_t i = 0; i < network_count; i++) {
if (test_address_generation(network_ids[i]) != 0) {
APP_LOG_ERROR("Address generation failed for network 0x%04X", network_ids[i]);
return -1;
}
}
// Test address validation
if (test_address_validation() != 0) {
APP_LOG_ERROR("Address validation tests failed");
return -1;
}
return 0;
}
static int test_address_generation(uint16_t network_id) {
APP_LOG_INFO("Testing address generation for network 0x%04X", network_id);
// Create key for address generation
dap_enc_key_t *key = dap_enc_key_new(DAP_ENC_KEY_TYPE_SIG_DILITHIUM);
if (!key) {
APP_LOG_ERROR("Failed to create key for address generation");
return -1;
}
// Generate address
dap_chain_addr_t *addr = dap_chain_addr_from_key(key, network_id);
if (!addr) {
APP_LOG_ERROR("Failed to generate address");
dap_enc_key_delete(key);
return -1;
}
// Convert to string
char *addr_str = dap_chain_addr_to_str(addr);
if (!addr_str) {
APP_LOG_ERROR("Failed to convert address to string");
DAP_DELETE(addr);
dap_enc_key_delete(key);
return -1;
}
APP_LOG_INFO("Generated address: %s", addr_str);
// Verify address properties
APP_LOG_INFO(" Network ID: 0x%04X", addr->net_id.uint64);
APP_LOG_INFO(" Signature Type: %d", addr->sig_type.type);
// Verify checksum
if (dap_chain_addr_check_sum(addr)) {
APP_LOG_INFO(" Checksum: VALID");
} else {
APP_LOG_ERROR(" Checksum: INVALID");
DAP_DELETE(addr_str);
DAP_DELETE(addr);
dap_enc_key_delete(key);
return -1;
}
// Test address parsing
dap_chain_addr_t *parsed_addr = dap_chain_addr_from_str(addr_str);
if (!parsed_addr) {
APP_LOG_ERROR("Failed to parse address from string");
DAP_DELETE(addr_str);
DAP_DELETE(addr);
dap_enc_key_delete(key);
return -1;
}
// Compare original and parsed addresses
if (memcmp(addr, parsed_addr, sizeof(dap_chain_addr_t)) == 0) {
APP_LOG_INFO(" ✓ Address parsing verified");
} else {
APP_LOG_ERROR(" Address parsing verification failed");
DAP_DELETE(parsed_addr);
DAP_DELETE(addr_str);
DAP_DELETE(addr);
dap_enc_key_delete(key);
return -1;
}
// Cleanup
DAP_DELETE(parsed_addr);
DAP_DELETE(addr_str);
DAP_DELETE(addr);
dap_enc_key_delete(key);
return 0;
}
```
## Network Integration
### Event System
#### Advanced Event Handling
```c
// src/app_network.c - Network Operations
#include "app_network.h"
#include <dap_events.h>
#include <dap_client.h>
static bool s_network_initialized = false;
static dap_events_socket_t *s_server_socket = NULL;
int app_network_init(const app_config_t *config) {
APP_LOG_INFO("=== Initializing Network Subsystem ===");
if (s_network_initialized) {
APP_LOG_WARNING("Network already initialized");
return 0;
}
// Initialize event system
uint32_t cpu_count = dap_get_cpu_count();
APP_LOG_INFO("CPU count: %u", cpu_count);
int ret = dap_events_init(cpu_count, 60);
if (ret != 0) {
APP_LOG_ERROR("Failed to initialize events: %d", ret);
return -1;
}
// Start event system
ret = dap_events_start();
if (ret != 0) {
APP_LOG_ERROR("Failed to start events: %d", ret);
dap_events_deinit();
return -1;
}
// Initialize server if enabled
if (config->network_enabled) {
ret = initialize_server(config);
if (ret != 0) {
APP_LOG_ERROR("Failed to initialize server");
dap_events_stop_all();
dap_events_deinit();
return -1;
}
}
s_network_initialized = true;
APP_LOG_INFO("✓ Network subsystem initialized");
return 0;
}
void app_network_cleanup(void) {
APP_LOG_INFO("=== Cleaning Up Network Subsystem ===");
if (!s_network_initialized) {
return;
}
// Close server socket
if (s_server_socket) {
dap_events_socket_delete(s_server_socket, true);
s_server_socket = NULL;
}
// Stop and cleanup event system
dap_events_stop_all();
dap_events_deinit();
s_network_initialized = false;
APP_LOG_INFO("✓ Network subsystem cleanup complete");
}
static int initialize_server(const app_config_t *config) {
APP_LOG_INFO("Initializing server on port %d", config->listen_port);
// Create server socket
s_server_socket = dap_events_socket_create_listening(
NULL, // Listen on all interfaces
config->listen_port,
server_callback_new_connection
);
if (!s_server_socket) {
APP_LOG_ERROR("Failed to create server socket");
return -1;
}
APP_LOG_INFO("✓ Server listening on port %d", config->listen_port);
return 0;
}
// Server callback for new connections
static void server_callback_new_connection(dap_events_socket_t *a_socket, void *a_arg) {
APP_LOG_INFO("New connection received");
// Set up connection callbacks
a_socket->callbacks.read_callback = server_callback_read;
a_socket->callbacks.write_callback = server_callback_write;
a_socket->callbacks.error_callback = server_callback_error;
// Send welcome message
const char *welcome = "Welcome to My Cellframe Application!\n";
dap_events_socket_write(a_socket, welcome, strlen(welcome));
}
// Handle incoming data
static void server_callback_read(dap_events_socket_t *a_socket, void *a_arg) {
size_t bytes_read = 0;
char buffer[1024];
// Read data
int ret = dap_events_socket_read(a_socket, buffer, sizeof(buffer) - 1, &bytes_read);
if (ret != 0 || bytes_read == 0) {
return;
}
buffer[bytes_read] = '\0';
APP_LOG_INFO("Received data: %s", buffer);
// Echo back the data
char response[1024];
snprintf(response, sizeof(response), "Echo: %s", buffer);
dap_events_socket_write(a_socket, response, strlen(response));
}
```
## Complete Application
### Integrated Application Example
```c
static int run_application(void) {
APP_LOG_INFO("=== Running Main Application ===");
// Display application information
display_app_info();
// Run feature demonstrations
if (g_app_context.config->enable_hashing) {
if (demonstrate_hash_operations() != 0) {
APP_LOG_ERROR("Hash operations failed");
return EXIT_FAILURE;
}
}
if (g_app_context.config->enable_signatures) {
if (demonstrate_signature_operations() != 0) {
APP_LOG_ERROR("Signature operations failed");
return EXIT_FAILURE;
}
}
if (g_app_context.config->enable_addresses) {
if (demonstrate_address_operations() != 0) {
APP_LOG_ERROR("Address operations failed");
return EXIT_FAILURE;
}
}
// Run network demonstration if enabled
if (g_app_context.config->enable_network_demo && g_app_context.network_initialized) {
if (demonstrate_network_operations() != 0) {
APP_LOG_ERROR("Network operations failed");
return EXIT_FAILURE;
}
}
// Main application loop
APP_LOG_INFO("Entering main application loop...");
APP_LOG_INFO("Press Ctrl+C to stop");
while (g_app_running) {
// Application main loop
usleep(100000); // 100ms
// Perform periodic tasks
perform_periodic_tasks();
}
APP_LOG_INFO("Application loop terminated");
return EXIT_SUCCESS;
}
static void display_app_info(void) {
APP_LOG_INFO("=== Application Information ===");
APP_LOG_INFO("Name: %s", g_app_context.config->app_name);
APP_LOG_INFO("Version: %s", g_app_context.config->app_version);
APP_LOG_INFO("Author: %s", g_app_context.config->author);
APP_LOG_INFO("Description: %s", g_app_context.config->description);
APP_LOG_INFO("Debug Mode: %s", g_app_context.config->debug_mode ? "ON" : "OFF");
APP_LOG_INFO("Network Enabled: %s", g_app_context.config->network_enabled ? "ON" : "OFF");
if (g_app_context.config->network_enabled) {
APP_LOG_INFO("Listen Port: %d", g_app_context.config->listen_port);
APP_LOG_INFO("Max Connections: %d", g_app_context.config->max_connections);
}
}
static void perform_periodic_tasks(void) {
static time_t last_status_time = 0;
time_t current_time = time(NULL);
// Print status every 30 seconds
if (current_time - last_status_time >= 30) {
APP_LOG_INFO("Application running normally (uptime: %ld seconds)",
current_time - g_app_start_time);
last_status_time = current_time;
}
}
```
## Building & Testing
### Complete Build Process
```bash
#!/bin/bash
# build.sh - Application Build Script
build_application() {
log_it "=== Building My Cellframe Application ==="
local build_type="${1:-Release}"
local clean_build="${2:-false}"
# Clean previous build if requested
if [ "$clean_build" = "true" ] && [ -d "build" ]; then
log_it "Cleaning previous build..."
rm -rf build
fi
# Create and enter build directory
mkdir -p build
cd build
# Configure with CMake
log_it "Configuring build ($build_type)..."
if ! cmake -DCMAKE_BUILD_TYPE="$build_type" ..; then
log_it "ERROR: CMake configuration failed"
return 1
fi
# Build the application
log_it "Building application..."
local cores=$(nproc 2>/dev/null || echo 4)
if ! make -j"$cores"; then
log_it "ERROR: Build failed"
return 1
fi
log_it "✓ Build completed successfully"
return 0
}
# Test the application
test_application() {
log_it "=== Testing Application ==="
# Run basic tests
if [ -f "./MyCellframeApp" ]; then
log_it "Running application test..."
timeout 10s ./MyCellframeApp --test-mode || {
log_it "Application test completed"
}
else
log_it "ERROR: Application binary not found"
return 1
fi
log_it "✓ Application testing completed"
}
log_it() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
# Build and test
if build_application "$@"; then
test_application
else
exit 1
fi
```
## Troubleshooting
### Common Issues & Solutions
#### Build Issues
```bash
diagnose_build_issues() {
log_it "=== Diagnosing Build Issues ==="
# Check SDK installation
if ! pkg-config --exists cellframe-sdk; then
log_it "ERROR: Cellframe SDK not found"
log_it "Solution: Install SDK using [[Installation Guide|Installation Guide]]"
return 1
fi
# Check compiler
if ! command -v gcc &> /dev/null && ! command -v clang &> /dev/null; then
log_it "ERROR: No suitable C compiler found"
log_it "Solution: Install build-essential (Ubuntu) or development tools"
return 1
fi
# Check CMake version
local cmake_version=$(cmake --version | head -n1 | cut -d' ' -f3)
if ! version_compare "$cmake_version" "3.10.0"; then
log_it "ERROR: CMake version too old: $cmake_version"
log_it "Solution: Update CMake to 3.10 or higher"
return 1
fi
log_it "✓ Build environment appears correct"
}
# Common runtime issues
diagnose_runtime_issues() {
log_it "=== Diagnosing Runtime Issues ==="
# Check configuration file
if [ ! -f "config/app.cfg" ]; then
log_it "WARNING: Configuration file not found"
log_it "Solution: Create config/app.cfg with required settings"
fi
# Check library paths
if ! ldconfig -p | grep -q cellframe; then
log_it "WARNING: Cellframe libraries not in library path"
log_it "Solution: Run 'sudo ldconfig' or set LD_LIBRARY_PATH"
fi
# Check permissions
if [ ! -w "." ]; then
log_it "WARNING: No write permissions in current directory"
log_it "Solution: Run from writable directory or adjust permissions"
fi
log_it "✓ Runtime environment check completed"
}
```
### Getting Help
For additional assistance:
#### Documentation Resources
- **[[Installation Guide|Installation Guide]]** - Complete SDK installation
- **[[Building from Source|Building from Source]]** - Building SDK from source
- **[[Architecture Overview|Architecture Overview]]** - Understanding SDK architecture
- **[[Development Guide|Development Guide]]** - Advanced development topics
- **[[Modules/Module Overview|Module Documentation]]** - Complete API reference
#### Community Support
- **Forum:** [Cellframe Community](https://forum.cellframe.net)
- **Developer Chat:** [Telegram](https://t.me/cellframe_dev_en)
- **Issues:** [GitLab Tracker](https://gitlab.demlabs.net/cellframe/cellframe-sdk/issues)
#### Example Code
- **GitHub Repository:** [Cellframe Examples](https://github.com/cellframe-examples)
- **Tutorial Code:** Available in SDK documentation
---
**See also:** [[Installation Guide|Installation Guide]], [[Building from Source|Building from Source]], [[Architecture Overview|Architecture Overview]], [[Development Guide|Development Guide]]