Close Menu
  • AI
  • Content Creation
  • Tech
  • Robotics
AI-trends.todayAI-trends.today
  • AI
  • Content Creation
  • Tech
  • Robotics
Trending
  • A Group of Researchers from Columbia and CertiK Introduce TensorLean for Formal Verification of GPU Kernels
  • Collectively AI Discloses Immediate Leak After Coding Agent Uncovered Credential – Unite.AI
  • Dragos Finds Immediate Leaks and Stolen Keys in AI Provide Chains
  • Lean and Mathlib Communities Certify Claude-Assisted Riemann Proof – Unite.AI
  • AWS Routes HyperPod Inference Throughout Areas From One Endpoint – Unite.AI
  • DailyAI Briefing: A Lean-checked Riemann proof, plus 4 extra
  • Anthropic Shares Drop 8.5% in Second Session Throughout AI Selloff – Unite.AI
  • OpenAI Ships GPT-Stay-1.1 for Voice Brokers, Cuts Idle Value to $0.02/Min
AI-trends.todayAI-trends.today
Home»Tech»The Implementation of A Code to Simulate Byzantine Practical Fault Tolerance Using Asyncio Malicious Nodes and Latency Analysis

The Implementation of A Code to Simulate Byzantine Practical Fault Tolerance Using Asyncio Malicious Nodes and Latency Analysis

Tech By Gavin Wallace24/02/20268 Mins Read
Facebook Twitter LinkedIn Email
Apple and Duke Researchers Present a Reinforcement Learning Approach That
Apple and Duke Researchers Present a Reinforcement Learning Approach That
Share
Facebook Twitter LinkedIn Email

This tutorial implements an end-toend Practical Byzantine Fault Tolerance simulator (PBFT). We use asyncio. Modeling a distributed network that is realistic with message-passing asynchronously, delays configurable, and Byzantine Nodes intentionally departing from protocol, we model the system. In order to understand how PBFT can achieve consensus even under adverse conditions, while maintaining the 3f+1 theoretical bound, we implement the phases of pre-prepare (before committing), prepare and commit. As the number malicious nodes grows, we instrument the system in order to track the increase of latency for consensus as well as success rates.

import asyncio
Import random
import time
Hashlib import
Import dataclasses and fields
Type import to get Dict, Sets, Tuple, Optional and List
Import matplotlib.pyplot into plt


Preparation = "PREPREPARE"
Preparation = "PREPARE"
The COMMIT= "COMMIT"


@dataclass(frozen=True)
class Msg
 Type: str
 View int
 Seq.
   digest: str
   sender: int


@dataclass
The NetConfig class is:
   min_delay_ms: int = 5
   max_delay_ms: int = 40
 Drop_prob: floating = 0.0
 Reorder_prob : float = 0.

By defining core PBFT messages and importing required libraries, we establish the foundation of the simulator. To ensure structured and consistent communication, we formalize messages sent over the network using dataclasses. Also, we define constants that represent the three phases of PBFT used in the entire system.

Class Network
   def __init__(self, cfg: NetConfig):
 Self.cfg is the same as cfg
 Self-nodes[int, "Node"] = {}


   def register(self, node: "Node"):
       self.nodes[node.nid] Node


 Async Def Send(self, Dst: Int, Msg: Msg, self)
 If you are random() 

The asynchronous network layer simulates the real-world delivery of messages with all its delays, reorderings, and dropouts. We use Asyncio Tasks to send messages through the simulation network. Modeling non-deterministic communications behavior directly affects consensus latency, robustness and reliability.

@dataclass
NodeConfig class:
 Int
 F: int
   primary_id: int = 0
 View: int=0
 Timeout_s: floating = 2


Class Node
   def __init__(self, nid: int, net: Network, cfg: NodeConfig, byzantine: bool = False):
       self.nid = nid
 This is self.net = net
 self.cfg= cfg
       self.byzantine = byzantine


       self.inbox: asyncio.Queue[Msg] = asyncio.Queue()


       self.preprepare_seen: Dict[int, str] = {}
 Self.prepare_votes[Tuple[int, str]Set[int]] = {}
 Self.commit_votes[Tuple[int, str]Set[int]] = {}


       self.committed: Dict[int, str] = {}
 Self-running = True


   @property
   def f(self) -> int:
 Return Self.cfg.f


   def _q_prepare(self) -> int:
       return 2 * self.f + 1


   def _q_commit(self) -> int:
       return 2 * self.f + 1


   @staticmethod
   def digest_of(payload: str) -> str:
       return hashlib.sha256(payload.encode("utf-8")).hexdigest()

