<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Mohy Fahim - Wireless Embedded Systems]]></title><description><![CDATA[I'm a Software Engineer with a keen interest in IoT, AI, Blockchain, and Data Communication Networks. I work on projects that integrate these technologies to create innovative solutions.]]></description><link>https://mohyfahim.info</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1719505010605/0c3e963c-e009-4e7c-977c-e30a056b350d.png</url><title>Mohy Fahim - Wireless Embedded Systems</title><link>https://mohyfahim.info</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 18:02:05 GMT</lastBuildDate><atom:link href="https://mohyfahim.info/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Rename USB Wi-Fi and LTE Dongles Using udev]]></title><description><![CDATA[Short summary / TL;DR:
My system has an on-board Wi-Fi and several USB network devices (a Realtek Wi-Fi dongle and an RNDIS LTE modem). USB interfaces get unpredictable names like wlxa0a3f0904f79. I solved this by writing udev rules that detect devic...]]></description><link>https://mohyfahim.info/how-to-rename-usb-wi-fi-and-lte-dongles-using-udev</link><guid isPermaLink="true">https://mohyfahim.info/how-to-rename-usb-wi-fi-and-lte-dongles-using-udev</guid><category><![CDATA[Linux]]></category><category><![CDATA[embedded systems]]></category><category><![CDATA[usb]]></category><category><![CDATA[hacking]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Tue, 18 Nov 2025 17:34:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/FO4CR0MnY_k/upload/a3bc5f6527964563856f2d121938c587.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Short summary / TL;DR</strong>:</p>
<p>My system has an on-board Wi-Fi and several USB network devices (a Realtek Wi-Fi dongle and an RNDIS LTE modem). USB interfaces get unpredictable names like wlxa0a3f0904f79. I solved this by writing udev rules that detect devices by USB vendor:product (VID:PID) and (optionally) DRIVER or MAC, then rename them to stable names (wlan-usb and lte-usb). This makes NetworkManager and scripts much simpler and deterministic.</p>
<p>Below is a publishable blog post / personal documentation you can keep, copy, or paste later.</p>
<h1 id="heading-problem-statement">Problem statement</h1>
<p>USB Wi-Fi dongles and USB LTE modems appear with interface names derived from MACs, e.g. wlxa0a3f0904f79.</p>
<p>Names change between different dongles or devices; this breaks static configuration (bridge/NetworkManager profiles, scripts).</p>
<p>I need stable, readable names: wlan-usb for the USB Wi-Fi dongle and lte-usb for the RNDIS/LTE device.</p>
<h1 id="heading-solution-overview">Solution overview</h1>
<p>Use udev rules in <code>/etc/udev/rules.d/</code> to detect the USB device by vendor/product ID (VID:PID), optionally match the driver (e.g., rndis_host) or the MAC, and rename the kernel net interface at creation time using <code>NAME="..."</code>.</p>
<p>This is:</p>
<ul>
<li><p>robust (matches device hardware, not ephemeral kernel names),</p>
</li>
<li><p>deterministic (same device always gets the same name), and</p>
</li>
<li><p>integrates cleanly with NetworkManager once the rename is applied.</p>
</li>
</ul>
<h2 id="heading-exact-udev-rules-i-used">Exact udev rules I used</h2>
<p><code>&gt; Replace 0bda:b812 and 1782:000c with your device VID:PID if different. If you prefer MAC-based match, see the MAC example below.</code></p>
<p>Create <code>/etc/udev/rules.d/10-network-usb.rules</code> with the following contents:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># /etc/udev/rules.d/10-network-usb.rules</span>
<span class="hljs-comment"># Rename Realtek USB Wi-Fi 0bda:b812 -&gt; wlan-usb</span>
SUBSYSTEM==<span class="hljs-string">"net"</span>, ACTION==<span class="hljs-string">"add"</span>, SUBSYSTEMS==<span class="hljs-string">"usb"</span>, \
ATTRS{idVendor}==<span class="hljs-string">"0bda"</span>, ATTRS{idProduct}==<span class="hljs-string">"b812"</span>, \
NAME=<span class="hljs-string">"wlan-usb"</span>

<span class="hljs-comment"># Rename Spreadtrum/Unisoc RNDIS device 1782:000c -&gt; lte-usb</span>
<span class="hljs-comment"># Prefer this rule only for RNDIS driver instances to avoid renaming non-rndis interfaces</span>
SUBSYSTEM==<span class="hljs-string">"net"</span>, ACTION==<span class="hljs-string">"add"</span>, SUBSYSTEMS==<span class="hljs-string">"usb"</span>, \
ATTRS{idVendor}==<span class="hljs-string">"1782"</span>, ATTRS{idProduct}==<span class="hljs-string">"000c"</span>, DRIVER==<span class="hljs-string">"rndis_host"</span>, \
NAME=<span class="hljs-string">"lte-usb"</span>
</code></pre>
<h2 id="heading-how-to-install-amp-test-the-rules-copypaste">How to install &amp; test the rules (copy/paste)</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># create the rule file (example)</span>
sudo tee /etc/udev/rules.d/10-network-usb.rules &gt; /dev/null &lt;&lt;<span class="hljs-string">'EOF’

# Rename Realtek USB Wi-Fi 0bda:b812 -&gt; wlan-usb

SUBSYSTEM=="net", ACTION=="add", SUBSYSTEMS=="usb", ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="b812", NAME="wlan-usb"

# Rename Spreadtrum/Unisoc RNDIS device 1782:000c -&gt; lte-usb
SUBSYSTEM=="net", ACTION=="add", SUBSYSTEMS=="usb", ATTRS{idVendor}=="1782", ATTRS{idProduct}=="000c", DRIVER=="rndis_host", NAME="lte-usb"

