DEV Community

Mark Dorn
Mark Dorn

Posted on

[BOUNTY] Share Why You Starred RustChain — 3 RTC + Community Shoutout (Pool: 300 RTC)

[BOUNTY] Share Why You Starred RustChain — 3 RTC + Community Shoutout (Pool: 300 RTC)

from future import annotations

from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from enum import Enum
from typing import Iterable, List, Optional, Sequence, Tuple
import re
import unittest
from urllib.parse import urlparse

class ClaimStatus(str, Enum):
PENDING = "pending"
APPROVED = "approved"
REJECTED = "rejected"
PAID = "paid"

class Platform(str, Enum):
X = "x"
REDDIT = "reddit"
MASTODON = "mastodon"
DEVTO = "devto"
HN = "hackernews"
BLOG = "blog"
OTHER = "other"

class ReviewError(ValueError):
pass

@dataclass(frozen=True)
class EngagementSnapshot:
likes: int = 0
reposts: int = 0
comments: int = 0
views: int = 0
signals: Sequence[str] = field(default_factory=tuple)

def suspicious(self) -> bool:
    flags = {s.strip().lower() for s in self.signals if s and s.strip()}
    suspicious_flags = {
        "bought_likes",
        "bought_retweets",
        "bought_reposts",
        "bot_activity",
        "inauthentic_engagement",
        "engagement_purchased",
        "coordinated_manipulation",
    }
    return any(flag in flags for flag in suspicious_flags)
Enter fullscreen mode Exit fullscreen mode

@dataclass(frozen=True)
class AuthorEvidence:
handle: str
account_created_at: datetime
prior_activity_count: int

