Spaces:
Sleeping
Sleeping
File size: 19,991 Bytes
08c19c7 9c888b7 08c19c7 9c888b7 08c19c7 9c888b7 08c19c7 9c888b7 7203787 056cf7b 7203787 056cf7b 7203787 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 | """
demo.py
-------
Interactive demo of the Smart Contract Audit RL Environment.
Shows Task 1 end-to-end with a human-readable step-by-step walkthrough.
Usage:
python demo.py # interactive mode
python demo.py --auto # auto-run with built-in demo agent (no input needed)
python demo.py --auto --seed 42
Great for hackathon demos β run this live to show the environment in action.
"""
import argparse
import sys
import textwrap
import time
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Imports
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
from tasks.task1.environment import Task1Environment
from env.schemas import Action, ActionType
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ANSI colours (falls back gracefully on Windows)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
try:
import os
if os.name == "nt":
raise ImportError
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
CYAN = "\033[96m"
RESET = "\033[0m"
except ImportError:
BOLD = DIM = GREEN = YELLOW = RED = CYAN = RESET = ""
DIVIDER = f"{DIM}{'β' * 64}{RESET}"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Pretty printers
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def banner():
print()
print(f"{BOLD}{CYAN}ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
print(f"β Smart Contract Audit RL Environment Β· Task 1 Demo β")
print(f"ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ{RESET}")
print()
def print_observation(obs):
print(DIVIDER)
print(f"{BOLD}Contract :{RESET} {obs.contract_name}")
print(f"{BOLD}Desc :{RESET} {textwrap.fill(obs.contract_description, 72, subsequent_indent=' ' * 11)}")
print(f"{BOLD}Step :{RESET} {obs.step_count} "
f"{BOLD}Reward :{RESET} {obs.cumulative_reward:+.2f}")
if obs.last_action:
colour = GREEN if obs.cumulative_reward >= 0 else YELLOW
result = obs.last_action_result or ""
print(f"{BOLD}Last :{RESET} [{obs.last_action}]")
for line in textwrap.wrap(result, 72):
print(f" {colour}{line}{RESET}")
print(DIVIDER)
def print_action_menu():
actions = [
("1", "list_functions", "{}", "List all functions"),
("2", "get_function_code", '{"function_name": "???"}', "Get function source code"),
("3", "get_function_summary", '{"function_name": "???"}', "Get NatSpec comment"),
("4", "get_file_metadata", "{}", "Get file metadata"),
("5", "get_state_variable", '{"variable_name": "???"}', "Get state variable"),
("6", "get_call_graph", "{}", "Get call graph"),
("7", "submit", '{"function_name":"???","vulnerability_type":"???"}', "Submit answer"),
]
print(f"\n{BOLD}Available actions:{RESET}")
for num, at, _, desc in actions:
print(f" {CYAN}{num}{RESET} {at:25s} {DIM}{desc}{RESET}")
print()
def prompt_action(env) -> Action:
"""Prompt the user to choose and configure an action interactively."""
action_map = {
"1": ActionType.LIST_FUNCTIONS,
"2": ActionType.GET_FUNCTION_CODE,
"3": ActionType.GET_FUNCTION_SUMMARY,
"4": ActionType.GET_FILE_METADATA,
"5": ActionType.GET_STATE_VARIABLE,
"6": ActionType.GET_CALL_GRAPH,
"7": ActionType.SUBMIT,
}
while True:
choice = input(f"{BOLD}Choose action (1-7): {RESET}").strip()
if choice not in action_map:
print(f" {YELLOW}Enter a number 1β7{RESET}")
continue
at = action_map[choice]
params = {}
if at in (ActionType.GET_FUNCTION_CODE, ActionType.GET_FUNCTION_SUMMARY):
fn = input(" Function name: ").strip()
params = {"function_name": fn}
elif at == ActionType.GET_STATE_VARIABLE:
var = input(" Variable name (leave blank to list all): ").strip()
if var:
params = {"variable_name": var}
elif at == ActionType.SUBMIT:
fn = input(" Vulnerable function name: ").strip()
vuln = input(" Vulnerability type (2-3 words): ").strip()
params = {"function_name": fn, "vulnerability_type": vuln}
return Action(action_type=at, params=params)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Scripted demo agent
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DEMO_SCRIPTS = {
# seed β list of (ActionType, params, commentary)
42: [
(ActionType.GET_FILE_METADATA, {},
"First, get high-level contract info to understand the domain."),
(ActionType.LIST_FUNCTIONS, {},
"List functions to understand the attack surface."),
(ActionType.GET_FUNCTION_SUMMARY, {"function_name": "emergencyDrain"},
"emergencyDrain sounds dangerous β check what it's supposed to do."),
(ActionType.GET_FUNCTION_CODE, {"function_name": "emergencyDrain"},
"Inspect the code β no onlyOwner modifier! Anyone can drain the vault."),
(ActionType.SUBMIT, {"function_name": "emergencyDrain", "vulnerability_type": "missing access control"},
"Confident: missing access control. Submitting!"),
],
7: [
(ActionType.LIST_FUNCTIONS, {},
"Start by surveying all functions."),
(ActionType.GET_FUNCTION_SUMMARY, {"function_name": "finalize"},
"finalize β what does this auction close-out function do?"),
(ActionType.GET_FUNCTION_CODE, {"function_name": "finalize"},
"Uses block.timestamp for deadline check β miners can manipulate this."),
(ActionType.SUBMIT, {"function_name": "finalize", "vulnerability_type": "timestamp dependence"},
"Classic timestamp manipulation. Submitting."),
],
}
DEFAULT_DEMO_SEED = 42
def run_auto_demo(seed: int, delay: float = 0.9):
"""Run the scripted demo agent with printed commentary."""
script = DEMO_SCRIPTS.get(seed)
if script is None:
# Generic fallback: list, code of first suspicious fn, submit
print(f"{YELLOW}No pre-written script for seed {seed}. Running generic agent.{RESET}\n")
script = [
(ActionType.LIST_FUNCTIONS, {}, "Listing all functions first."),
(ActionType.GET_FILE_METADATA, {}, "Checking contract metadata."),
]
env = Task1Environment()
result = env.reset(seed=seed)
obs = result.observation
banner()
print(f"{BOLD}Mode:{RESET} Automated demo | {BOLD}Seed:{RESET} {seed}\n")
print_observation(obs)
for at, params, commentary in script:
time.sleep(delay)
print(f"\n{CYAN}βΆ Agent thinking:{RESET} {commentary}")
time.sleep(delay * 0.5)
action = Action(action_type=at, params=params)
step = env.step(action)
obs = step.observation
print_observation(obs)
if step.done:
_print_episode_summary(obs)
return
# Episode not finished β shouldn't happen with a good script
state = env.state()
print(f"\n{YELLOW}Episode not completed (no submit action in script). "
f"Target was: {state.target_function}{RESET}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Interactive mode
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_interactive(seed: int = None):
env = Task1Environment()
seed = seed or 42
result = env.reset(seed=seed)
obs = result.observation
banner()
print(f"{BOLD}Mode:{RESET} Interactive | {BOLD}Seed:{RESET} {seed}")
print(f"{DIM}Tip: Start with list_functions and get_file_metadata.{RESET}\n")
print_observation(obs)
while not obs.done:
print_action_menu()
try:
action = prompt_action(env)
except (KeyboardInterrupt, EOFError):
print(f"\n{YELLOW}Demo interrupted.{RESET}")
break
step = env.step(action)
obs = step.observation
print()
print_observation(obs)
if step.done:
_print_episode_summary(obs)
break
_offer_replay()
def _print_episode_summary(obs):
print()
print(f"{BOLD}{'β' * 64}{RESET}")
reward = obs.cumulative_reward
colour = GREEN if reward > 0 else RED
print(f"{BOLD}Episode complete!{RESET}")
print(f" Steps taken : {obs.step_count}")
print(f" Total reward : {colour}{reward:+.2f}{RESET}")
last = obs.last_action_result or ""
if "β
CORRECT" in last or "EXCELLENT" in last:
print(f" {GREEN}Perfect score β full marks!{RESET}")
elif "β οΈ" in last or "PARTIAL" in last:
print(f" {YELLOW}Partial credit.{RESET}")
elif "π‘ GOOD" in last:
print(f" {YELLOW}Good β most key concepts matched!{RESET}")
elif "π " in last:
print(f" {YELLOW}Partial β some key concepts matched.{RESET}")
elif "β" in last:
print(f" {RED}Incorrect β better luck next episode.{RESET}")
else:
print(f" {'Good effort!' if reward > 0 else 'Keep exploring next time.'}")
print(f"{BOLD}{'β' * 64}{RESET}\n")
def _offer_replay():
try:
again = input("Play again? (y/n): ").strip().lower()
if again == "y":
run_interactive()
except (KeyboardInterrupt, EOFError):
pass
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Entry point
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def main():
parser = argparse.ArgumentParser(
description="Smart Contract Audit RL Environment β Demo"
)
parser.add_argument(
"--auto", action="store_true",
help="Run the scripted demo agent (no keyboard input required)"
)
parser.add_argument(
"--seed", type=int, default=DEFAULT_DEMO_SEED,
help="Episode seed (default: 42)"
)
parser.add_argument(
"--delay", type=float, default=0.9,
help="Seconds between auto-agent steps (default: 0.9)"
)
args = parser.parse_args()
if args.auto:
run_auto_demo(seed=args.seed, delay=args.delay)
else:
run_interactive(seed=args.seed)
if __name__ == "__main__":
main()
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Task 2 demo
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DEMO_SCRIPTS_T2 = {
42: [
(ActionType.GET_FUNCTION_NATSPEC, {}, "First, read the NatSpec to understand intent and expected outputs."),
(ActionType.GET_IO, {}, "Check parameters, return type and expected behaviour."),
(ActionType.GET_FUNCTION_CODE, {}, "Read the actual Solidity code to confirm the behaviour."),
(ActionType.SUBMIT_PROPERTY,
{"property": "After a successful claimRewards call, all of the caller's accrued reward tokens are transferred to the caller and their rewards balance is set to zero. Reverts if the caller has no accrued rewards."},
"Confident about the property. Submitting!"),
],
}
def run_auto_demo_t2(seed: int = 42, delay: float = 0.9):
"""Run the scripted Task 2 demo."""
from tasks.task2.environment import Task2Environment
script = DEMO_SCRIPTS_T2.get(seed)
env = Task2Environment()
result = env.reset(seed=seed)
obs = result.observation
print()
print(f"{BOLD}{CYAN}ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
print(f"β Smart Contract Audit RL Env Β· Task 2 Demo β")
print(f"ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ{RESET}")
print()
print(f"{BOLD}Mode:{RESET} Automated demo | {BOLD}Seed:{RESET} {seed}")
print(f"{BOLD}Task:{RESET} Property Discovery")
print()
fn_name = obs.extra.get("target_function", "?")
sig = obs.extra.get("target_signature", "")
print(f"{BOLD}Contract :{RESET} {obs.contract_name}")
print(f"{BOLD}Function :{RESET} {fn_name} ({sig})")
print(f"{BOLD}Goal :{RESET} Write the natural-language property for '{fn_name}'")
print(DIVIDER)
if not script:
print(f"{YELLOW}No pre-written script for seed {seed}.{RESET}")
return
for at, params, commentary in script:
time.sleep(delay)
print(f"\n{CYAN}βΆ Agent thinking:{RESET} {commentary}")
time.sleep(delay * 0.5)
step_result = env.step(Action(action_type=at, params=params))
sobs = step_result.observation
print(DIVIDER)
print(f"{BOLD}Step {sobs.step_count:2d}{RESET} [{at.value}] r={step_result.reward.value:+.2f} cum={sobs.cumulative_reward:+.2f}")
result_text = sobs.last_action_result or ""
colour = GREEN if step_result.reward.value > 0 else (YELLOW if step_result.reward.value > -0.15 else YELLOW)
for line in result_text.split("\n")[:8]:
print(f" {colour}{line[:90]}{RESET}")
print(DIVIDER)
if step_result.done:
_print_episode_summary(sobs)
return
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Task 3 demo
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DEMO_SCRIPTS_T3 = {
42: [
(ActionType.GET_PROPERTY_SPECIFICATION, {},
"Read the formal spec first β cheapest action at -0.03."),
(ActionType.LIST_FUNCTIONS, {},
"List all functions to survey candidates."),
(ActionType.GET_FUNCTION_CODE, {"function_name": "emergencyDrain"},
"No access modifier! Anyone can call this β that's the violation."),
(ActionType.SUBMIT_FUNCTION, {"function_name": "emergencyDrain"},
"Confident. emergencyDrain violates the access-control property."),
],
45: [
(ActionType.GET_PROPERTY_SPECIFICATION, {},
"Formal spec: first caller at valid price should win."),
(ActionType.LIST_FUNCTIONS, {},
"Auction contract β bid() immediately looks suspicious."),
(ActionType.GET_FUNCTION_CODE, {"function_name": "bid"},
"No commit-reveal, no maxPrice guard β front-running is trivially possible."),
(ActionType.SUBMIT_FUNCTION, {"function_name": "bid"},
"bid() violates the front-running property. Submitting."),
],
}
def run_auto_demo_t3(seed: int = 42, delay: float = 0.9):
"""Run the scripted Task 3 demo."""
from tasks.task3.environment import Task3Environment
script = DEMO_SCRIPTS_T3.get(seed)
env = Task3Environment()
result = env.reset(seed=seed)
obs = result.observation
print()
print(f"{BOLD}{CYAN}ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
print(f"β Smart Contract Audit RL Env Β· Task 3 Demo β")
print(f"ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ{RESET}")
print()
print(f"{BOLD}Mode:{RESET} Automated demo | {BOLD}Seed:{RESET} {seed}")
print(f"{BOLD}Task:{RESET} Rule Checker")
print()
prop = obs.extra.get("property_english", "")
print(f"{BOLD}Contract :{RESET} {obs.contract_name}")
print(f"{BOLD}Property :{RESET} {prop[:100]}{'...' if len(prop) > 100 else ''}")
print(f"{BOLD}Goal :{RESET} Find the function that violates this property.")
print(DIVIDER)
if not script:
print(f"{YELLOW}No pre-written script for seed {seed}. Try seed 42 or 45.{RESET}")
return
for at, params, commentary in script:
time.sleep(delay)
print(f"\n{CYAN}βΆ Agent thinking:{RESET} {commentary}")
time.sleep(delay * 0.5)
step_result = env.step(Action(action_type=at, params=params))
sobs = step_result.observation
print(DIVIDER)
print(f"{BOLD}Step {sobs.step_count:2d}{RESET} [{at.value}] "
f"r={step_result.reward.value:+.2f} cum={sobs.cumulative_reward:+.2f}")
result_text = sobs.last_action_result or ""
colour = GREEN if step_result.reward.value > 0 else YELLOW
for line in result_text.split("\n")[:6]:
print(f" {colour}{line[:90]}{RESET}")
print(DIVIDER)
if step_result.done:
_print_episode_summary(sobs)
return
|