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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing FromRequestParts lets you turn cross-cutting validation into a reusable handler argument.
  2. 2Proof-of-work forces clients to spend CPU finding a nonce, throttling abuse without server-side state.
  3. 3Counting leading zero bits of a hash is the standard way to measure how much work a solution proves.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A proof-of-work extractor in Axum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code