Genpyteal - Experiment to rewrite Python into PyTeal using RedBaron

Overview

genpyteal

Converts Python to PyTeal. Your mileage will vary depending on how much you deviate from the examples. Its quite easy to get an error by doing something not supported. However, it often still outputs useful PyTeal that you can then fix up.

If you appreciate this tool, you are welcome to send ALGOs to RMONE54GR6CYOJREKZQNFCZAUGJHSPBUJNFRBTXS4NKNQL3NJQIHVCS53M.

Installation

pip3 install genpyteal or pip install genpyteal

Warning: The scripts have python3 in them because that is what works on my system. It only works with Python 3. There might be some system where it needs to say python instead. If so, maybe just pull the code from the github repo to change it?

Usage

To generate PyTeal:

genpyteal thescript.py

To generate PyTeal and do syntax highlighting (requires pygmentize and boxes to be installed):

genpyteal thescript.py | niceout

To generate PyTeal and then TEAL:

genteal thescript.py

To show the AST (FST) of a Python program (uses RedBaron .help(), and requires ipython installed):

showast thescript.py

Supported constructs

statement list (= Seq), integer const ( = Int(n)), if/else, while, print (= Log), + ( = Concat(str1, str2) ), True/False (= 1/0), and/or/not ... (maybe something I am forgetting).

Details

You can use a subset of Python. For scratch variables, you will need to initialize them at the beginning of a function, such as x = 0 or s = "tom". It uses that to determine the type. Sometimes you may need to specify Bytes or Int still. Integer/string literals get Int/Bytes added automatically. You can use print instead of Log.

Name the main function app to indicate a stateful application contract, or sig for a LogicSig contract.

For transaction fields, you can leave off the parenthesis, e.g. Txn.sender instead of Txn.sender().

It will assume functions return uint64 unless you specify @bytes or there is no return, which will automatically insert @Subroutine(TealType.none)

If you want to print a number in the log, you can use the numtostr function I made:

from lib import util

def app():
  print("Your number is " + util.numtostr(100))

The best explanation is just to show the examples.

Examples

examples/bool.py

def app():
  amt = 15
  return amt > 10 and amt < 20 or amt == 0

examples/callscratch.py

def g(x):
    return 3

def f(n):
    return g(n)

def app():
    x = f(30)
    name = "Bob"
    print(name)
    return 100

examples/checkgroup.py

PAYTO = Addr('6ZHGHH5Z5CTPCF5WCESXMGRSVK7QJETR63M3NY5FJCUYDHO57VTCMJOBGY')
FEE = 10 * 1000000
ZERO = Global.zero_address()

def no_close_to(i):
  Assert( Gtxn[i].close_remainder_to == ZERO )

def no_rekey(i):
  Assert( Gtxn[i].rekey_to == ZERO )

def verify_payment(i):
  Assert( Gtxn[i].receiver == PAYTO and
          Gtxn[i].amount == Int(FEE) and
          Gtxn[i].type_enum == TxnType.Payment )
         
def app():
  Assert( Global.group_size == 2 )
  
  no_close_to(1)
  no_rekey(1)

  verify_payment(1)

  App.globalPut('lastPaymentFrom', Gtxn[1].sender)
  Approve()

examples/ifseq.py

def foo(b):
  x = b

def app():
  foo(10)
  if 1 == 1:
    return 1
  else:
    return 0

examples/inner.py

def pay(amount: uint64, receiver: bytes):
    Begin()
    SetFields({
        TxnField.type_enum: TxnType.Payment,
        TxnField.sender: Global.current_application_address,
        TxnField.amount: amount,
        TxnField.receiver: receiver
        })
    Submit()

def app():
    pay(10, Addr('6ZHGHH5Z5CTPCF5WCESXMGRSVK7QJETR63M3NY5FJCUYDHO57VTCMJOBGY'))
    result = 0
    if Txn.first_valid > 1000000:
        result = 1
    return result

examples/strargs.py

65: print("User " + name + " is at retirement age.") return 1 else: print("User " + name + " is still young.") return 0">
def app():
  name = ""
  name = Txn.application_args[0]
  age = Btoi(Txn.application_args[1])
  if age > 65:
    print("User " + name + " is at retirement age.")
    return 1
  else:
    print("User " + name + " is still young.")
    return 0

examples/swap.py