Each PBFT participating node’s configuration and state is defined. In order to support both Byzantine and honest behavior, we initialize the data structures that track votes for pre-prepare and commit. Also, we implement logic to determine quorum thresholds as well as deterministic digestion generation for the request validation.

 async def propose(self, payload: str, seq: int):
       if self.nid != self.cfg.primary_id:
           raise ValueError("Only the primary can propose in this simplified simulator.")


 If not byzantine,
           dig = self.digest_of(payload)
 msg= Msg (PREPREPAARE, self.cfg.view.seq, dig.self.nid).
           await self.net.broadcast(self.nid, msg)
 You can return to your original language by clicking here.


 For self.net.nodes.keys():
 Variant = f"{payload}::to={dst}::salt={random.randint(0,10**9)}"
           dig = self.digest_of(variant)
 msg = Message(PREPREPARE. self.cfg.view. seq. dig. self.nid.)
           await self.net.send(dst, msg)


   async def handle_preprepare(self, msg: Msg):
       seq = msg.seq
       dig = msg.digest


       if self.byzantine:
 If random() = self._q_prepare():
 Out = Msg.commit, seq.dig, self.nid, msg.view
           await self.net.broadcast(self.nid, out)


   async def handle_commit(self, msg: Msg):
       seq, dig = msg.seq, msg.digest
 "key" = (seq. dig.
       voters = self.commit_votes.setdefault(key, set())
       voters.add(msg.sender)


       if self.byzantine:
 You can return to your original language by clicking here.


       if self.preprepare_seen.get(seq) != dig:
 You can return to your original language by clicking here.


 If seq is committed to self:
 You can return to your original language by clicking here.


       if len(voters) >= self._q_commit():
           self.committed[seq] = dig

The core PBFT protocols logic including the proposal processing and pre-prepare/prepare phases are implemented. Byzantine equivocation is explicitly modeled by allowing malicious hosts to send different digests to peers. Once the necessary prepare quorum has been reached, we advance to the commit phase.

 async def run(self):
 Self-running is:
           msg = await self.inbox.get()
 If msg.type== PREPREPARE:
               await self.handle_preprepare(msg)
 Elif: msg.typ PREPARE
               await self.handle_prepare(msg)
 Elif msg.type == COMMIT
               await self.handle_commit(msg)


   def stop(self):
 Self-running = FALSE


def pbft_params(n: int) -> int:
 Return (n + 1) // 3


async def run_single_consensus(
   n: int,
   malicious: int,
   net_cfg: NetConfig,
 Payload: str "tx: pay Alice->Bob 5",
 Integer seq = 1
 Timeout_s = float 2.0
 Seeds: optional[int] No.
) -> Dict[str, object]:
 If seed is None
       random.seed(seed)


   f_max = pbft_params(n)
 F = max f


 net = Network_cfg
   cfg = NodeConfig(n=n, f=f, primary_id=0, view=0, timeout_s=timeout_s)


   mal_set = set(random.sample(range(n), k=min(malicious, n)))
 Nodes List[Node] = []
   for i in range(n):
       node = Node(i, net, cfg, byzantine=(i in mal_set))
       net.register(node)
       nodes.append(node)


   tasks = [asyncio.create_task(node.run()) for node in nodes]


   t0 = time.perf_counter()
   await nodes[cfg.primary_id].propose(payload, seq)


   honest = [node for node in nodes if not node.byzantine]
   target = max(1, len(honest))


   committed_honest = 0
   latency = None


   async def poll_commits():
 Latency, nonlocal commitment_honest
 While True
 Node.committed = committed_honest + sum(1 for the node in honest, if it is seq)
           if committed_honest >= target:
               latency = time.perf_counter() - t0
 You can return to your original language by clicking here.
           await asyncio.sleep(0.005)


   try:
       await asyncio.wait_for(poll_commits(), timeout=timeout_s)
 Success = True
   except asyncio.TimeoutError:
 Success = False
       latency = None


 For node in nodes
       node.stop()
 For task within tasks:Return
       task.cancel()
   await asyncio.gather(*tasks, return_exceptions=True)


   digest_set = set(node.committed.get(seq) for node in honest if seq in node.committed)
   agreed = (len(digest_set) == 1) if success else False


   return {
       "n": n,
       "f": f,
       "malicious": malicious,
       "mal_set": mal_set,
       "success": success,
       "latency_s": latency,
       "honest_committed": committed_honest,
       "honest_total": len(honest),
       "agreed_digest": agreed,
   }

Once the commit quorum is met, we complete the state machine of PBFT by processing all commit messages. The node event cycle is used to process messages continuously and asynchronously. We include lifecycle control to safely shut down nodes at the end of each experiment.

async def latency_sweep(
 Integer = 10,
   max_malicious: Optional[int] = None,
 The number of trials per point is 5.
 float value of timeout_s is 2.0
 Net_cfg Optional[NetConfig] = None,
 Seed: int = 7.
):
 If net_cfg equals None, then:
       net_cfg = NetConfig(min_delay_ms=5, max_delay_ms=35, drop_prob=0.0, reorder_prob=0.05)


 If max_malicious equals None:
       max_malicious = n


 Results = []
   random.seed(seed)


 If m is in the range (0, max_malicious+ 1):
       latencies = []
 The success rate is 0
 Agreements = 0


       for t in range(trials_per_point):
           out = await run_single_consensus(
               n=n,
               malicious=m,
               net_cfg=net_cfg,
               timeout_s=timeout_s,
               seed=seed + 1000*m + t
           )
           results.append(out)
 If out["success"]:
 Results = 1
               latencies.append(out["latency_s"])
 If you're out["agreed_digest"]:
 Negotiations += 1.


       avg_lat = sum(latencies)/len(latencies) if latencies else None
       print(
 The f"malicious={m:2d} | success={successes}/{trials_per_point} "
 The f"| avg_latency={avg_lat if avg_lat is not None else 'NA'} "
 The f"| digest_agreement={agreements}/{successes if successes else 1}"
       )


 Results of the return


def plot_latency(results: List[Dict[str, object]], trials_per_point: int):
   by_m = {}
 For r, see results
 r = m["malicious"]
       by_m.setdefault(m, []).append(r)


 The xs and ys are equal [], []
   success_rate = []
 Find m by sorting (by_m.keys)()):
 group = by_m[m]
       lats = [g["latency_s"] If g is in the group, then g["latency_s"] There is no None]
 If g is a group, then succ = sum (1 for each g).["success"])
       xs.append(m)
       ys.append(sum(lats)/len(lats) if lats else float("nan"))
       success_rate.append(succ / len(group))


   plt.figure()
   plt.plot(xs, ys, marker="o")
   plt.xlabel("Number of malicious (Byzantine) nodes")
   plt.ylabel("Consensus latency (seconds) — avg over successes")
   plt.title("PBFT Simulator: Latency vs Malicious Nodes")
   plt.grid(True)
   plt.show()


   plt.figure()
   plt.plot(xs, success_rate, marker="o")
   plt.xlabel("Number of malicious (Byzantine) nodes")
   plt.ylabel("Success rate")
   plt.title("PBFT Simulator: Success Rate vs Malicious Nodes")
   plt.ylim(-0.05, 1.05)
   plt.grid(True)
   plt.show()


