rust
59 lines · 9 steps
A proof-of-work extractor in Axum
An Axum extractor that gates handlers behind a SHA-256 proof-of-work challenge.
Explained by
highlit
1use axum::{
2 async_trait,
3 extract::FromRequestParts,
4 http::{request::Parts, StatusCode},
5};
6use sha2::{Digest, Sha256};
7
8const REQUIRED_LEADING_ZERO_BITS: u32 = 20;
9
10pub struct VerifiedPow {
11 pub challenge: String,
12}
13
14#[async_trait]
15impl<S> FromRequestParts<S> for VerifiedPow
16where
17 S: Send + Sync,
18{
19 type Rejection = (StatusCode, &'static str);
20
21 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
22 let header = parts
23 .headers
24 .get("x-pow")
25 .and_then(|v| v.to_str().ok())
26 .ok_or((StatusCode::UNAUTHORIZED, "missing X-PoW header"))?;
27
28 let (challenge, nonce) = header
29 .split_once(':')
30 .ok_or((StatusCode::BAD_REQUEST, "malformed proof-of-work"))?;
31
32 let mut hasher = Sha256::new();
33 hasher.update(challenge.as_bytes());
34 hasher.update(b":");
35 hasher.update(nonce.as_bytes());
36 let digest = hasher.finalize();
37
38 if leading_zero_bits(&digest) < REQUIRED_LEADING_ZERO_BITS {
39 return Err((StatusCode::TOO_MANY_REQUESTS, "insufficient proof-of-work"));
40 }
41
42 Ok(VerifiedPow {
43 challenge: challenge.to_owned(),
44 })
45 }
46}
47
48fn leading_zero_bits(bytes: &[u8]) -> u32 {
49 let mut count = 0;
50 for &b in bytes {
51 if b == 0 {
52 count += 8;
53 } else {
54 count += b.leading_zeros();
55 break;
56 }
57 }
58 count
59}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing FromRequestParts lets you turn cross-cutting validation into a reusable handler argument.
- 2Proof-of-work forces clients to spend CPU finding a nonce, throttling abuse without server-side state.
- 3Counting leading zero bits of a hash is the standard way to measure how much work a solution proves.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-proof-of-work-extractor-in-axum-explained-rust-be96/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.