< Int(tmpl_fee) is_payment = Txn.type_enum == TxnType.Payment no_closeto = Txn.close_remainder_to == ZERO_ADDR no_rekeyto = Txn.rekey_to == ZERO_ADDR safety_cond = is_payment and no_rekeyto and no_closeto recv_cond = (Txn.receiver == tmpl_seller) and (tmpl_hash_fn(Arg(0)) == tmpl_secret) esc_cond = (Txn.receiver == tmpl_buyer) and (Txn.first_valid > Int(tmpl_timeout)) return (fee_cond and safety_cond) and (recv_cond or esc_cond)">
"""Atomic Swap"""

alice = Addr("6ZHGHH5Z5CTPCF5WCESXMGRSVK7QJETR63M3NY5FJCUYDHO57VTCMJOBGY")
bob = Addr("7Z5PWO2C6LFNQFGHWKSK5H47IQP5OJW2M3HA2QPXTY3WTNP5NU2MHBW27M")
secret = Bytes("base32", "2323232323232323")
timeout = 3000
ZERO_ADDR = Global.zero_address()

def sig(
    tmpl_seller=alice,
    tmpl_buyer=bob,
    tmpl_fee=1000,
    tmpl_secret=secret,
    tmpl_hash_fn=Sha256,
    tmpl_timeout=timeout,
):
    fee_cond = Txn.fee < Int(tmpl_fee)
    is_payment = Txn.type_enum == TxnType.Payment
    no_closeto = Txn.close_remainder_to == ZERO_ADDR
    no_rekeyto = Txn.rekey_to == ZERO_ADDR
    safety_cond = is_payment and no_rekeyto and no_closeto
    
    recv_cond = (Txn.receiver == tmpl_seller) and (tmpl_hash_fn(Arg(0)) == tmpl_secret)
    esc_cond = (Txn.receiver == tmpl_buyer) and (Txn.first_valid > Int(tmpl_timeout))

    return (fee_cond and safety_cond) and (recv_cond or esc_cond)

examples/usenumtostr.py

from lib import util

def app():
  print("The best number is " + util.numtostr(42))
  return True

examples/whilecallif.py

from lib import util

def proc(n):
  return n * 2

def acceptable(n, target):
  if n >= target:
    print("Acceptable. Diff is " + util.numtostr(n - target))
    return True
  else:
    return False

def app():
  total = 1
  i = 0
  while not acceptable(total, Btoi(Txn.application_args[0])):
    total = proc(total)
    i += 1
  return i

examples/whilesum.py

def app():  
  totalFees = 0
  i = 0
  while i < Global.group_size:
    totalFees = totalFees + Gtxn[i].fee
    i = i + 1
  return 1

lib/util.py

@bytes
def numtostr(num):
  out = "             "
  i = 0
  digit = 0
  n = num
  done = False
  while not done:
    digit = n % 10
    out = SetByte(out, 12-i, digit+48)
    n = n / 10		
    if n == 0: done = True
    i = i + 1
  return Extract(out, 12 - i + 1, i)
Owner
Jason Livesay
Jason Livesay
OpenSource Poc && Vulnerable-Target Storage Box.

reapoc OpenSource Poc && Vulnerable-Target Storage Box. We are aming to collect different normalized poc and the vulerable target to verify it. Now re

cckuailong 560 Dec 23, 2022
🍉一款基于Python-Django的多功能Web安全渗透测试工具,包含漏洞扫描,端口扫描,指纹识别,目录扫描,旁站扫描,域名扫描等功能。

Sec-Tools 项目介绍 系统简介 本项目命名为Sec-Tools,是一款基于 Python-Django 的在线多功能 Web 应用渗透测试系统,包含漏洞检测、目录识别、端口扫描、指纹识别、域名探测、旁站探测、信息泄露检测等功能。本系统通过旁站探测和域名探测功能对待检测网站进行资产收集,通过端

简简 300 Jan 07, 2023
Fast python tool to test apache path traversal CVE-2021-41773 in a List of url

CVE-2021-41773 Fast python tool to test apache path traversal CVE-2021-41773 in a List of url Usage :- create a live urls file and use the flag "-l" p

Zahir Tariq 12 Nov 09, 2022
A secure way of storing your passwords.

StrongBox 🔐 A secure way of storing your passwords. 🔑 Why to use StrongBox? StrongBox makes it possible to have a random generated strong password i

Dylan Tintenfich 5 Dec 25, 2021
CVE-2021-43936 is a critical vulnerability (CVSS3 10.0) leading to Remote Code Execution (RCE) in WebHMI Firmware.

CVE-2021-43936 CVE-2021-43936 is a critical vulnerability (CVSS3 10.0) leading to Remote Code Execution (RCE) in WebHMI Firmware. This vulnerability w