def account_age_days(self, now: datetime) -> int:
    if now.tzinfo is None or now.utcoffset() is None:
        raise ReviewError("'now' must be timezone-aware UTC datetime.")
    if self.account_created_at.tzinfo is None or self.account_created_at.utcoffset() is None:
        raise ReviewError("account_created_at must be timezone-aware UTC datetime.")
    delta = now - self.account_created_at
    return int(delta.total_seconds() // 86400)
Enter fullscreen mode Exit fullscreen mode

@dataclass(frozen=True)
class ClaimEvidence:
post_url: str
platform: Platform
author: AuthorEvidence
posted_at: datetime
content: str
engagement: EngagementSnapshot

@dataclass(frozen=True)
class SettlementReference:
confirmed: bool
funding_txs: Tuple[str, ...] = ()
amount_rtc: int = 0
txid: Optional[str] = None

def normalized_funding_txs(self) -> Tuple[str, ...]:
    return tuple(tx.strip() for tx in self.funding_txs if tx and tx.strip())
Enter fullscreen mode Exit fullscreen mode

@dataclass
class ClaimReview:
status: ClaimStatus
reasons: List[str] = field(default_factory=list)
payout_rtc: int = 0
payout_address: Optional[str] = None
post_url: Optional[str] = None
platform: Optional[Platform] = None
author_handle: Optional[str] = None
account_age_days: Optional[int] = None
engagement_snapshot: Optional[EngagementSnapshot] = None
timestamp: Optional[datetime] = None
review_status: Optional[str] = None

@dataclass(frozen=True)
class ClaimIdentity:
handle: str
wallet_address: str
post_url: str

def key(self) -> str:
    return f"{self.handle.strip().lower()}|{self.wallet_address.strip().lower()}|{self.post_url.strip().lower()}"
Enter fullscreen mode Exit fullscreen mode

class BountyEngine:
POOL_RTC = 300
REWARD_RTC = 3
MIN_ACCOUNT_AGE_DAYS = 30

SOLANA_ADDRESS = "BGNQH4e8YjVVmarFmwng7Ja8tf7GuBYTua6znxZhSxgo"
EVM_ADDRESS = "0xF56366Ed5731A5d424e686eb594FC8982BcEbbe1"

def __init__(self) -> None:
    self._paid_subjects: set[str] = set()
    self._confirmed_settlement_txs: set[str] = set()
    self._remaining_pool = self.POOL_RTC

@property
def remaining_pool(self) -> int:
    return self._remaining_pool

def review_claim(
    self,
    evidence: ClaimEvidence,
    wallet_address: Optional[str],
    payout_chain: str = "evm",
    settlement: Optional[SettlementReference] = None,
    claimed_at: Optional[datetime] = None,
) -> ClaimReview:
    reasons: List[str] = []
    now = datetime.now(timezone.utc)
    claimed_at = claimed_at or now

    self._validate_aware_datetime(evidence.posted_at, "posted_at")
    self._validate_aware_datetime(evidence.author.account_created_at, "author.account_created_at")
    self._validate_aware_datetime(claimed_at, "claimed_at")

    if evidence.posted_at > claimed_at:
        reasons.append("Post timestamp cannot be in the future relative to claim review time.")

    if not self._is_public_url(evidence.post_url):
        reasons.append("Post URL must be a public, absolute HTTP(S) URL.")

    if evidence.platform not in Platform:
        reasons.append("Unsupported platform.")

    if evidence.author.account_age_days(now) < self.MIN_ACCOUNT_AGE_DAYS:
        reasons.append("Author account must be older than 30 days.")

    if evidence.author.prior_activity_count <= 0:
        reasons.append("Author must have prior activity from platform metadata.")

    if not self._is_genuine_content(evidence.content):
        reasons.append("Post must include a genuine short explanation of why RustChain was starred.")

    if evidence.engagement.suspicious():
        reasons.append("Suspicious engagement signals detected; possible bought or manipulated engagement.")

    payout_address = self._resolve_payout_address(wallet_address, payout_chain)

    identity = ClaimIdentity(
        handle=evidence.author.handle,
        wallet_address=payout_address,
        post_url=evidence.post_url,
    )
    identity_key = identity.key()

    if identity_key in self._paid_subjects:
        reasons.append("One participant may only claim once; duplicate subject detected.")

    if settlement is not None:
        if not settlement.confirmed:
            reasons.append("Settlement reference must be confirmed on-chain.")
        if settlement.amount_rtc != self.REWARD_RTC:
            reasons.append("Confirmed settlement amount must match fixed 3 RTC payout.")
        if not settlement.normalized_funding_txs():
            reasons.append("Confirmed settlement must include at least one funding transaction.")
        for tx in settlement.normalized_funding_txs():
            if not self._is_valid_txid(tx):
                reasons.append("Funding transaction identifier is invalid.")
            if tx in self._confirmed_settlement_txs:
                reasons.append("Funding transaction has already been consumed.")
    else:
        reasons.append("Missing confirmed settlement reference.")

    if self._remaining_pool < self.REWARD_RTC:
        reasons.append("Bounty pool exhausted.")

    if reasons:
        return ClaimReview(
            status=ClaimStatus.REJECTED,
            reasons=reasons,
            payout_rtc=0,
            payout_address=payout_address,
            post_url=evidence.post_url,
            platform=evidence.platform,
            author_handle=evidence.author.handle,
            account_age_days=evidence.author.account_age_days(now),
            engagement_snapshot=evidence.engagement,
            timestamp=claimed_at,
            review_status=ClaimStatus.REJECTED.value,
        )

    self._remaining_pool -= self.REWARD_RTC
    self._paid_subjects.add(identity_key)
    if settlement is not None:
        self._confirmed_settlement_txs.update(settlement.normalized_funding_txs())

    return ClaimReview(
        status=ClaimStatus.APPROVED,
        reasons=[],
        payout_rtc=self.REWARD_RTC,
        payout_address=payout_address,
        post_url=evidence.post_url,
        platform=evidence.platform,
        author_handle=evidence.author.handle,
        account_age_days=evidence.author.account_age_days(now),
        engagement_snapshot=evidence.engagement,
        timestamp=claimed_at,
        review_status=ClaimStatus.APPROVED.value,
    )

def mark_paid(self, payout_address: str) -> None:
    self._paid_subjects.add(payout_address.strip().lower())

@classmethod
def _resolve_payout_address(cls, wallet_address: Optional[str], payout_chain: str) -> str:
    if wallet_address and wallet_address.strip():
        return wallet_address.strip()
    chain = (payout_chain or "").strip().lower()
    if chain == "solana":
        return cls.SOLANA_ADDRESS
    return cls.EVM_ADDRESS

@staticmethod
def _validate_aware_datetime(value: datetime, name: str) -> None:
    if value.tzinfo is None or value.utcoffset() is None:
        raise ReviewError(f"{name} must be timezone-aware UTC datetime.")

@staticmethod
def _is_public_url(url: str) -> bool:
    if not isinstance(url, str) or not url.strip():
        return False
    parsed = urlparse(url.strip())
    return parsed.scheme in {"http", "https"} and bool(parsed.netloc)

@staticmethod
def _is_valid_txid(txid: str) -> bool:
    tx = txid.strip()
    return bool(re.fullmatch(r"[A-Fa-f0-9]{32,128}", tx))

@staticmethod
def _is_genuine_content(content: str) -> bool:
    text = (content or "").strip()
    if len(text) < 20:
        return False
    sentence_count = len([s for s in re.split(r"[.!?]+", text) if s.strip()])
    if sentence_count < 1:
        return False
    lowered = text.lower()
    keyword_hits = [
        "rustchain",
        "proof of antiquity",
        "vintage",
        "powerpc",
        "powerbook",
        "ibm power",
        "old hardware",
        "hardware",
        "mining",
        "reward",
    ]
    return any(word in lowered for word in keyword_hits)
Enter fullscreen mode Exit fullscreen mode

class TestBountyEngine(unittest.TestCase):
def setUp(self) -> None:
self.engine = BountyEngine()
self.now = datetime.now(timezone.utc)
self.author = AuthorEvidence(
handle="@validuser",
account_created_at=self.now - timedelta(days=45),
prior_activity_count=12,
)
self.valid_settlement = SettlementReference(
confirmed=True,
funding_txs=("A1B2C3D4E5F678901234567890ABCDEF",),
amount_rtc=3,
txid="A1B2C3D4E5F678901234567890ABCDEF",
)

def test_approve_valid_claim_with_default_evm_address(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://x.com/valid/status/123",
        platform=Platform.X,
        author=self.author,
        posted_at=self.now - timedelta(days=1),
        content="RustChain is interesting because Proof of Antiquity rewards vintage hardware like PowerPC G4s.",
        engagement=EngagementSnapshot(likes=10, reposts=2, comments=1, views=100),
    )
    review = self.engine.review_claim(evidence, wallet_address=None, payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.APPROVED)
    self.assertEqual(review.payout_rtc, 3)
    self.assertEqual(review.payout_address, BountyEngine.EVM_ADDRESS)
    self.assertEqual(self.engine.remaining_pool, 297)
    self.assertEqual(review.review_status, "approved")

def test_default_solana_address_when_requested(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://mastodon.social/@user/1",
        platform=Platform.MASTODON,
        author=self.author,
        posted_at=self.now - timedelta(hours=3),
        content="RustChain uses Proof of Antiquity instead of Proof of Work, so old machines feel valuable again.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address=None, payout_chain="solana", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.APPROVED)
    self.assertEqual(review.payout_address, BountyEngine.SOLANA_ADDRESS)

def test_reject_new_account(self) -> None:
    author = AuthorEvidence(
        handle="@newuser",
        account_created_at=self.now - timedelta(days=10),
        prior_activity_count=3,
    )
    evidence = ClaimEvidence(
        post_url="https://reddit.com/r/test/post/1",
        platform=Platform.REDDIT,
        author=author,
        posted_at=self.now - timedelta(hours=2),
        content="RustChain rewards old hardware mining.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address="0xabc", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("older than 30 days", " ".join(review.reasons))

def test_reject_no_prior_activity(self) -> None:
    author = AuthorEvidence(
        handle="@noactivity",
        account_created_at=self.now - timedelta(days=60),
        prior_activity_count=0,
    )
    evidence = ClaimEvidence(
        post_url="https://dev.to/u/user/post",
        platform=Platform.DEVTO,
        author=author,
        posted_at=self.now - timedelta(hours=1),
        content="RustChain is neat because vintage hardware gets rewarded.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address="0xabc", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("prior activity", " ".join(review.reasons))

def test_reject_suspicious_engagement(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://mastodon.social/@user/1",
        platform=Platform.MASTODON,
        author=self.author,
        posted_at=self.now - timedelta(hours=3),
        content="RustChain uses Proof of Antiquity instead of Proof of Work.",
        engagement=EngagementSnapshot(signals=("bought_likes",)),
    )
    review = self.engine.review_claim(evidence, wallet_address="0xabc", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("Suspicious engagement", " ".join(review.reasons))

def test_reject_duplicate_subject(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://dev.to/u/user/post",
        platform=Platform.DEVTO,
        author=self.author,
        posted_at=self.now - timedelta(hours=5),
        content="I starred RustChain because vintage servers matter here.",
        engagement=EngagementSnapshot(),
    )
    first = self.engine.review_claim(evidence, wallet_address="0xdeadbeef", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(first.status, ClaimStatus.APPROVED)
    second = self.engine.review_claim(evidence, wallet_address="0xdeadbeef", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(second.status, ClaimStatus.REJECTED)
    self.assertIn("duplicate subject", " ".join(second.reasons))

def test_reject_invalid_url(self) -> None:
    evidence = ClaimEvidence(
        post_url="javascript:alert(1)",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now - timedelta(hours=2),
        content="RustChain is compelling because old hardware gets a fair shot.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("public, absolute HTTP(S) URL", " ".join(review.reasons))

def test_reject_future_post_timestamp(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://example.com/post/1",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now + timedelta(hours=1),
        content="RustChain is interesting because old hardware matters.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("cannot be in the future", " ".join(review.reasons))

def test_reject_weak_content(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://example.com/post/2",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now - timedelta(hours=1),
        content="Nice project.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("genuine short explanation", " ".join(review.reasons))

def test_reject_missing_settlement_reference(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://example.com/post/3",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now - timedelta(hours=1),
        content="RustChain rewards vintage hardware, which is a fun idea.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=None)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("Missing confirmed settlement reference", " ".join(review.reasons))

def test_reject_unconfirmed_settlement(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://example.com/post/4",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now - timedelta(hours=1),
        content="RustChain rewards old machines fairly.",
        engagement=EngagementSnapshot(),
    )
    settlement = SettlementReference(confirmed=False, funding_txs=("A1B2C3D4E5F678901234567890ABCDEF",), amount_rtc=3)
    review = self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("confirmed on-chain", " ".join(review.reasons))

def test_reject_invalid_funding_tx(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://example.com/post/5",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now - timedelta(hours=1),
        content="RustChain rewards old hardware in a novel way.",
        engagement=EngagementSnapshot(),
    )
    settlement = SettlementReference(confirmed=True, funding_txs=("fake-tx-id",), amount_rtc=3)
    review = self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("invalid", " ".join(review.reasons).lower())

def test_reject_wrong_settlement_amount(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://example.com/post/6",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now - timedelta(hours=1),
        content="RustChain is cool because old hardware is rewarded.",
        engagement=EngagementSnapshot(),
    )
    settlement = SettlementReference(confirmed=True, funding_txs=("A1B2C3D4E5F678901234567890ABCDEF",), amount_rtc=9)
    review = self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("fixed 3 RTC", " ".join(review.reasons))

def test_reject_when_pool_exhausted(self) -> None:
    self.engine._remaining_pool = 0
    evidence = ClaimEvidence(
        post_url="https://news.ycombinator.com/item?id=1",
        platform=Platform.HN,
        author=self.author,
        posted_at=self.now - timedelta(hours=1),
        content="RustChain is a fun idea: old hardware gets rewarded.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)
    self.assertIn("exhausted", " ".join(review.reasons))

def test_timezone_aware_required(self) -> None:
    naive_author = AuthorEvidence(
        handle="@naive",
        account_created_at=datetime.utcnow(),
        prior_activity_count=1,
    )
    evidence = ClaimEvidence(
        post_url="https://example.com/post/7",
        platform=Platform.BLOG,
        author=naive_author,
        posted_at=datetime.utcnow(),
        content="RustChain rewards old hardware.",
        engagement=EngagementSnapshot(),
    )
    with self.assertRaises(ReviewError):
        self.engine.review_claim(evidence, wallet_address="0x111", payout_chain="evm", settlement=self.valid_settlement)

def test_mark_paid_does_not_create_approval(self) -> None:
    self.engine.mark_paid("0xabc")
    evidence = ClaimEvidence(
        post_url="https://example.com/post/8",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now - timedelta(hours=1),
        content="RustChain rewards vintage hardware because it is fun.",
        engagement=EngagementSnapshot(),
    )
    review = self.engine.review_claim(evidence, wallet_address="0xabc", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(review.status, ClaimStatus.REJECTED)

def test_reject_when_settlement_tx_reused(self) -> None:
    evidence = ClaimEvidence(
        post_url="https://example.com/post/9",
        platform=Platform.BLOG,
        author=self.author,
        posted_at=self.now - timedelta(hours=1),
        content="RustChain rewards old hardware in a fair way.",
        engagement=EngagementSnapshot(),
    )
    first = self.engine.review_claim(evidence, wallet_address="0x222", payout_chain="evm", settlement=self.valid_settlement)
    self.assertEqual(first.status, ClaimStatus.APPROVED)
    second = self.engine.review_claim(
        evidence,
        wallet_address="0x333",
        payout_chain="evm",
        settlement=self.valid_settlement,
    )
    self.assertEqual(second.status, ClaimStatus.REJECTED)
    self.assertIn("already been consumed", " ".join(second.reasons))
Enter fullscreen mode Exit fullscreen mode

if name == "main":
unittest.main(verbosity=2)

Top comments (1)

Collapse
 
topstar_ai profile image
Luis Cruz

The implementation of ClaimReview in conjunction with the ClaimEvidence class demonstrates a well-thought-out approach to handling claim evaluations. I particularly appreciate how you've encapsulated engagement metrics within EngagementSnapshot, allowing for a structured way to analyze suspicious activity. In my experience, ensuring that accounts are verified and engagement metrics are monitored can significantly reduce fraudulent claims, but I wonder if you've considered integrating a machine learning model to automate parts of this review process? It could enhance efficiency while maintaining the integrity of the evaluation.