async def main():
 N = 10
   trials = 6
 F = pbft_params()
   print(f"n={n} => PBFT theoretical max f = floor((n-1)/3) = {f}")
 "Theory: a false assumption of safety/life is made when malicious intent occurs" 

We conduct large-scale tests by collecting data on the latency of different malicious nodes. We use plots to visualize the system’s behavior and aggregate our results in order to analyse consensus rates. The full pipeline of experiments is run and we observe the degradation in PBFT as the Byzantine Faults approach and exceed the theoretical limit.

We gained a practical understanding of how the PBFT performs in real-world situations, and we learned how pressure from adversaries can affect latency as well as liveness. The quorum-thresholds were used to enforce safety. We also saw that consensus is lost when Byzantine nodes surpass the tolerance bound. Asynchronous networks amplified these effects. The implementation is a good starting point for exploring more complex distributed systems concepts such as leader rotation or authenticated messages. The implementation allows us to gain an understanding of design decisions that go into modern trust-based systems and blockchains.


Take a look at the Full Codes here. Also, feel free to follow us on Twitter Don’t forget about our 120k+ ML SubReddit Subscribe now our Newsletter. Wait! What? now you can join us on telegram as well.


code
Share. Facebook Twitter LinkedIn Email
Avatar
Gavin Wallace

Related Posts

A Group of Researchers from Columbia and CertiK Introduce TensorLean for Formal Verification of GPU Kernels

22/11/2026

OpenAI Ships GPT-Stay-1.1 for Voice Brokers, Cuts Idle Value to $0.02/Min

21/11/2026

Meet Pondering Machines Inkling 2 Mini: 26B Looped MoE Runs on a 32GB Mac

21/11/2026

Baseten Releases Bison-1 and Groundhog-1, Topping Choice Mannequin Index

21/11/2026
Top News

OpenAI Will get Sued Over the Hugging Face Hack

What the US Motion In opposition to Information Facilities Can Study From Overseas

Carbon-X: Hugging Face’s Open Mannequin That Reads DNA

OpenAI’s hugging face hack raises more questions than it answers

‘It’s a Modern-Day Draft’: Why Stanford Students Walked Out on Sundar Pichai’s Commencement Speech

Load More
AI-Trends.Today

Your daily source of AI news and trends. Stay up to date with everything AI and automation!

X (Twitter) Instagram
Top Insights

Right here’s What the AI Apocalypse May Look Like

17/09/2026

Wordsmith Extends Series B With $14 Million to Scale AI for In-House Legal Teams – Unite.AI

05/08/2026
Latest News

A Group of Researchers from Columbia and CertiK Introduce TensorLean for Formal Verification of GPU Kernels

22/11/2026

Collectively AI Discloses Immediate Leak After Coding Agent Uncovered Credential – Unite.AI

22/11/2026
X (Twitter) Instagram
  • Privacy Policy
  • Contact Us
  • Terms and Conditions
© 2026 AI-Trends.Today

Type above and press Enter to search. Press Esc to cancel.