Jeremiasz Pluta 8 Jul 05, 2022
ProxyLogon Full Exploit Chain PoC (CVE-2021–26855, CVE-2021–26857, CVE-2021–26858, CVE-2021–27065)

ExProlog ProxyLogon Full Exploit Chain PoC (CVE-2021–26855, CVE-2021–26857, CVE-2021–26858, CVE-2021–27065) Usage: exprolog.py [OPTIONS] ExProlog -

Herwono W. Wijaya 130 Dec 15, 2022
Find existing email addresses by nickname using API/SMTP checking methods without user notification. Please, don't hesitate to improve cat's job! 🐱🔎 📬

mailcat The only cat who can find existing email addresses by nickname. Usage First install requirements: pip3 install -r requirements.txt Then just

282 Dec 30, 2022
DirBruter is a Python based CLI tool. It looks for hidden or existing directories/files using brute force method. It basically works by launching a dictionary based attack against a webserver and analyse its response.

DirBruter DirBruter is a Python based CLI tool. It looks for hidden or existing directories/files using brute force method. It basically works by laun

vijay sahu 12 Dec 17, 2022
PoC for CVE-2021-45897 aka SCRMBT-#180 - RCE via Email-Templates (Authenticated only) in SuiteCRM <= 8.0.1

CVE-2021-45897 PoC for CVE-2021-45897 aka SCRMBT-#180 - RCE via Email-Templates (Authenticated only) in SuiteCRM = 8.0.1 This vulnerability was repor

Manuel Zametter 17 Nov 09, 2022
ShoLister - a tool that collects all available subdomains for specific hostname or organization from Shodan

ShoLister is a tool that collects all available subdomains for specific hostname or organization from Shodan. The tool is designed to be used from Penetration Tester and Bug Bounty Hunters.

Eslam Akl 45 Dec 28, 2022
Nmap scanner with python

Nmap_scanner Usage: sudo python3 nmap_ping.py -i Network List.txt -o Output Folder Location Program can Run Ping Scan Run Port Scan Run Nmap Vuln

Arshaad Mohiadeen 3 Apr 13, 2022
Local File Inclusion Scanner and Exploiter

LFI-Paradise Local File Inclusion Scanner and Exploiter Features 1- Scanner 2- E

11 Sep 04, 2022
Confluence OGNL injection

CVE-2021-26084 Confluence OGNL injection CVE-2021-26084 is an Object-Graph Navigation Language (OGNL) injection vulnerability in the Atlassian Conflue

Ashish Kunwar 15 Sep 23, 2022
Crowbar - A windows post exploitation tool

Crowbar - A windows post exploitation tool Status - ✔️ This project is now considered finished. Any updates from now on will most likely be new script

29 Nov 20, 2022
xp_CAPTCHA(白嫖版) burp 验证码 识别 burp插件

xp_CAPTCHA(白嫖版) 说明 xp_CAPTCHA (白嫖版) 验证码识别 burp插件 安装 需要python3 小于3.7的版本 安装 muggle_ocr 模块(大概400M左右) python3 -m pip install -i http://mirrors.aliyun.com/

算命縖子 588 Jan 09, 2023
CamRaptor is a tool that exploits several vulnerabilities in popular DVR cameras to obtain device credentials.

CamRaptor is a tool that exploits several vulnerabilities in popular DVR cameras to obtain device credentials.

EntySec 118 Dec 24, 2022
Orthrus is a macOS agent that uses Apple's MDM to backdoor a device using a malicious profile.

Orthrus is a macOS agent that uses Apple's MDM to backdoor a device using a malicious profile. It effectively runs its own MDM server and allows the operator to interface with it using Mythic.

Mythic Agents 37 Dec 06, 2022
"KeyLogger-WebService" Is a Keylogger Write In python.

KeyLogger-WebService "KeyLogger-WebService" Is a Keylogger Write In python. When you Inject the file on a computer once the file is opened on the comp

Freddox 21 Dec 16, 2022
Proof of Concept Exploit for ManageEngine ServiceDesk Plus CVE-2021-44077

CVE-2021-44077 Proof of Concept Exploit for CVE-2021-44077: PreAuth RCE in ManageEngine ServiceDesk Plus 11306 Based on: https://xz.aliyun.com/t/106

Horizon 3 AI Inc 25 Nov 09, 2022
Malware for Discord, designed to steal passwords, tokens, and inject discord folders for long-term use.

Vital What is Vital? Vital is malware primarily used to collect and extract information from the Discord desktop client. While it has other features (

HellSec 59 Dec 01, 2022