EOF</span>
</code></pre>
<h2 id="heading-reload-rules">Reload rules</h2>
<pre><code class="lang-bash">sudo udevadm control --reload
<span class="hljs-comment"># trigger (or unplug &amp; replug the dongles)</span>
sudo udevadm trigger --action=add /sys/class/net/* || <span class="hljs-literal">true</span>
<span class="hljs-comment"># show renamed interfaces</span>
ifconfig -a
</code></pre>
<p>If you unplug and replug the device, you should see <code>wlan-usb</code> and <code>lte-usb</code> appear.</p>
]]></content:encoded></item><item><title><![CDATA[OpenWrt Package Creation: A Quick Guide]]></title><description><![CDATA[This post outlines the process of building and deploying a custom C/C++ package on an OpenWrt-enabled HLK-7628N development board. To set up a build environment quickly, you just need to download the openwrt-sdk for your hardware platform. In this ca...]]></description><link>https://mohyfahim.info/openwrt-package-creation-a-quick-guide</link><guid isPermaLink="true">https://mohyfahim.info/openwrt-package-creation-a-quick-guide</guid><category><![CDATA[OpenWRT]]></category><category><![CDATA[Linux]]></category><category><![CDATA[build system]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Wed, 12 Nov 2025 14:05:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/U52NDoOl6gg/upload/cd937ba9a6f1ba71077049452772b1ff.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This post outlines the process of building and deploying a custom C/C++ package on an OpenWrt-enabled HLK-7628N development board. To set up a build environment quickly, you just need to download the openwrt-sdk for your hardware platform. In this case, I'm using the HLK-7628N dev board, whose <a target="_blank" href="https://downloads.openwrt.org/releases/24.10.0/targets/ramips/mt76x8/openwrt-sdk-24.10.0-ramips-mt76x8_gcc-13.3.0_musl.Linux-x86_64.tar.zst">sdk</a> and <a target="_blank" href="https://downloads.openwrt.org/releases/24.10.0/targets/ramips/mt76x8/openwrt-24.10.0-ramips-mt76x8-hilink_hlk-7628n-squashfs-sysupgrade.bin">firmware</a> can be downloaded from the OpenWrt website.</p>
<h4 id="heading-1-download-sdk-and-firmware">1. Download SDK and Firmware</h4>
<p>First, get the necessary files.</p>
<ul>
<li><p>Go to the <a target="_blank" href="https://downloads.openwrt.org/">OpenWrt Downloads</a> page.</p>
</li>
<li><p>Navigate to your device's target (e.g., <code>targets/ramips/mt76x8</code>).</p>
</li>
<li><p>Download the <strong>SDK</strong> for your specific release (e.g., <code>openwrt-sdk-*-ramips-mt76x8_gcc-*-musl.Linux-x86_64.tar.zst</code>).</p>
</li>
<li><p>Download the <strong>firmware image</strong> (<code>squashfs-sysupgrade.bin</code>) for your board, if you need to flash it.</p>
</li>
</ul>
<h4 id="heading-2-extract-the-sdk">2. Extract the SDK</h4>
<p>Extract the downloaded SDK archive to your desired working directory.</p>
<pre><code class="lang-bash">tar --zstd -xfv openwrt-sdk-*-mt7628_gcc-*-musl.Linux-x86_64.tar.xz
<span class="hljs-built_in">cd</span> openwrt-sdk-* <span class="hljs-comment"># Navigate into the extracted SDK directory</span>
</code></pre>
<h4 id="heading-3-create-package-folder-and-add-to-feeds">3. Create Package Folder and Add to Feeds</h4>
<p>Create your package directory and integrate it with the SDK's build system.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create your package directory</span>
mkdir -p /path/to/sdk/my_custom_feed
src-link my_custom_feed /path/to/sdk/my_custom_feed
<span class="hljs-comment"># Update and install feeds (ensure you're in the SDK root)</span>
./scripts/feeds update -a
./scripts/feeds install -a
</code></pre>
<h4 id="heading-4-write-the-package-makefile-and-source-code">4. Write the Package Makefile and Source Code</h4>
<p>Place your C++ source code and the OpenWrt Makefile in the <code>my_custom_feed/my-first-app</code> directory.</p>
<p><code>my_custom_feed/my-first-app/main.cpp</code></p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">char</span>* argv[])</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello from the HLK-7628!"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><code>my_custom_feed/my-first-app/CMakeLists.txt</code></p>
<pre><code class="lang-plaintext">cmake_minimum_required(VERSION 3.5)
project(my-first-app CXX)

add_executable(my-first-app main.cpp)
install(TARGETS my-first-app  DESTINATION /usr/bin)
</code></pre>
<p><code>my_custom_feed/my-first-app/Makefile</code></p>
<pre><code class="lang-makefile"><span class="hljs-keyword">include</span> <span class="hljs-variable">$(TOPDIR)</span>/rules.mk

PKG_NAME:=my-first-app
PKG_VERSION:=1.0
PKG_RELEASE:=1


SOURCE_DIR:=<span class="hljs-variable">$(TOPDIR)</span>/my_custom_feed/my-first-app
PKG_BUILD_DIR:=<span class="hljs-variable">$(BUILD_DIR)</span>/<span class="hljs-variable">$(PKG_NAME)</span>-<span class="hljs-variable">$(PKG_VERSION)</span>

<span class="hljs-keyword">include</span> <span class="hljs-variable">$(INCLUDE_DIR)</span>/package.mk
<span class="hljs-comment"># You can include different mk file for different build systems...</span>
<span class="hljs-keyword">include</span> <span class="hljs-variable">$(INCLUDE_DIR)</span>/cmake.mk

<span class="hljs-keyword">define</span> Package/my-first-app
       SECTION:=utils        
       CATEGORY:=Utilities
       TITLE:=My First Custom Application
       DEPENDS:=+libstdcpp <span class="hljs-comment"># or other libs</span>
<span class="hljs-keyword">endef</span>

<span class="hljs-keyword">define</span> Build/Prepare
         mkdir -p <span class="hljs-variable">$(PKG_BUILD_DIR)</span>
        cp -r <span class="hljs-variable">$(SOURCE_DIR)</span>/* <span class="hljs-variable">$(PKG_BUILD_DIR)</span>/
<span class="hljs-keyword">endef</span>


<span class="hljs-keyword">define</span> Package/my-first-app/install
  <span class="hljs-variable">$(INSTALL_DIR)</span> $(1)/usr/bin
  <span class="hljs-variable">$(INSTALL_BIN)</span> <span class="hljs-variable">$(PKG_BUILD_DIR)</span>/my-first-app $(1)/usr/bin/
<span class="hljs-keyword">endef</span>

<span class="hljs-variable">$(<span class="hljs-built_in">eval</span> $(<span class="hljs-built_in">call</span> BuildPackage,my-first-app)</span>)
</code></pre>
<h4 id="heading-5-select-the-package-and-build">5. Select the Package and Build</h4>
<p>Configure the SDK to build your package and then compile it.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># From the SDK root directory:</span>
make menuconfig
</code></pre>
<ul>
<li><p>Navigate to <code>Utilities</code>.</p>
</li>
<li><p>Find <code>my-first-app</code> and select it by pressing <code>M</code> (to build as a module/package).</p>
</li>
<li><p>Save and exit.</p>
</li>
</ul>
<pre><code class="lang-bash"><span class="hljs-comment"># Build the package (from the SDK root directory)</span>
./scripts/feeds update my_custom_feed
./scripts/feeds install my-first-app
make package/my-first-app/compile V=s
</code></pre>
<p>Your <code>.ipk</code> package will be in <code>bin/packages/mipsel_24kc/my_custom_feed/</code>.</p>
<h4 id="heading-6-push-to-device-install-and-test">6. Push to Device, Install, and Test</h4>
<p>Transfer the package to your HLK-7628, install it, and verify functionality.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Copy the .ipk to your device (replace with actual IP and filename)</span>
scp bin/packages/mipsel_24kc/my_custom_feed/my-first-app_1.0-1_mipsel_24kc.ipk root@&lt;router_ip&gt;:/tmp/

<span class="hljs-comment"># SSH into your device</span>
ssh root@&lt;router_ip&gt;

<span class="hljs-comment"># Install the package</span>
opkg install /tmp/my-first-app_1.0-1_mipsel_24kc.ipk

<span class="hljs-comment"># Run your application</span>
my-first-app
</code></pre>
<p>You should see: <code>Hello from the HLK-7628!</code></p>
<p>Now that you've seen how to build and deploy your own package, the possibilities are endless. What custom functionality will you add to your HLK-7628?</p>
<p>Try this tutorial for yourself and share your experience in the comments below. I'd love to hear about the custom tools or features you're creating for your own router!</p>
]]></content:encoded></item><item><title><![CDATA[Learning Rust: Developing Your Own Naivechain Blockchain]]></title><description><![CDATA[In the world of blockchain, simplicity is often overshadowed by complex protocols and intricate algorithms. Yet, simplicity has its own charm and power, which is precisely what inspired the creation of Naivechain—a minimal blockchain implementation d...]]></description><link>https://mohyfahim.info/learning-rust-developing-your-own-naivechain-blockchain</link><guid isPermaLink="true">https://mohyfahim.info/learning-rust-developing-your-own-naivechain-blockchain</guid><category><![CDATA[Rust]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Blockchain]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Wed, 07 Aug 2024 15:23:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/0eqgB57xMeA/upload/f24d8e28e6f457a7354c66f5e49ca1ea.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the world of blockchain, simplicity is often overshadowed by complex protocols and intricate algorithms. Yet, simplicity has its own charm and power, which is precisely what inspired the creation of <a target="_blank" href="https://github.com/lhartikk/naivechain">Naivechain</a>—a minimal blockchain implementation designed to teach the basic principles of blockchain technology. In this blog post, I am excited to share a fresh take on Naivechain, rewritten in Rust, and invite you to join me on this journey to improve and optimize the project.</p>
<h3 id="heading-why-rust">Why Rust?</h3>
<p>Rust is known for its performance, safety, and concurrency capabilities. These features make it an ideal choice for blockchain development, where performance and security are paramount. By rewriting Naivechain in Rust, we not only aim to leverage these benefits but also provide an opportunity for developers to learn Rust through a practical and engaging project.</p>
<h3 id="heading-project-overview">Project Overview</h3>
<p>The Rust implementation of Naivechain maintains the core simplicity of the original project while introducing several enhancements. Here’s a quick overview of the project structure:</p>
<ul>
<li><p><strong>Main Component</strong>: Initializes the blockchain and starts the HTTP server.</p>
</li>
<li><p><strong>API Module</strong>: Handles RESTful API requests for interacting with the blockchain.</p>
</li>
<li><p><strong>Engine Module</strong>: Manages the blockchain’s core logic, such as adding new blocks and validating chains.</p>
</li>
<li><p><strong>Chain Module</strong>: Defines the blockchain structure, including blocks and chain management.</p>
</li>
<li><p><strong>Network Module</strong>: Implements peer-to-peer networking for blockchain propagation using Libp2p.</p>
</li>
</ul>
<h3 id="heading-key-features">Key Features</h3>
<ol>
<li><p><strong>Improved Performance</strong>: Rust’s zero-cost abstractions and memory safety features help achieve better performance without sacrificing safety.</p>
</li>
<li><p><strong>Concurrency Support</strong>: By using Rust’s concurrency model, the project can handle multiple requests efficiently, making it more robust and scalable.</p>
</li>
<li><p><strong>Enhanced Networking</strong>: With the integration of Libp2p, the project supports peer-to-peer networking, allowing for decentralized and distributed operation.</p>
</li>
</ol>
<h3 id="heading-get-involved">Get Involved</h3>
<p>This project is an open invitation for collaboration and innovation. Whether you’re a seasoned developer or new to Rust, your ideas and contributions are welcome. Here are some ways you can get involved:</p>
<ul>
<li><p><strong>Review the Code</strong>: Check out the project on GitHub, explore the code, and suggest improvements or optimizations.</p>
</li>
<li><p><strong>Share Your Ideas</strong>: Have a feature in mind that could enhance the project? Share your thoughts, and let’s discuss how we can integrate it.</p>
</li>
<li><p><strong>Contribute</strong>: Found a bug or want to add a new feature? Submit a pull request and become a part of the project’s evolution.</p>
</li>
</ul>
<h3 id="heading-file-structure-overview">File Structure Overview</h3>
<ol>
<li><p><a target="_blank" href="http://main.rs"><code>main.rs</code></a>: The entry point of the application, setting up the Actix Web server and initializing the blockchain state.</p>
</li>
<li><p><a target="_blank" href="http://api.rs"><code>api.rs</code></a>: Handles the HTTP API for interacting with the blockchain, including endpoints for retrieving blocks and mining new ones.</p>
</li>
<li><p><a target="_blank" href="http://chain.rs"><code>chain.rs</code></a>: Defines the core blockchain structures and methods for block validation and manipulation.</p>
</li>
<li><p><a target="_blank" href="http://engine.rs"><code>engine.rs</code></a>: Manages the P2P message handling and processing of blockchain updates from peers.</p>
</li>
<li><p><a target="_blank" href="http://net.rs"><code>net.rs</code></a>: Manages the network layer using Libp2p, implementing P2P communication and network behavior.</p>
</li>
</ol>
<h2 id="heading-chainrs">Chain.rs</h2>
<p>The <a target="_blank" href="http://chain.rs"><code>chain.rs</code></a> file is a crucial part of your blockchain project, as it defines the structure and behavior of the blockchain itself. Below, we'll summarize the code, highlighting the important points to help you understand how it works.</p>
<h3 id="heading-overview">Overview</h3>
<p>The <a target="_blank" href="http://chain.rs"><code>chain.rs</code></a> file consists of two main components: <code>Block</code> and <code>Chain</code>. These structures define the individual blocks in the blockchain and the blockchain itself.</p>
<h3 id="heading-key-structures-and-functions">Key Structures and Functions</h3>
<h4 id="heading-1-block-structure">1. <strong>Block Structure</strong></h4>
<p>The <code>Block</code> structure represents a single block in the blockchain. Each block contains:</p>
<ul>
<li><p><code>index</code>: The position of the block in the chain.</p>
</li>
<li><p><code>previous_hash</code>: The hash of the previous block, ensuring the integrity of the chain.</p>
</li>
<li><p><code>timestamp</code>: The time the block was created.</p>
</li>
<li><p><code>data</code>: The data stored in the block (could be transactions, messages, etc.).</p>
</li>
<li><p><code>hash</code>: The block's own hash, calculated using its contents.</p>
</li>
</ul>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Block</span></span> {
    <span class="hljs-keyword">pub</span> index: <span class="hljs-built_in">usize</span>,
    <span class="hljs-keyword">pub</span> previous_hash: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> timestamp: <span class="hljs-built_in">u64</span>,
    <span class="hljs-keyword">pub</span> data: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> hash: <span class="hljs-built_in">String</span>,
}
</code></pre>
<p><strong>Constructor Functions</strong>:</p>
<ul>
<li><p><code>new_with_hash</code>: Allows creating a block with a predefined hash (for testing or genesis block).</p>
</li>
<li><p><code>new</code>: Creates a new block and calculates its hash using the <code>calculate_hash</code> function.</p>
</li>
</ul>
<h4 id="heading-2-chain-structure">2. <strong>Chain Structure</strong></h4>
<p>The <code>Chain</code> structure represents the blockchain as a whole. It maintains a list of blocks and handles operations on the blockchain.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug, Serialize, Deserialize)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Chain</span></span> {
    <span class="hljs-keyword">pub</span> next_index: <span class="hljs-built_in">usize</span>,
    <span class="hljs-keyword">pub</span> chains: <span class="hljs-built_in">Vec</span>&lt;Block&gt;,
}
</code></pre>
<ul>
<li><p><strong>Important Methods</strong>:</p>
<ul>
<li><p><code>new</code>: Initializes a new blockchain with a genesis block.</p>
</li>
<li><p><code>replace_block_chain</code>: Replaces the current blockchain with a new one if it's valid and longer.</p>
</li>
<li><p><code>is_valid_chain</code>: Validates the entire blockchain to ensure it hasn't been tampered with.</p>
</li>
<li><p><code>is_valid_new_block</code>: Checks if a new block is valid by comparing it with the previous block.</p>
</li>
<li><p><code>get_latest_block</code>: Retrieves the most recent block in the chain.</p>
</li>
<li><p><code>add_block</code>: Adds a new block to the chain if it's valid.</p>
</li>
</ul>
</li>
</ul>
<h4 id="heading-3-hash-functions">3. <strong>Hash Functions</strong></h4>
<p>The file includes two functions to calculate the hash of a block, which is essential for maintaining the chain's integrity:</p>
<ul>
<li><p><code>calculate_hash</code>: Generates a hash for a new block using its index, previous hash, timestamp, and data.</p>
<pre><code class="lang-rust">  <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_hash</span></span>(index: <span class="hljs-built_in">usize</span>, previous_hash: &amp;<span class="hljs-built_in">str</span>, timestamp: <span class="hljs-built_in">u64</span>, data: &amp;<span class="hljs-built_in">str</span>) -&gt; <span class="hljs-built_in">String</span> {
      <span class="hljs-keyword">let</span> block_data = <span class="hljs-built_in">format!</span>(<span class="hljs-string">"{}{}{}{}"</span>, index, previous_hash, timestamp, data);
      <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> hasher = Sha256::new();
      hasher.update(block_data);
      <span class="hljs-keyword">let</span> result = hasher.finalize();
      <span class="hljs-built_in">format!</span>(<span class="hljs-string">"{:x}"</span>, result)
  }
</code></pre>
</li>
</ul>
<p><code>calculate_hash_from_block</code>: Calculates the hash from an existing block structure.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_hash_from_block</span></span>(block: &amp;Block) -&gt; <span class="hljs-built_in">String</span> {
    <span class="hljs-keyword">let</span> block_data = <span class="hljs-built_in">format!</span>(
        <span class="hljs-string">"{}{}{}{}"</span>,
        block.index, block.previous_hash, block.timestamp, block.data
    );
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> hasher = Sha256::new();
    hasher.update(block_data);
    <span class="hljs-keyword">let</span> result = hasher.finalize();
    <span class="hljs-built_in">format!</span>(<span class="hljs-string">"{:x}"</span>, result)
}
</code></pre>
<h3 id="heading-important-points">Important Points</h3>
<ul>
<li><p><strong>Block Creation and Validation</strong>: Blocks are created with a calculated hash to ensure data integrity. Each block points to the previous one using a hash, forming a chain.</p>
</li>
<li><p><strong>Chain Integrity</strong>: The blockchain is validated by checking the genesis block and ensuring all blocks are correctly linked with valid hashes and indices.</p>
</li>
<li><p><strong>Chain Updates</strong>: New blocks are added only if they are valid, and the chain can be replaced if a valid longer chain is received, ensuring consensus among nodes.</p>
</li>
<li><p><strong>Data Structures</strong>: The use of <code>Vec&lt;Block&gt;</code> for storing the chain and <code>usize</code> for indices helps manage the chain efficiently. Serialization with Serde allows easy transmission of blocks over the network.</p>
</li>
</ul>
<p>This <a target="_blank" href="http://chain.rs"><code>chain.rs</code></a> file implements a simple yet effective blockchain mechanism in Rust, encapsulating both the concept of a block and the overall blockchain while ensuring integrity and consensus.</p>
<h2 id="heading-netrs">Net.rs</h2>
<p>The <a target="_blank" href="http://net.rs"><code>net.rs</code></a> file provides the networking functionality for the blockchain project, using the Rust library <code>libp2p</code> for peer-to-peer communication. This file is responsible for managing peer discovery and message exchange in the network, enabling the blockchain to function as a decentralized system.</p>
<h3 id="heading-key-components-and-concepts">Key Components and Concepts</h3>
<h4 id="heading-1-p2pmessage-enum">1. <strong>P2PMessage Enum</strong></h4>
<p>The <code>P2PMessage</code> enum defines the different types of messages that can be exchanged between peers in the network. These messages include:</p>
<ul>
<li><p><code>QueryLatest</code>: Request the latest block from peers.</p>
</li>
<li><p><code>QueryAll</code>: Request the entire blockchain from peers.</p>
</li>
<li><p><code>ResponseBlockchain</code>: Send the current blockchain to peers.</p>
</li>
<li><p><code>QueryPeers</code>: Request the list of peers.</p>
</li>
<li><p><code>ResponsePeers</code>: Respond with a list of peers.</p>
</li>
<li><p><code>AddPeer</code>: Add a new peer to the network.</p>
</li>
</ul>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Serialize, Deserialize, Debug)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">P2PMessage</span></span> {
    QueryLatest,
    QueryAll,
    ResponseBlockchain(<span class="hljs-built_in">Vec</span>&lt;Block&gt;),
    QueryPeers,
    ResponsePeers(<span class="hljs-built_in">Vec</span>&lt;PeerId&gt;),
    AddPeer(<span class="hljs-built_in">String</span>),
}
</code></pre>
<h4 id="heading-2-network-behavior">2. <strong>Network Behavior</strong></h4>
<p>The <code>P2PNetWorkBehaviour</code> struct combines two important network protocols: Gossipsub and mDNS. These protocols facilitate message propagation and peer discovery, respectively.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(NetworkBehaviour)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">P2PNetWorkBehaviour</span></span> {
    <span class="hljs-keyword">pub</span> gossipsub: gossipsub::Behaviour,
    <span class="hljs-keyword">pub</span> mdns: mdns::tokio::Behaviour,
}
</code></pre>
<ul>
<li><p><strong>Gossipsub</strong>: A publish-subscribe protocol that allows nodes to communicate by broadcasting messages to subscribers. It is used for disseminating blockchain updates and other messages.</p>
</li>
<li><p><strong>mDNS (Multicast DNS)</strong>: A protocol for automatic service discovery on a local network, allowing peers to find each other without needing a central registry.</p>
</li>
</ul>
<h4 id="heading-3-transmit-and-receive-handlers">3. <strong>Transmit and Receive Handlers</strong></h4>
<p>These structs manage message transmission and reception between different components of the system, allowing for asynchronous communication.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Clone)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TransmitHandlers</span></span> {
    <span class="hljs-keyword">pub</span> swarm_tx: UnboundedSender&lt;P2PMessage&gt;,
    <span class="hljs-keyword">pub</span> router_tx: UnboundedSender&lt;P2PMessage&gt;,
    <span class="hljs-keyword">pub</span> api_peers_tx: UnboundedSender&lt;P2PMessage&gt;,
}

<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ReceiveHandlers</span></span> {
    <span class="hljs-keyword">pub</span> api_peers_rx: Mutex&lt;UnboundedReceiver&lt;P2PMessage&gt;&gt;,
}
</code></pre>
<h4 id="heading-4-handling-swarm-events">4. <strong>Handling Swarm Events</strong></h4>
<p>The <code>handle_swarm</code> function manages the swarm's events and message handling. It uses <code>tokio::select!</code> to asynchronously handle incoming messages and network events, such as discovering new peers or receiving messages.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle_swarm</span></span>(
    <span class="hljs-keyword">mut</span> swarm: Swarm&lt;P2PNetWorkBehaviour&gt;,
    topic: gossipsub::IdentTopic,
    transmit_handler: TransmitHandlers,
    <span class="hljs-keyword">mut</span> rx: UnboundedReceiver&lt;P2PMessage&gt;,
) {
    log::info!(<span class="hljs-string">"swarm task is started"</span>);

    <span class="hljs-keyword">let</span> handle_msg = |msg: P2PMessage, swarm: &amp;<span class="hljs-keyword">mut</span> Swarm&lt;P2PNetWorkBehaviour&gt;| <span class="hljs-keyword">match</span> msg {
        <span class="hljs-comment">// Handle different message types</span>
    };

    <span class="hljs-keyword">loop</span> {
        tokio::<span class="hljs-built_in">select!</span> {
            <span class="hljs-literal">Some</span>(msg) = rx.recv() =&gt; handle_msg(msg, swarm.borrow_mut()),
            event = swarm.select_next_some() =&gt; <span class="hljs-keyword">match</span> event {
                SwarmEvent::Behaviour(P2PNetWorkBehaviourEvent::Mdns(mdns::Event::Discovered(list))) =&gt; {
                    <span class="hljs-keyword">for</span> (peer_id, _multiaddr) <span class="hljs-keyword">in</span> list {
                        log::info!(<span class="hljs-string">"mDNS discovered a new peer: {peer_id}"</span>);
                        swarm.behaviour_mut().gossipsub.add_explicit_peer(&amp;peer_id);
                    }
                },
                <span class="hljs-comment">// Handle other swarm events</span>
            }
        }
    }
}
</code></pre>
<ul>
<li><p><strong>Peer Discovery</strong>: When a new peer is discovered via mDNS, it is added as an explicit peer in the Gossipsub network.</p>
</li>
<li><p><strong>Message Propagation</strong>: When a message is received or generated, it is published to the network using Gossipsub.</p>
</li>
</ul>
<h4 id="heading-5-configuring-the-network">5. <strong>Configuring the Network</strong></h4>
<p>The <code>config_network</code> function sets up the network configuration, including the transport protocols (TCP and QUIC) and initializes the network behavior (Gossipsub and mDNS).</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">config_network</span></span>(transmit_handler: TransmitHandlers, rx: UnboundedReceiver&lt;P2PMessage&gt;) {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> swarm = libp2p::SwarmBuilder::with_new_identity()
        .with_tokio()
        .with_tcp(
            tcp::Config::default(),
            noise::Config::new,
            yamux::Config::default,
        )
        .unwrap()
        .with_quic()
        .with_behaviour(|key| {
            <span class="hljs-comment">// Configure Gossipsub and mDNS</span>
        })
        .unwrap()
        .with_swarm_config(|c| c.with_idle_connection_timeout(tokio::time::Duration::from_secs(<span class="hljs-number">60</span>)))
        .build();

    <span class="hljs-keyword">let</span> topic = gossipsub::IdentTopic::new(<span class="hljs-string">"test-net"</span>);
    swarm.behaviour_mut().gossipsub.subscribe(&amp;topic).unwrap();

    <span class="hljs-comment">// Start listening on network interfaces</span>
    swarm
        .listen_on(<span class="hljs-string">"/ip4/0.0.0.0/udp/0/quic-v1"</span>.parse().unwrap())
        .unwrap();
    swarm
        .listen_on(<span class="hljs-string">"/ip4/0.0.0.0/tcp/0"</span>.parse().unwrap())
        .unwrap();

    actix_web::rt::spawn(handle_swarm(swarm, topic, transmit_handler, rx));
}
</code></pre>
<ul>
<li><p><strong>Transport Protocols</strong>: The network uses TCP and QUIC for transport, providing reliability and performance.</p>
</li>
<li><p><strong>Message Handling</strong>: The network is configured to handle incoming messages, peer discovery, and message propagation.</p>
</li>
</ul>
<h3 id="heading-important-points-1">Important Points</h3>
<ul>
<li><p><strong>Peer-to-Peer Communication</strong>: This file establishes a decentralized network using libp2p, allowing nodes to communicate and synchronize without a central server.</p>
</li>
<li><p><strong>Message Types</strong>: The <code>P2PMessage</code> enum defines the protocol for exchanging information between nodes, including querying the blockchain and discovering peers.</p>
</li>
<li><p><strong>Network Behavior</strong>: The combination of Gossipsub and mDNS facilitates efficient message propagation and peer discovery, enabling the blockchain to maintain consistency across nodes.</p>
</li>
<li><p><strong>Asynchronous Handling</strong>: The use of <code>tokio</code> and channels for message transmission and reception ensures that the network can handle events and messages efficiently.</p>
</li>
</ul>
<p>The <a target="_blank" href="http://net.rs"><code>net.rs</code></a> file is essential for the decentralized nature of the blockchain, enabling communication and synchronization across a distributed network of peers.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Rewriting NaiveChain in Rust is more than just a technical exercise; it’s a community-driven effort to explore the possibilities of blockchain technology using Rust. By simplifying blockchain concepts, we aim to make learning and contributing accessible to everyone.</p>
<p>I invite you to explore the project on <a target="_blank" href="https://github.com/mohyfahim/naivechain-rs">GitHub</a> and join the discussion. Let’s work together to make this project better, more efficient, and a valuable resource for learners and developers alike.</p>
<p>Thank you for reading, and I look forward to your contributions and insights!</p>
]]></content:encoded></item><item><title><![CDATA[Rust and WebSocket: Building a Peer-to-Peer Network]]></title><description><![CDATA[Creating a peer-to-peer (P2P) network over a WebSocket infrastructure can seem like a daunting task, especially if you're new to asynchronous programming in Rust. However, with the right approach, you can build a robust and efficient P2P network that...]]></description><link>https://mohyfahim.info/rust-and-websocket-building-a-peer-to-peer-network</link><guid isPermaLink="true">https://mohyfahim.info/rust-and-websocket-building-a-peer-to-peer-network</guid><category><![CDATA[Rust]]></category><category><![CDATA[distributed system]]></category><category><![CDATA[websockets]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[asynchronous]]></category><category><![CDATA[networking]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Mon, 05 Aug 2024 08:07:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722789496719/926ef928-0a70-47a7-92b1-bdb958d434a5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Creating a peer-to-peer (P2P) network over a WebSocket infrastructure can seem like a daunting task, especially if you're new to asynchronous programming in Rust. However, with the right approach, you can build a robust and efficient P2P network that allows real-time communication between nodes. In this post, we'll walk through the key components of our Rust-based P2P network code, exploring how each part contributes to building a seamless WebSocket infrastructure. To view the full source code, check out the project's <a target="_blank" href="https://github.com/mohyfahim/p2pws-rs">GitHub</a> repository.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Although there is a well-established project in this area called<a target="_blank" href="https://libp2p.io/"> libp2p</a>, which has also been developed for the Rust language, in this post, we intended to strengthen our Rust skills and, as practice, write a simple P2P network ourselves.</div>
</div>

<h2 id="heading-introduction-to-p2p-networks">Introduction to P2P Networks</h2>
<p>Peer-to-peer networks enable decentralized communication between nodes, allowing data exchange without relying on a central server. Each participant in the network, or "peer," can act as both a <strong>client</strong> and a <strong>server</strong>, fostering direct connections and communication. In our example, we use WebSocket, which provide a full-duplex communication channel over a single TCP connection, to facilitate this real-time interaction.</p>
<h2 id="heading-overview-of-the-project">Overview of the Project</h2>
<p>Our project is structured to demonstrate how to establish a P2P network using WebSocket in Rust, leveraging the power of asynchronous programming with the Tokio runtime. We'll explore the following key components:</p>
<ul>
<li><p><strong>Command-Line Argument Parsing</strong>: We'll use <code>clap</code> to parse the peer URLs and bind address.</p>
</li>
<li><p><strong>WebSocket Actor</strong>: This component manages WebSocket connections to peers.</p>
</li>
<li><p><strong>Network State Management</strong>: We'll maintain the state of the network, including connected peers.</p>
</li>
<li><p><strong>Connection Handling</strong>: We'll manage the lifecycle of WebSocket connections with peers.</p>
</li>
<li><p><strong>Broadcasting Messages</strong>: We'll send messages to all connected peers periodically.</p>
</li>
<li><p><strong>Graceful Shutdown</strong>: We'll handle interruptions gracefully to shut down the network.</p>
</li>
</ul>
<h2 id="heading-understanding-the-code">Understanding the Code</h2>
<h3 id="heading-command-line-argument-parsing">Command-Line Argument Parsing</h3>
<p>We'll start by defining our command-line arguments using <code>clap</code>. This allows us to specify peer URLs and the bind address when starting our P2P node.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Parser, Debug)]</span>
<span class="hljs-meta">#[command(author, version, about, long_about = None)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Args</span></span> {
    <span class="hljs-comment">/// List of client addresses to connect to</span>
    <span class="hljs-meta">#[arg(short, long, value_delimiter = ',', value_parser = parse_peer)]</span>
    peers: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">String</span>&gt;,

    <span class="hljs-comment">/// Address to bind the server</span>
    <span class="hljs-meta">#[arg(short, long, value_parser = parse_bind)]</span>
    bind: <span class="hljs-built_in">String</span>,
}
</code></pre>
<ul>
<li><p><code>--peers</code>: A comma-separated list of WebSocket URLs to connect to as peers.</p>
</li>
<li><p><code>--bind</code>: The address to bind the server for incoming connections.</p>
</li>
</ul>
<h3 id="heading-websocket-actor">WebSocket Actor</h3>
<p>The <code>WebSocketActor</code> struct manages WebSocket connections. It establishes a connection to a given URL and handles the sending and receiving of messages.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">WebSocketActor</span></span> {
    ws_stream: WebSocketStream&lt;MaybeTlsStream&lt;TcpStream&gt;&gt;,
}

<span class="hljs-keyword">impl</span> WebSocketActor {
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">connect</span></span>(url: &amp;<span class="hljs-built_in">str</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;<span class="hljs-keyword">Self</span>&gt; {
        <span class="hljs-keyword">match</span> connect_async(url).<span class="hljs-keyword">await</span> {
            <span class="hljs-literal">Ok</span>((conn, _)) =&gt; {
                log::info!(<span class="hljs-string">"Connected successfully to {}"</span>, url);
                <span class="hljs-literal">Some</span>(WebSocketActor { ws_stream: conn })
            }
            <span class="hljs-literal">Err</span>(e) =&gt; {
                log::error!(<span class="hljs-string">"Connection to {} failed: {:?}"</span>, url, e);
                <span class="hljs-literal">None</span>
            }
        }
    }
}
</code></pre>
<h3 id="heading-network-state-management">Network State Management</h3>
<p>The <code>P2PWebsocketNetwork</code> struct maintains the state of the network, including connected peers and a master sender for message broadcasting.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">P2PWebsocketNetwork</span></span> {
    addresses: Arc&lt;Mutex&lt;HashMap&lt;SocketAddr, UnboundedSender&lt;P2PInnerMessage&gt;&gt;&gt;&gt;,
    master: Arc&lt;Mutex&lt;UnboundedSender&lt;P2PInnerMessage&gt;&gt;&gt;,
}
</code></pre>
<h3 id="heading-connection-handling">Connection Handling</h3>
<p>We'll handle incoming and outgoing connections using the <code>handle_connection</code> and <code>handle_server_connection</code> functions. These functions manage the lifecycle of WebSocket connections, sending and receiving messages.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle_connection</span></span>(
    state: Arc&lt;P2PWebsocketNetwork&gt;,
    conn: WebSocketActor,
    token: CancellationToken,
) {
    <span class="hljs-comment">// Logic for handling connections and message exchange</span>
}
</code></pre>
<h4 id="heading-function-signature">Function Signature</h4>
<ul>
<li><p><code>state</code>: A shared state (<code>Arc&lt;P2PWebsocketNetwork&gt;</code>) that contains the network's information, including connected peers and message handlers.</p>
</li>
<li><p><code>conn</code>: A <code>WebSocketActor</code> instance representing the connection with a peer.</p>
</li>
<li><p><code>token</code>: A <code>CancellationToken</code> used to handle task cancellation for graceful shutdown.</p>
</li>
</ul>
<h4 id="heading-extracting-the-socket-address">Extracting the Socket Address</h4>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> addr = <span class="hljs-keyword">match</span> conn.ws_stream.get_ref() {
    MaybeTlsStream::Plain(f) =&gt; f.peer_addr().unwrap(),
    _ =&gt; {
        <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"tls is not supported yet"</span>);
    }
};
</code></pre>
<ul>
<li><code>addr</code>: The socket address of the peer. The code extracts the peer's address from the WebSocket stream. Currently, only non-TLS (plain) streams are supported.</li>
</ul>
<h4 id="heading-setting-up-the-message-channel">Setting Up the Message Channel</h4>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> (tx, <span class="hljs-keyword">mut</span> rx) = unbounded_channel::&lt;P2PInnerMessage&gt;();
{
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> list = state.addresses.lock().unwrap();
    list.insert(addr, tx.clone());
}
</code></pre>
<ul>
<li><p><code>tx</code> and <code>rx</code>: An unbounded channel for sending and receiving messages (<code>P2PInnerMessage</code>) between this function and other parts of the application.</p>
</li>
<li><p><code>state.addresses</code>: The connected peers' addresses are stored in a shared <code>HashMap</code>, and the new peer's address and its sender (<code>tx</code>) are added to the list.</p>
</li>
</ul>
<h4 id="heading-splitting-the-websocket-stream">Splitting the WebSocket Stream</h4>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> (<span class="hljs-keyword">mut</span> ws_tx, <span class="hljs-keyword">mut</span> ws_rx) = conn.ws_stream.split();
</code></pre>
<ul>
<li><code>ws_tx</code> and <code>ws_rx</code>: The WebSocket stream is split into a sender (<code>ws_tx</code>) and a receiver (<code>ws_rx</code>) to handle incoming and outgoing messages asynchronously.</li>
</ul>
<h4 id="heading-message-handling-loop">Message Handling Loop</h4>
<pre><code class="lang-rust"><span class="hljs-keyword">loop</span> {
    tokio::<span class="hljs-built_in">select!</span> {
        <span class="hljs-literal">Some</span>(msg) = ws_rx.next() =&gt; {
            log::debug!(<span class="hljs-string">"Received: {:?}"</span>, msg);
            <span class="hljs-keyword">match</span> msg {
                <span class="hljs-literal">Ok</span>(msg) =&gt; {
                    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Err</span>(e) = state.master.lock().unwrap().send(P2PInnerMessage {
                        message: msg,
                        tx_handler: tx.clone(),
                    }) {
                        log::error!(<span class="hljs-string">"Failed to send message to master: {:?}"</span>, e);
                    }
                },
                <span class="hljs-literal">Err</span>(e) =&gt; {
                    log::error!(<span class="hljs-string">"Error receiving message or connection closed: {:?}"</span>, e);
                    <span class="hljs-keyword">break</span>
                }
            }
        }
        <span class="hljs-literal">Some</span>(msg) = rx.recv() =&gt; {
            log::debug!(<span class="hljs-string">"Sending: {:?}"</span>, msg);
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Err</span>(e) = ws_tx.send(msg.message).<span class="hljs-keyword">await</span> {
                log::error!(<span class="hljs-string">"Failed to send message on socket: {:?}"</span>, e);
            }
        }
        _ = token.cancelled() =&gt; {
            log::warn!(<span class="hljs-string">"task is cancelled"</span>);
            <span class="hljs-keyword">break</span>
        }
    }
}
</code></pre>
<ul>
<li><p><strong>Incoming Messages (</strong><code>ws_rx</code>): The loop uses <code>tokio::select!</code> to wait for multiple asynchronous events. It first checks for incoming messages from the peer (<code>ws_</code><a target="_blank" href="http://rx.next"><code>rx.next</code></a><code>()</code>).</p>
<ul>
<li><p>If a message is received successfully, it is forwarded to the master handler by sending it through <code>state.master</code>. This allows centralized processing or routing of messages.</p>
</li>
<li><p>If an error occurs (e.g., connection closed), the loop breaks, effectively terminating the connection.</p>
</li>
</ul>
</li>
<li><p><strong>Outgoing Messages (</strong><code>rx</code>): The loop also checks for messages received from the application's internal channels (<code>rx.recv()</code>), intended to be sent to the peer.</p>
<ul>
<li>The message is sent to the peer using <code>ws_tx.send(msg.message).await</code>. Errors in sending are logged.</li>
</ul>
</li>
<li><p><strong>Cancellation Token</strong>: If the cancellation token is triggered (<code>token.cancelled()</code>), the loop breaks, allowing the task to exit cleanly.</p>
</li>
</ul>
<h4 id="heading-removing-the-peer-from-the-list">Removing the Peer from the List</h4>
<pre><code class="lang-rust">{
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> list = state.addresses.lock().unwrap();
    list.remove(&amp;addr);
}
</code></pre>
<p>Once the loop exits (either due to an error or cancellation), the peer's address is removed from the list of connected addresses, ensuring that the state reflects the current network connections accurately.</p>
<p>The <code>handle_server_connection</code> function operates as described above.</p>
<h3 id="heading-broadcasting-messages">Broadcasting Messages</h3>
<p>Our <code>broadcast</code> function sends a message to all connected peers periodically, demonstrating the P2P network's ability to propagate information.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">broadcast</span></span>(
    state: Arc&lt;P2PWebsocketNetwork&gt;,
    tx: UnboundedSender&lt;P2PInnerMessage&gt;,
    bind: <span class="hljs-built_in">String</span>,
) {
    <span class="hljs-comment">// Broadcast messages to all connected peers</span>
    <span class="hljs-keyword">let</span> list = state.addresses.lock().unwrap();
    <span class="hljs-keyword">for</span> (i, cl) <span class="hljs-keyword">in</span> list.iter().enumerate() {
        log::debug!(<span class="hljs-string">"Broadcasting to {} "</span>, cl.<span class="hljs-number">0</span>);
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Err</span>(e) = cl.<span class="hljs-number">1</span>.send(P2PInnerMessage {
            message: tungstenite::protocol::Message::text(<span class="hljs-built_in">format!</span>(
                <span class="hljs-string">"Message to client {} from {}"</span>,
                i, bind
            )),
            tx_handler: tx.clone(),
        }) {
            log::error!(<span class="hljs-string">"Failed to send broadcast message: {:?}"</span>, e);
        }
    }
}
<span class="hljs-meta">#[tokio::main]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
<span class="hljs-comment">// other parts of the code</span>
 <span class="hljs-keyword">loop</span> {
        tokio::<span class="hljs-built_in">select!</span> {
            <span class="hljs-comment">//other match rules</span>
             _ = tokio::time::sleep(tokio::time::Duration::from_secs(<span class="hljs-number">10</span>)) =&gt; {
                tracker.spawn(broadcast(network_state.clone(), tx.clone(), args.bind.clone()));
            }
        }
    }
}
</code></pre>
<h3 id="heading-graceful-shutdown">Graceful Shutdown</h3>
<p>Finally, we'll ensure our network can be shut down gracefully by handling <code>Ctrl+C</code> signals and canceling tasks accordingly.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">loop</span> {
    tokio::<span class="hljs-built_in">select!</span> {
        <span class="hljs-literal">Some</span>(msg) = rx.recv() =&gt; {
            <span class="hljs-comment">// Process received messages</span>
        }
        _ = tokio::signal::ctrl_c() =&gt; {
            log::warn!(<span class="hljs-string">"Received Ctrl+C, shutting down..."</span>);
            tracker.close();
            cancelation_token.cancel();
            <span class="hljs-keyword">break</span>
        }
    }
}
<span class="hljs-comment">// wait unitl all tasks are closed</span>
tracker.wait().<span class="hljs-keyword">await</span>;
</code></pre>
<h2 id="heading-running-the-project">Running the Project</h2>
<p>In separate sessions, run the program in the following order with these arguments:</p>
<pre><code class="lang-bash">$ RUST_LOG=debug cargo run -- --<span class="hljs-built_in">bind</span> localhost:8080 <span class="hljs-comment"># start the first node </span>
$ RUST_LOG=debug cargo run -- --peers ws://localhost:8080 --<span class="hljs-built_in">bind</span> localhost:8085 <span class="hljs-comment"># start the second node </span>
$ RUST_LOG=debug cargo run -- --peers ws://localhost:8080,ws://localhost:8085 --<span class="hljs-built_in">bind</span> localhost:8086 <span class="hljs-comment"># start the third node</span>
</code></pre>
<p>Then you will see messages being broadcast from each peer to all others. It's an all-to-all broadcast!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Building a P2P network over WebSocket infrastructure in Rust offers a powerful and efficient way to enable real-time communication between nodes. By understanding each part of our code, you can extend and customize this example to fit your specific needs, whether for decentralized applications, real-time data sharing, or distributed computing tasks. To view the full source code, check out the project's <a target="_blank" href="https://github.com/mohyfahim/p2pws-rs">GitHub</a> repository.</p>
<p>We hope this walkthrough helps you understand the core concepts and inspires you to explore more possibilities with Rust and P2P networks. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[The Essential Components and Functionality of Blockchain]]></title><description><![CDATA[Introduction
Blockchain technology has revolutionized the way we think about digital transactions and data integrity. At its core, a blockchain is a decentralized and distributed ledger that ensures security, transparency, and immutability. Understan...]]></description><link>https://mohyfahim.info/the-essential-components-and-functionality-of-blockchain</link><guid isPermaLink="true">https://mohyfahim.info/the-essential-components-and-functionality-of-blockchain</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Cryptocurrency]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Sun, 30 Jun 2024 17:38:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/R2HtYWs5-QA/upload/469c06af6830cf637a34f463cfd2ac7b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Blockchain technology has revolutionized the way we think about digital transactions and data integrity. At its core, a blockchain is a decentralized and distributed ledger that ensures security, transparency, and immutability. Understanding the fundamental components of a blockchain is essential for anyone looking to delve into this transformative technology. This is the second part of the <strong>Blockchain Introduction</strong> series, you can find the first part <a target="_blank" href="https://mohyfahim.info/what-is-blockchain-a-simple-introduction">here</a>. In this blog post, we'll explore the generic elements that make up a blockchain, providing a handy reference for those new to the field or needing a refresher.</p>
<h3 id="heading-generic-elements-of-a-blockchain">Generic Elements of a Blockchain</h3>
<p>One of the main elements of a blockchain (as the name suggests) is the <strong>Block</strong>. We can visualize the block for a better understanding as follow:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719765122570/2ff0e572-aa56-44c8-8ee7-15fc34561035.jpeg?width=500" alt class="image--center mx-auto" /></p>
<p>So a Generic Block includes:</p>
<ul>
<li><p><strong>Previous Block Hash</strong>: A reference to the previous block, providing a chain structure, except for the genesis block, which is the first block hard coded when the blockchain is started.</p>
</li>
<li><p><strong>Nonce</strong>: A unique number used once, essential in cryptographic operations for replay protection and authentication, particularly in Proof of Work (PoW) consensus algorithms.</p>
</li>
<li><p><strong>Timestamp</strong>: The creation time of the block.</p>
</li>
<li><p><strong>Merkle Root</strong>: A hash representing all the transactions in the block, enabling efficient and secure verification of the entire block's transactions.</p>
</li>
<li><p><strong>Block Body</strong>: Contains the transactions that make up the block. The size of the block can vary based on the blockchain type; for instance, Bitcoin's block size is limited to one megabyte.</p>
</li>
</ul>
<p>The second element is the <strong>Transaction</strong>. This is the basic unit of a blockchain, representing the transfer of value from one address to another. The next element is the <strong>Address</strong>. These are unique identifiers used in blockchain transactions to denote senders and recipients. Typically, an address is a public key or derived from one. We can also visualize a simple chain to gain a better understanding:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719767135856/8b952cea-c5be-4896-b8ec-75fcbdc3a06f.jpeg" alt class="image--center mx-auto" /></p>
<p>Beyond the core components, a blockchain includes several other critical attributes that enhance its functionality:</p>
<ul>
<li><p><strong>Peer-to-Peer Network</strong>: This network topology allows all peers to communicate directly, sending and receiving messages without intermediaries.</p>
</li>
<li><p><strong>Scripting or Programming Language</strong>: Scripts or programs perform operations on transactions to facilitate various functions. For instance, Bitcoin uses a language called Script, which allows essential operations but does not support arbitrary program development.</p>
</li>
<li><p><strong>Virtual Machine (VM)</strong>: Extending transaction scripts, VMs enable Turing-complete code to run on a blockchain, facilitating smart contracts. Not all blockchains support VMs. Examples include the Ethereum Virtual Machine (EVM) and the Chain Virtual Machine (CVM).</p>
</li>
<li><p><strong>State Machine</strong>: A blockchain operates as a state transition mechanism, where the state is modified through transaction execution by nodes on the network.</p>
</li>
<li><p><strong>Smart Contracts</strong>: These programs encapsulate business logic, automatically executing when certain conditions are met. They are enforceable and highly desirable for their flexibility and power in applications such as identity management, capital markets, trade finance, and e-governance.</p>
</li>
<li><p><strong>Node</strong>: Nodes in a blockchain network have various roles, including proposing and validating transactions, performing mining, and ensuring consensus. They can also perform simple payment verification and transaction signing, proving ownership of assets through private keys.</p>
</li>
</ul>
<h3 id="heading-blockchain-functionality">Blockchain Functionality</h3>
<p>Let’s walk through the general scheme of how a blockchain validates transactions and creates and adds blocks to the blockchain:</p>
<ol>
<li><p><strong>Transaction Initiation</strong>:</p>
<ul>
<li><p>A node initiates a transaction by creating it and digitally signing it with its private key.</p>
</li>
<li><p>A transaction can represent various actions, most commonly the transfer of value between users on the blockchain network.</p>
</li>
<li><p>The transaction data structure typically includes the logic of the transfer, relevant rules, source and destination addresses, and other validation information.</p>
</li>
<li><p>Transactions are usually either a cryptocurrency transfer or a smart contract invocation.</p>
</li>
</ul>
</li>
<li><p><strong>Transaction Validation and Broadcast</strong>:</p>
<ul>
<li><p>The transaction is propagated to other peers using data-dissemination protocols, such as the Gossip protocol.</p>
</li>
<li><p>Peers validate the transaction based on preset validity criteria before broadcasting it further.</p>
</li>
</ul>
</li>
<li><p><strong>Finding a New Block</strong>:</p>
<ul>
<li><p>Validated transactions are included in a block by special participants called miners.</p>
</li>
<li><p>Miners start the process of mining, racing to finalize the block by solving a mathematical puzzle or fulfilling the requirements of the consensus mechanism.</p>
</li>
</ul>
</li>
<li><p><strong>New Block Found</strong>:</p>
<ul>
<li><p>Once a miner solves the puzzle, the block is considered "found" and finalized.</p>
</li>
<li><p>The transaction is now considered confirmed.</p>
</li>
<li><p>In cryptocurrency blockchains like Bitcoin, the miner is rewarded with a certain number of coins as an incentive for their effort.</p>
</li>
</ul>
</li>
<li><p><strong>Adding the New Block to the Blockchain</strong>:</p>
<ul>
<li><p>The newly created block is validated, and the transactions or smart contracts within it are executed.</p>
</li>
<li><p>The block is propagated to other peers, who also validate and execute it.</p>
</li>
<li><p>The block becomes part of the blockchain (ledger), with the next block cryptographically linking back to it via a hash pointer.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Understanding how a blockchain works is crucial for appreciating the details of this technology. From transaction initiation to block validation and propagation, each step ensures the security, transparency, and immutability of the blockchain. As we explore specific blockchain implementations like Bitcoin and Ethereum, these basic concepts will provide a solid foundation for deeper insights into blockchain functionality.</p>
<blockquote>
<p>The main reference for this blog post is <a target="_blank" href="https://www.packtpub.com/en-us/product/mastering-blockchain-9781803241067"><strong>Mastering Blockchain: Inner workings of blockchain, from cryptography and decentralized identities, to DeFi, NFTs and Web3, Fourth Edition</strong></a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[What is Blockchain? A Simple Introduction]]></title><description><![CDATA[Introduction
Blockchain technology has revolutionized the way we think about data security, transparency, and decentralization. Originally devised as the backbone for Bitcoin, the first cryptocurrency, blockchain's potential reaches far beyond digita...]]></description><link>https://mohyfahim.info/what-is-blockchain-a-simple-introduction</link><guid isPermaLink="true">https://mohyfahim.info/what-is-blockchain-a-simple-introduction</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[architecture]]></category><category><![CDATA[System Architecture]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Thu, 27 Jun 2024 15:32:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/T9rKvI3N0NM/upload/6542ce7d242e6ec0b61b8e975aa91306.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Blockchain technology has revolutionized the way we think about data security, transparency, and decentralization. Originally devised as the backbone for Bitcoin, the first cryptocurrency, blockchain's potential reaches far beyond digital currencies. This blog post aims to demystify the basics of blockchain, exploring its fundamental architecture and providing a clear definition. Whether you're a tech enthusiast or a curious beginner, join us as we delve into the intricate yet fascinating world of blockchain technology, uncovering how it works and why it's poised to transform various industries.</p>
<h3 id="heading-definitions">Definitions</h3>
<p>There are various definitions, but two are widely accepted:</p>
<ol>
<li><p><strong>Layman's definition:</strong> Blockchain is an ever-growing, secure, shared record keeping system in which each user of the data holds a copy of the records, which can only be updated if a majority of parties involved in a transaction agree to update.</p>
</li>
<li><p><strong>Technical definition:</strong> Blockchain is a peer-to-peer, distributed ledger that is cryptographically secure, append-only, immutable (extremely hard to change), and updateable only via consensus among peers.</p>
</li>
</ol>
<p>In the technical definition, some keywords have deep meanings, including <strong>peer-to-peer, distributed ledger, cryptographically secure, append-only</strong>, and <strong>updateable via consensus</strong>. These are the main features of blockchain.</p>
<ul>
<li><p><strong>Peer-to-peer:</strong> peer-to-peer (P2P) refers to a decentralized network architecture where each participant (or node) interacts directly with others without the need for a central authority.</p>
</li>
<li><p><strong>Distributed Ledger:</strong> A distributed ledger is a digital database that is shared and synchronized across a network of multiple nodes, or participants. Unlike traditional centralized databases, where data is stored and controlled by a single entity, a distributed ledger distributes data across all nodes in a decentralized manner. Each node independently maintains an identical copy of the ledger.</p>
</li>
<li><p><strong>Cryptographically Secure:</strong> It means that cryptography has been used to provide security services that make this ledger secure against tampering and misuse. It refers to the robustness of cryptographic techniques employed to ensure the integrity, authenticity, and privacy of data and transactions within the blockchain network.</p>
</li>
<li><p><strong>Append-Only:</strong> The "append-only" feature in the context of blockchain refers to the fundamental principle that once data (such as transactions or blocks) is added to the blockchain, it cannot be altered, removed, or tampered with retroactively.</p>
</li>
</ul>
<blockquote>
<p>A blockchain can be altered in rare cases where bad actors collude and gain more than 51% control of the network.</p>
</blockquote>
<ul>
<li><strong>Updateable via Consensus:</strong> This means changes to the blockchain are made through agreement among network participants. Unlike centralized systems, blockchain updates are governed by decentralized mechanisms. All nodes must agree on changes, ensuring integrity and security. It allows the blockchain to evolve and adapt while staying decentralized and trustworthy.</li>
</ul>
<h3 id="heading-architecture">Architecture</h3>
<p>Understanding blockchain technology starts with exploring its layered architecture, similar to uncovering the details of a complex digital system. At its core, blockchain works within a well-organized framework that uses decentralized networks and cryptographic security. Let's look into each layer of this fascinating design:</p>
<pre><code class="lang-plaintext">|---------------|
|  Application  |
|---------------|
|   Execution   |
|---------------|
|   Consensus   |
|---------------|
| Cryptography  |
|---------------|
|      P2p      |
|---------------|
|    Network    |
|---------------|
</code></pre>
<ol>
<li><p><strong>Network Layer:</strong> At the foundation lies the network layer, the backbone that connects nodes across the globe. This layer leverages the Internet's infrastructure to facilitate peer-to-peer (P2P) communication among blockchain participants.</p>
</li>
<li><p><strong>P2P Layer:</strong> A P2P (peer-to-peer) network runs on top of the Network layer, which consists of information propagation protocols such as gossip or flooding protocols.</p>
</li>
<li><p><strong>Cryptography Layer:</strong> Securing the blockchain's integrity is the cryptography layer, where advanced mathematical algorithms play a pivotal role. Cryptographic techniques like hashing, digital signatures, and encryption safeguard transactions and data against tampering and unauthorized access. These mechanisms ensure transparency and trust in an inherently trustless environment.</p>
</li>
<li><p><strong>Consensus Layer:</strong> Above the cryptography layer is the consensus layer, where network nodes agree on the validity and order of transactions. This crucial part of the blockchain architecture includes techniques like State Machine Replication (SMR), proof-based consensus mechanisms, and Byzantine fault-tolerant consensus protocols from traditional distributed systems research.</p>
</li>
<li><p><strong>Execution Layer:</strong> The Execution layer includes virtual machines, blocks, transactions, and smart contracts. This layer handles key functions on the blockchain, such as processing transactions, running smart contracts, and creating new blocks. Virtual machines like the Ethereum Virtual Machine (EVM), Ethereum WebAssembly (ewasm), and Zinc VM offer the environments needed to execute smart contracts securely and efficiently.</p>
</li>
<li><p><strong>Application Layer:</strong> At the Application layer, we find smart contracts, decentralized applications (dApps), DAOs (Decentralized Autonomous Organizations), and autonomous agents. This layer contains various user-facing entities and software that operate within the blockchain ecosystem. It's where users interact directly with decentralized applications, taking advantage of the innovative features provided by blockchain technology.</p>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In conclusion, blockchain's layered design promotes innovation in various fields, from supply chains to digital identity. Understanding its architecture and principles shows its potential to change our digital future with decentralized, transparent, and secure solutions. <strong><em>Embrace the evolution of blockchain technology, where each layer plays a part in this transformative revolution</em></strong>.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding the CAP and PACELC Theorem in the Context of Blockchain]]></title><description><![CDATA[Introduction
Blockchain technology has changed how we think about data storage, transactions, and decentralized systems. To fully understand blockchain, it's important to know some basic principles from distributed systems, like the CAP theorem and P...]]></description><link>https://mohyfahim.info/understanding-the-cap-and-pacelc-theorem-in-the-context-of-blockchain</link><guid isPermaLink="true">https://mohyfahim.info/understanding-the-cap-and-pacelc-theorem-in-the-context-of-blockchain</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[distributed system]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Thu, 27 Jun 2024 13:49:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ZiQkhI7417A/upload/9656a91c49e78fa01032897bf0925431.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Blockchain technology has changed how we think about data storage, transactions, and decentralized systems. To fully understand blockchain, it's important to know some basic principles from distributed systems, like the CAP theorem and PACELC theorem. These concepts help explain the trade-offs in blockchain design and implementation.</p>
<h3 id="heading-the-cap-theorem">The CAP Theorem</h3>
<p>The CAP theorem, introduced by Eric Brewer in 1998, states that it is impossible for a distributed data store to simultaneously provide more than two out of the following three guarantees:</p>
<ol>
<li><p><strong>Consistency (C)</strong>: Every read receives the most recent write or an error.</p>
</li>
<li><p><strong>Availability (A)</strong>: Every request receives a (non-error) response, without the guarantee that it contains the most recent write.</p>
</li>
<li><p><strong>Partition Tolerance (P)</strong>: The system continues to operate despite an arbitrary number of messages being dropped (or delayed) by the network between nodes.</p>
</li>
</ol>
<p>In the context of blockchain:</p>
<ul>
<li><p><strong>Consistency</strong>: Ensuring that all nodes in the network reflect the same state of the ledger.</p>
</li>
<li><p><strong>Availability</strong>: Guaranteeing that the blockchain is accessible and operational, allowing transactions to be processed.</p>
</li>
<li><p><strong>Partition Tolerance</strong>: The blockchain's ability to continue functioning even if there are network splits or delays.</p>
</li>
</ul>
<p>Blockchains, being decentralized, must handle network partitions, which means they have to balance between consistency and availability. Bitcoin, for example, prioritizes availability and partition tolerance over immediate consistency. This means Bitcoin is always available for transactions, but consistency is achieved over time as the blockchain eventually reaches a consistent state across all nodes. This is known as eventual consistency, where consistency is achieved through validation from multiple nodes over time.</p>
<h3 id="heading-the-pacelc-theorem">The PACELC Theorem</h3>
<p>The PACELC theorem, proposed by Daniel J. Abadi, extends the CAP theorem by introducing another dimension to consider during normal operation. It states:</p>
<ul>
<li><p><strong>If there is a Partition (P)</strong>, then the system must trade off between Availability (A) and Consistency (C).</p>
</li>
<li><p><strong>Else (E)</strong>, when the system is running normally, it must trade off between Latency (L) and Consistency (C).</p>
</li>
</ul>
<p>In the context of blockchain:</p>
<ul>
<li><p><strong>Partition (P)</strong>: As previously discussed, blockchains must handle network partitions.</p>
</li>
<li><p><strong>Availability (A)</strong>: The blockchain's ability to continue processing transactions.</p>
</li>
<li><p><strong>Consistency (C)</strong>: Maintaining a uniform state across all nodes.</p>
</li>
<li><p><strong>Else (E)</strong>: Under normal conditions without partitions.</p>
</li>
<li><p><strong>Latency (L)</strong>: The time it takes to process and confirm transactions.</p>
</li>
</ul>
<p><img src="https://miro.medium.com/v2/resize:fit:720/format:webp/1*OVw8Z1CmQvwMfZk7tMKHxA.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>The CAP and PACELC theorems offer a theoretical framework to understand the trade-offs in distributed systems like blockchain. By examining how platforms like Bitcoin and Ethereum handle these trade-offs, we gain a better understanding of their design choices and operational behaviors. These principles are crucial for developing robust, efficient, and secure blockchain applications. As blockchain technology advances, new strategies and innovations will continue to emerge, addressing these trade-offs in new ways and expanding the capabilities of distributed systems.</p>
]]></content:encoded></item><item><title><![CDATA[Beginner's Guide to Cross-Compiling Rust for Raspberry Pi 4B]]></title><description><![CDATA[Introduction
Welcome to my blog! Today, I'll be sharing my experience in creating and cross-compiling a simple project in Rust for the Raspberry Pi 4. This guide will help you understand the steps involved and get you started on your own Rust project...]]></description><link>https://mohyfahim.info/beginners-guide-to-cross-compiling-rust-for-raspberry-pi-4b</link><guid isPermaLink="true">https://mohyfahim.info/beginners-guide-to-cross-compiling-rust-for-raspberry-pi-4b</guid><category><![CDATA[Rust]]></category><category><![CDATA[cross-compile]]></category><category><![CDATA[Raspberry Pi]]></category><category><![CDATA[embedded systems]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Wed, 26 Jun 2024 12:51:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/p-xSl33Wxyc/upload/699484e9f6822d92d0e15aab76b2c961.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h4 id="heading-introduction">Introduction</h4>
<p>Welcome to my blog! Today, I'll be sharing my experience in creating and cross-compiling a simple project in Rust for the Raspberry Pi 4. This guide will help you understand the steps involved and get you started on your own Rust projects for Raspberry Pi.</p>
<blockquote>
<p>Rust also has the cross tool. "Cross" is a popular tool designed to simplify cross-compiling Rust code for various target architectures. In this tutorial, we will do the cross-compilation without this tool and will cover it in later tutorials.</p>
</blockquote>
<h4 id="heading-setting-up-the-environment">Setting Up the Environment</h4>
<ol>
<li><p><strong>Install Rust</strong>: Ensure you have Rust installed on your development machine. If not, you can install it using the following command:</p>
<pre><code class="lang-sh"> $ curl --proto <span class="hljs-string">'=https'</span> --tlsv1.2 -sSf https://sh.rustup.rs | sh
</code></pre>
</li>
<li><p><strong>Set Up the Rust Target</strong>: To find the architecture running on your Raspberry Pi, you can run the following command on your board:</p>
<pre><code class="lang-sh"> $ uname -a
 Linux raspberrypi 6.6.28+rpt-rpi-v8 <span class="hljs-comment">#1 SMP PREEMPT Debian 1:6.6.28-1+rpt1 (2024-04-22) aarch64 GNU/Linux</span>
</code></pre>
<p> As you can see, we are on an aarch64-linux-gnu machine. So, we select the target for the aarch64 architecture, which is needed for the Raspberry Pi 4.:</p>
<pre><code class="lang-sh"> $ rustup target add aarch64-unknown-linux-gnu
</code></pre>
</li>
</ol>
<p>To see all supporting targets, look at the <a target="_blank" href="https://doc.rust-lang.org/rustc/platform-support.html">rustc documentation</a></p>
<ol start="3">
<li><p><strong>Install the GCC Toolchain</strong>: You need the GCC toolchain for cross-compilation. On Ubuntu, you can install it with:</p>
<pre><code class="lang-sh"> $ sudo apt-get install gcc-aarch64-linux-gnu
</code></pre>
</li>
</ol>
<h4 id="heading-creating-a-simple-rust-project">Creating a Simple Rust Project</h4>
<ol>
<li><p><strong>Create a New Rust Project</strong>: Use Cargo to create a new Rust project:</p>
<pre><code class="lang-sh"> $ cargo new hello_rust_pi
 $ <span class="hljs-built_in">cd</span> hello_rust_pi
</code></pre>
</li>
<li><p><strong>Write Your Rust Code</strong>: Open <code>src/main.rs</code> and write a simple "Hello, world!" program:</p>
<pre><code class="lang-rust"> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
     <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello, Raspberry Pi!"</span>);
 }
</code></pre>
</li>
</ol>
<h4 id="heading-cross-compiling-the-project">Cross-Compiling the Project</h4>
<ol>
<li><p><strong>Configure Cargo for Cross-Compilation</strong>: Create a <code>.cargo/config.toml</code> file in your project directory with the following content:</p>
<pre><code class="lang-toml"> <span class="hljs-section">[target.aarch64-unknown-linux-gnu]</span>
 <span class="hljs-attr">linker</span> = <span class="hljs-string">"aarch64-linux-gnu-gcc"</span>
</code></pre>
</li>
<li><p><strong>Build the Project</strong>: Cross-compile your project using Cargo:</p>
<pre><code class="lang-sh"> $ cargo build --target=aarch64-unknown-linux-gnu
</code></pre>
</li>
<li><p><strong>Transfer the Binary</strong>: After a successful build, transfer the binary to your Raspberry Pi using SCP:</p>
<pre><code class="lang-sh"> scp target/aarch64-unknown-linux-gnu/debug/hello_rust_pi pi@&lt;your_pi_ip&gt;:/home/pi/
</code></pre>
</li>
</ol>
<h4 id="heading-running-the-project-on-raspberry-pi">Running the Project on Raspberry Pi</h4>
<ol>
<li><p><strong>Connect to Your Raspberry Pi</strong>: SSH into your Raspberry Pi:</p>
<pre><code class="lang-sh"> ssh pi@&lt;your_pi_ip&gt;
</code></pre>
</li>
<li><p><strong>Run the Binary</strong>: Make the binary executable and run it:</p>
<pre><code class="lang-sh"> $ chmod +x hello_rust_pi
 $ ./hello_rust_pi
</code></pre>
<p> You should see the output:</p>
<pre><code class="lang-sh"> Hello, Raspberry Pi!
</code></pre>
</li>
</ol>
<h4 id="heading-conclusion">Conclusion</h4>
<p>Congratulations! You've successfully created and cross-compiled a Rust project for the Raspberry Pi 4. This guide covered the basics, and there's so much more to explore in the world of Rust. Stay tuned for more tutorials and projects as I continue my Rust programming journey.</p>
]]></content:encoded></item><item><title><![CDATA[ESP32 Tutorial Series - Part 1 Setting up ESP-IDF]]></title><description><![CDATA[Hello and Welcome to part 1. 
For accessing to last parts, click here.
In this part, we will install and setup ESP-IDF and look at creating projects and components, sdkconfig, and CMake files.
I am currently doing these steps on Linux, but these step...]]></description><link>https://mohyfahim.info/esp32-tutorial-series-part-1</link><guid isPermaLink="true">https://mohyfahim.info/esp32-tutorial-series-part-1</guid><category><![CDATA[iot]]></category><category><![CDATA[C]]></category><category><![CDATA[C++]]></category><category><![CDATA[embedded]]></category><category><![CDATA[Linux]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Thu, 17 Mar 2022 14:42:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647527327001/neJ9QfJFS.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello and Welcome to part 1. </p>
<p>For accessing to last parts, <a target="_blank" href="https://mohyfahim.ir/esp32-tutorial-series-p0">click here</a>.</p>
<p>In this part, we will install and setup ESP-IDF and look at creating projects and components, sdkconfig, and CMake files.</p>
<p>I am currently doing these steps on Linux, but these steps are repeatable on Windows and Mac. Our primary reference is <a target="_blank" href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32">ESP-IDF documentation</a>. The items mentioned in this section are also fully described in this reference.
To use IDF there are several prerequisites (such as Python, Git, Cross compilers, etc) that you must have installed. If you are using Windows, there is an installation wizard that automates the installation process.
For Ubuntu or Debian you can use this command as follow: (  <a target="_blank" href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/linux-macos-setup.html#get-started-prerequisites">read this for the rest of architectures</a> )</p>
<pre><code class="lang-bash">$ sudo apt-get install git wget flex bison gperf python3 python3-pip python3-setuptools cmake ninja-build ccache libffi-dev libssl-dev dfu-util libusb-1.0-0
</code></pre>
<p>To install IDF, we first download its source from GitHub. You can download branches related to the specific releases, but I prefer to use the master branch.</p>
<pre><code class="lang-bash">$ mkdir -p ~/esp
$ <span class="hljs-built_in">cd</span> ~/esp
$ git <span class="hljs-built_in">clone</span> --recursive https://github.com/espressif/esp-idf.git
</code></pre>
<p>After downloading the files, go to the esp-idf folder and execute <code>./install.sh</code>. We can pass one or more specific version names ( or all ) to download the cross-compilation tools for them.</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">cd</span> ~/esp/esp-idf
$ ./install.sh esp32,esp32s2
</code></pre>
<p>Now it’s time to export the <code>idf.py’s</code> path to use it in our project. You can make an alias to make exporting easy. Put this alias in your <code>.bashrc</code> or <code>.zshrc</code> file.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">alias</span> get_idf=<span class="hljs-string">'. $HOME/esp/esp-idf/export.sh'</span>
</code></pre>
<p>Now source that file
<code>source ~/.bashrc</code> or <code>source ~/.zshrc</code>. 
Finally, you can use <code>idf.py</code> without any issues.
You can now go to the folder where you want to create the project and use<code>idf.py</code>as follow:</p>
<pre><code class="lang-bash">$ get_idf <span class="hljs-comment"># to load idf.py’s path</span>
$ idf.py create-project tutorial
</code></pre>
<p>The project structure is as follow:</p>
<pre><code class="lang-bash">$ tree tutorial
├── CMakeLists.txt
└── main
    ├── CMakeLists.txt
    └── tutorial.c
</code></pre>
<p>The IDF structure is based on components. The project has the main component by default. You can add a new component by <code>idf.py create-component -C components component-name</code>command.</p>
<pre><code class="lang-bash">$ idf.py create-component -C components test-component
$ tree tutorial
├── CMakeLists.txt
├── components
│   └── test-component
│       ├── CMakeLists.txt
│       ├── include
│       │   └── test-component.h
│       └── test-component.c
└── main
    ├── CMakeLists.txt
    └── tutorial.c
</code></pre>
<p>The main component has a <code>tutorial.c</code> file that contains the program’s start point, the <code>app_main</code> function. You can use cpp instead of c, just add <code>extern “C”</code> before the <code>app_main</code>. I will cover this in the future.</p>
<p>The Cmake files contain scripts for building a project. In addition, such scripts exist in the IDF source, and we import them in the project's main CMake file to use the IDF components, ie <code>include($ENV{IDF_PATH}/tools/cmake/project.cmake)</code>. In order to add the components folder just created to the project, we add the following command in the main CMakeLists.txt file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">set</span>(EXTRA_COMPONENTS_DIRS components/)
</code></pre>
<p>As a result, IDF will locate the components we created.</p>
<p>The <code>idf.py build</code> command builds the project. If you want to compile the code for a specific family, you must first use <code>idf.py set-target</code>, otherwise, esp32 is selected by default.</p>
<pre><code class="lang-bash">$ idf.py set-target esp32
$ idf.py build
</code></pre>
<p>In this step, after building the code, errors are shown. If the build steps are successful, the <code>idf.py flash -p port</code>command will flash the binary file onto the module.</p>
<pre><code class="lang-bash">$ idf.py flash -p /dev/ttyUSB0
</code></pre>
<p>The question might be, where did IDF store this code in this 4MB of flash memory? The answer is in the Partition Table. We have the ability to divide the flash memory into different sections and the IDF writes binary files including bootloader, partition table, app, etc to the appropriate address based on the partition table we gave it. It uses <code>esptool</code> for flashing purposes. This tool has interesting features that we'll mention if necessary. By default, there are several partition tables that we can use or write a custom one. But where and how to make these settings?</p>
<p>With the <code>idf.py menuconfig</code> command, we can set a number of settings. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647527494408/o85_xMa3r.png" alt="Screenshot from 2022-03-17 17-54-26.png" /></p>
<p>You can see different settings for different sections. We will survey this command in the next part. The output of this menu command is in the <code>sdkconfig</code> file, which is used during the compilation process. Our future components will have a section in the menuconfig so that we can systematically change their settings.
If you run the above commands without any problems, your idf is ready and you can enter the next step. If there is a particular problem, share it so we can investigate.</p>
<p>Good luck.</p>
]]></content:encoded></item><item><title><![CDATA[ESP32 tutorial Series Based on ESP-IDF]]></title><description><![CDATA[In this series, I am going to talk about using the ESP32 module. You will find good and enough information about setting up this module using the Arduino IDE on ...
Table of Contents
This will be updated

Table of Contents
Introduction
ESP32 introduc...]]></description><link>https://mohyfahim.info/esp32-tutorial-series-p0</link><guid isPermaLink="true">https://mohyfahim.info/esp32-tutorial-series-p0</guid><category><![CDATA[C]]></category><category><![CDATA[C++]]></category><category><![CDATA[embedded]]></category><category><![CDATA[iot]]></category><category><![CDATA[Internet of Things]]></category><dc:creator><![CDATA[Mohammad Fahim]]></dc:creator><pubDate>Wed, 16 Mar 2022 19:51:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/jXd2FSvcRr8/upload/v1647458937209/07B56xP-K.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this series, I am going to talk about using the ESP32 module. You will find good and enough information about setting up this module using the Arduino IDE on ...</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<p>This will be updated</p>
<ul>
<li><a class="post-section-overview" href="#table-of-contents">Table of Contents</a></li>
<li><a class="post-section-overview" href="#introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#esp32-introduction">ESP32 introduction</a></li>
</ul>
<h1 id="heading-introduction">Introduction</h1>
<p>Hello and welcome.</p>
<p>In this series, I am going to talk about using the ESP32 module. You will find good and enough information about setting up this module using the Arduino IDE on the Web. In addition, using the Arduino IDE makes a lot of things easier, but the core used for ESP32 is the ESP-IDF compiled.</p>
<p>The <a target="_blank" href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/index.html">ESP-IDF</a> is the espressif framework for ESP32 modules and their families (ESP32s2, ESP32s3, ESP32c3 and etc). If you check their <a target="_blank" href="https://github.com/espressif/esp-idf">GitHub</a>, you will notice newly updated. However, the <a target="_blank" href="https://github.com/espressif/arduino-esp32">Arduino IDE Core</a> is based on the specific ESP-IDF releases, so it doesn't update simultaneously with IDF. On the other hand, some configuration parameters (such as buffer sizes, etc.) were fixed when compiling the ESP-IDF source code. 
These limit your ability to configure and maneuver embedded systems.</p>
<p>In my case, I had to use the ESP-IDF instead of Arduino IDE, so I'm going to share with you what I learned about setting up the ESP-IDF in this series.</p>
<p>I would appreciate it if you would share your knowledge about this with me and if you found this content helpful, please share it with your friends as well. </p>
<h1 id="heading-esp32-introduction">ESP32 introduction</h1>
<p>The ESP32 module is an SoC microcontroller that incorporates WiFi and Bluetooth. It is available in single-core and dual-core versions. These processors belong to the Xtensa family or RISC-V. The RAM and flash storage also differ according to the different versions.</p>
<p><a target="_blank" href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/chip-series-comparison.html">Hardware Comparision</a></p>
<p>I use ESP32-CAM, which is based on ESP32-s from AiThinker. This module has a 2MP camera and a 4MB PSRAM and FLASH memory. There is no specific difference between their core ( ESP32 and ESP32-CAM ), so we choose the target to esp32 when compiling codes. Some variants have external PSRAM inside, while some do not. While some use the onboard PCB antenna, we can swap it out for an external antenna. We will discuss this in the future. I plan to talk about the following subjects for now based on what I have in mind:</p>
<ul>
<li>Setting up the ESP-IDF</li>
<li>WiFi and  provisioning</li>
<li>Bluetooth</li>
<li>HTTP client and server</li>
<li>Socket client and server</li>
<li>MQTT client</li>
<li>ESP-NOW</li>
<li>File systems and other storage</li>
<li>Camera</li>
<li>Mesh Network</li>
<li>Face Detection via CNN</li>
<li>WiFi CSI</li>
</ul>
<p>Whenever you find something interesting or useful, tell me about it so we can check it out.</p>
<p>Thanks.</p>
]]></content:encoded></item></channel></rss>