ESP-IDF: a request and its reply over Noise¶
A Noise link (RFC-0033) carries
frames inside a Noise_NNpsk0_25519_ChaChaPoly_SHA256 session over UDP. This example builds two
of them in one image, a DIAL link and a LISTEN link talking over 127.0.0.1, and sends one
request through them. The LISTEN side echoes it as the reply. The request is the session’s
confirmation and the reply its acknowledgement, so the initiator reports UP after two round
trips.
What to notice¶
One Kconfig option turns it on.
CONFIG_LIBTRACER_NOISE_CRYPTO_PSA=yinsdkconfig.defaultsmakes the component define the PSA backend and selects the mbedTLS ciphers ESP-IDF leaves off. The module is header-only, so an image without the option compiles none of it.The application sizes mbedTLS’s key-slot table.
main/psa_slots.his passed asMBEDTLS_USER_CONFIG_FILEfrom the projectCMakeLists.txt. The rule is 6 slots per Noise link, so these two links need 12, each 32 B. Without static slotssecurity_noise_psa.hpprefuses to build.The library holds no key, no entropy and no clock. The host type gives it the key store (
resolve_psk), the random source (ephemeral, PSA’s, backed by the hardware RNG) and the initiator counter (next_counter, anoise::boot_counter_t). The clock reaches the links as thenowpassed tosweep. A real node keeps its PSK in its own secure storage and persists the boot number once per boot before its first attempt.The session state is one block. Each link draws one block from its
memory.state, the net sub-pool by default. The example prints its size next to the link object’s.lwIP serves
127.0.0.1only with its loopback interface, sosdkconfig.defaultssetsCONFIG_LWIP_NETIF_LOOPBACK=y.Board-only, named and not run: to reach a host or a second board instead, give the DIAL link that peer’s address and run a LISTEN link with the same PSK there, once the board has joined a network (Wi-Fi or Ethernet bring-up, which is the application’s).
What it costs on an ESP32-C6¶
Measured with ESP-IDF 6.0 (mbedTLS 4) and GCC 15.2 at -Os. The flash rows compare this image
with the same two-link echo over plain UDP, with no Noise link and no PSA.
bytes |
|
|---|---|
per link: the |
632 |
per link: the session-state block (PSK state, handshake cipher, both session slots of 48 B each, the handshake slot and its stored messages) |
496 |
per image: mbedTLS’s PSA key-slot table at 12 slots of 32 B ( |
820 |
per image: other static RAM ( |
396 |
flash: mbedTLS’s PSA crypto (X25519, ChaCha20-Poly1305, SHA-256, HKDF) |
100,291 |
flash: what else the image grows by in ESP-IDF’s components (NVS, which PSA’s key storage uses, the SHA and DMA drivers, eFuse, stdio) |
21,917 |
flash: the link code, the host type and the example app |
11,318 |
The UDP carrier under each link costs what the one-link example shows. Handshake time on silicon is not measured yet: no board was attached.
Source¶
1/*
2 * SPDX-License-Identifier: Apache-2.0
3 * SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
4 */
5
6/**
7 * @file
8 * @brief ONE CONCEPT: a Noise link (RFC-0033) carries one request and its reply inside an
9 * NNpsk0 session over UDP, with every seam the application's own.
10 *
11 * Two links in one image talk over 127.0.0.1: a DIAL link (the initiator) and a LISTEN link
12 * (the responder), each over its own `udp_transport_t`. The DIAL side sends one request; the
13 * LISTEN side echoes it as the reply. The request is the session's confirmation and the reply
14 * its acknowledgement, so the initiator reports `UP` after two round trips (reference/23 §4).
15 *
16 * The library holds no key, no entropy and no clock. The application gives it:
17 * - the key store (`resolve_psk`), here one compiled-in PSK. A real node keeps it in its own
18 * secure storage;
19 * - the random source (`ephemeral`), here PSA's, which ESP-IDF backs with the hardware RNG;
20 * - the initiator counter (`next_counter`), here a `boot_counter_t`. A real node raises and
21 * persists the boot number once per boot (in NVS, for example) before its first attempt;
22 * - the clock, as the `now` passed to `sweep`.
23 *
24 * Board-only step, not run here: to reach a host or a second board instead, give the DIAL link
25 * that peer's address and run a LISTEN link with the same PSK there, once the board has joined a
26 * network (Wi-Fi or Ethernet bring-up, which is the application's and not libtracer's).
27 */
28
29#include <array>
30#include <atomic>
31#include <chrono>
32#include <cstdint>
33#include <cstdio>
34#include <cstdlib>
35#include <cstring>
36#include <span>
37#include <string_view>
38#include <thread>
39#include <vector>
40
41#include "libtracer/mem_source.hpp"
42#include "libtracer/tlv_emit.hpp"
43#include "libtracer/transport_noise.hpp"
44#include "libtracer/transport_udp.hpp"
45#include "psa/crypto.h"
46#include "sdkconfig.h"
47#if !CONFIG_IDF_TARGET_LINUX
48#include "esp_netif.h"
49#endif
50
51namespace {
52
53namespace noise = tr::net::noise;
54
55/** @brief An example PSK. Never ship a key in source: a node resolves it from its key store. */
56constexpr std::array<std::uint8_t, 32> kExamplePsk = {
57 0x6e, 0x6f, 0x69, 0x73, 0x65, 0x2d, 0x6c, 0x69, 0x6e, 0x6b, 0x2d, 0x65, 0x78, 0x61, 0x6d, 0x70,
58 0x6c, 0x65, 0x2d, 0x6b, 0x65, 0x79, 0x2d, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38};
59
60/** @brief The application's seams (`noise::link_host`). */
61struct app_host_t {
62 noise::boot_counter_t counter{.boot = 1}; /**< @brief Boot 1: a real node persists it. */
63
64 /** @brief The key store: one PSK, under one name. */
65 bool resolve_psk(std::string_view ref, noise::key32_t& out) {
66 if (ref != "example-psk") return false;
67 std::memcpy(out.data(), kExamplePsk.data(), out.size());
68 return true;
69 }
70 /** @brief A fresh ephemeral private key from PSA's random source. */
71 bool ephemeral(noise::key32_t& out) {
72 return psa_generate_random(reinterpret_cast<std::uint8_t*>(out.data()), out.size()) ==
73 PSA_SUCCESS;
74 }
75 /** @brief Strictly increasing across attempts, and across reboots once `boot` persists. */
76 std::uint64_t next_counter() { return counter.next(); }
77};
78
79/** @brief A Noise link over UDP, on the build's backend (PSA here). */
80using link_t = tr::net::noise_link_t<noise::default_crypto_t, app_host_t, tr::net::udp_transport_t>;
81
82/** @brief The inbound datagram cap: every receive block is this size (see one_link). */
83constexpr std::size_t kMaxDatagram = 1024;
84
85/** @brief The application's monotonic clock, in nanoseconds: the `now` every sweep takes. */
86std::uint64_t now_ns() {
87 return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
88 std::chrono::steady_clock::now().time_since_epoch())
89 .count());
90}
91
92/** @brief The links' config: retries from 20 ms up to 200 ms, a 2 s attempt. */
93tr::net::noise_config_t noise_config() {
94 return tr::net::noise_config_t{.psk_ref = "example-psk",
95 .retry = 20'000'000,
96 .retry_cap = 200'000'000,
97 .attempt = 2'000'000'000,
98 .pending_expiry = 2'000'000'000};
99}
100
101/** @brief The carrier's config: datagrams up to @ref kMaxDatagram. */
102tr::net::udp_config_t udp_config() { return tr::net::udp_config_t{.max_frame = kMaxDatagram}; }
103
104/** @brief Failed checks so far. */
105int g_failures = 0;
106
107/** @brief Print @p what with its verdict and count a failure. */
108void check(bool ok, const char* what) {
109 std::printf(" [%s] %s\n", ok ? "ok" : "FAIL", what);
110 if (!ok) ++g_failures;
111}
112
113/** @brief Print the verdict; on the `linux` target also exit with it, so CI can run this. */
114void finish() {
115 std::printf("RESULT %s\n", g_failures == 0 ? "ok" : "FAIL");
116#if CONFIG_IDF_TARGET_LINUX
117 std::exit(g_failures == 0 ? 0 : 1);
118#endif
119}
120
121/** @brief Sweep both links with the clock until @p done holds or 3 s pass. */
122template <class Pred>
123bool drive(link_t& a, link_t& b, Pred done) {
124 const std::uint64_t start = now_ns();
125 while (now_ns() - start < 3'000'000'000ULL) {
126 const std::uint64_t now = now_ns();
127 (void)a.sweep(now, 0);
128 (void)b.sweep(now, 0);
129 if (done()) return true;
130 std::this_thread::sleep_for(std::chrono::milliseconds(1));
131 }
132 return done();
133}
134
135} // namespace
136
137extern "C" void app_main(void) {
138#if !CONFIG_IDF_TARGET_LINUX
139 ESP_ERROR_CHECK(esp_netif_init()); // starts lwIP; the links' sockets need it
140#endif
141 const psa_status_t init = psa_crypto_init(); // the links call it too; it is idempotent
142 check(init == PSA_SUCCESS, "PSA crypto starts: the backend and the random source are ready");
143 tr::mem::block_source_t& pool = tr::mem::net_source();
144
145 // What a link's session state costs: a Noise link draws one block from `memory.state` (the
146 // net sub-pool by default) beyond what its UDP carrier draws.
147 std::size_t carrier_bytes = 0;
148 {
149 const std::size_t before = pool.stats().in_use;
150 tr::net::udp_transport_t plain(0, {}, 0, udp_config());
151 carrier_bytes = pool.stats().in_use - before;
152 }
153 app_host_t host_a;
154 app_host_t host_b;
155 const std::size_t before = pool.stats().in_use;
156 link_t b(tr::net::conn_role_t::LISTEN, host_b, noise_config(), std::uint16_t{0},
157 std::string_view{}, std::uint16_t{0}, udp_config());
158 const std::size_t link_bytes = pool.stats().in_use - before;
159 link_t a(tr::net::conn_role_t::DIAL, host_a, noise_config(), std::uint16_t{0},
160 std::string_view{"127.0.0.1"}, b.carrier().local_port(), udp_config());
161 check(a.ok() && b.ok(), "both links came up: PSK resolved, state drawn, carriers bound");
162 std::printf("per link: %zu B object, %zu B session state (one block for both sessions)\n",
163 sizeof(link_t), link_bytes - carrier_bytes);
164
165 // The responder echoes each frame back as the reply; the initiator records it.
166 auto echo = [&b](std::span<const std::byte> frame) { b.send(frame); };
167 b.set_receiver(echo);
168 std::atomic<bool> replied{false};
169 auto on_reply = [&replied](std::span<const std::byte>) { replied.store(true); };
170 a.set_receiver(on_reply);
171
172 (void)a.sweep(now_ns(), 0); // deadlines count from the last `now` a link was given
173 (void)b.sweep(now_ns(), 0);
174 const std::uint64_t t0 = now_ns();
175 a.dial();
176 check(drive(a, b, [&a] { return a.link_up(); }),
177 "the initiator holds a session after one round trip");
178 const std::uint64_t t1 = now_ns();
179 std::printf("handshake, both ends in this image: %llu us\n",
180 static_cast<unsigned long long>((t1 - t0) / 1000));
181 check(a.state() == tr::net::link_state_t::DIALING, "not UP yet: the session is unacknowledged");
182
183 std::vector<std::byte> request;
184 const std::string_view text = "hello over Noise";
185 tr::wire::emit_tlv(request, tr::wire::type_t::VALUE, tr::wire::opt_t{},
186 std::as_bytes(std::span(text)));
187 a.send(request); // the confirmation
188 check(drive(a, b, [&replied] { return replied.load(); }),
189 "the reply arrives (the acknowledgement)");
190 check(a.state() == tr::net::link_state_t::UP, "the initiator is UP after two round trips");
191 check(b.count(noise::counter_t::HANDSHAKE_FAILED) == 0 &&
192 b.count(noise::counter_t::DECRYPT_FAILED) == 0,
193 "nothing was refused");
194 finish();
195}
Build and run¶
$ cd integrations/esp-idf/examples/concepts/noise_link
$ idf.py set-target esp32c6 build
$ idf.py flash monitor # board-only
CI builds it for esp32c6, and also builds and runs it on the ESP-IDF linux target, where the
two links bind host UDP ports. See also: the Noise module ·
one link, and its max_frame.