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
An auxiliary tool for iot vulnerability hunter

firmeye - IoT固件漏洞挖掘工具 firmeye 是一个 IDA 插件,基于敏感函数参数回溯来辅助漏洞挖掘。我们知道,在固件漏洞挖掘中,从敏感/危险函数出发,寻找其参数来源,是一种很有效的漏洞挖掘方法,但程序中调用敏感函数的地方非常多,人工分析耗时费力,通过该插件,可以帮助排除大部分的安全

Firmy Yang 171 Nov 28, 2022
Jolokia Exploitation Toolkit (JET) helps exploitation of exposed jolokia endpoints.

jolokia-exploitation-toolkit Jolokia Exploitation Toolkit (JET) helps exploitation of exposed jolokia endpoints. Core concept Jolokia is a protocol br

Laluka 194 Jan 01, 2023
PySharpSphere - Inspired by SharpSphere, just another python version

PySharpSphere Inspired by SharpSphere, just another python version. Installation python3 setup.py install Features Support control both Linux and Wind

Ricter Zheng 191 Dec 22, 2022
Cam-Hacker: Ip Cameras hack with python

Cam-Hacker Hack Cameras Mode Of Execution: apt-get install python3 apt-get insta

Error 4 You 9 Dec 17, 2022
The Decompressoin tool for Vxworks MINIFS

MINIFS-Decompression The Decompression tool for Vxworks MINIFS filesystem. USAGE python minifs_decompression.py [target_firmware] The example of Mercu

8 Jan 03, 2023
Fast and customizable vulnerability scanner For JIRA written in Python

Fast and customizable vulnerability scanner For JIRA. 🤔 What is this? Jira-Lens 🔍 is a Python Based vulnerability Scanner for JIRA. Jira is a propri

Mayank Pandey 185 Dec 25, 2022
CVE-2021-21985 VMware vCenter Server远程代码执行漏洞 EXP (更新可回显EXP)

CVE-2021-21985 CVE-2021-21985 EXP 本文以及工具仅限技术分享,严禁用于非法用途,否则产生的一切后果自行承担。 0x01 利用Tomcat RMI RCE 1. VPS启动JNDI监听 1099 端口 rmi需要bypass高版本jdk java -jar JNDIIn

r0cky 355 Aug 03, 2022
Let's you scan the entire internet in a couple of hours and identify all Minecraft servers on IPV4

Minecraft-Server-Scanner Let's you scan the entire internet in a couple of hours and identify all Minecraft servers on IPV4 Installation and running i

116 Jan 08, 2023
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
An ARP Spoofer attacker for windows to block away devices from your network.

arp0_attacker An ARP Spoofer-attacker for Windows -OS to block away devices from your network. INFO Built in Python 3.8.2. arp0_attackerx.py is Upgrad

Wh0_ 15 Mar 17, 2022
A tool to extract the IdP cert from vCenter backups and log in as Administrator

vCenter SAML Login Tool A tool to extract the Identity Provider (IdP) cert from vCenter backups and log in as Administrator Background Commonly, durin

Horizon 3 AI Inc 343 Dec 31, 2022
Chapter 1 of the AWS Cookbook

Chapter 1 - Security Set and export your default region: export AWS_REGION=us-east-1 Set your AWS ACCOUNT ID:: AWS_ACCOUNT_ID=$(aws sts get-caller-ide

AWS Cookbook 30 Nov 27, 2022
Scan Site - Tools For Scanning Any Site and Get Site Information

Site Scanner Tools For Scanning Any Site and Get Site Information Example Require - pip install colorama - pip install requests How To Use Download Th

NumeX 5 Mar 19, 2022
StarUML cracker - StarUML cracker With Python

StarUML_cracker Usage On Linux Clone the repo. git clone https://github.com/mana

Bibek Manandhar 9 Jun 20, 2022
利用NTLM Hash读取Exchange邮件

GetMail 利用NTLM Hash读取Exchange邮件:在进行内网渗透时候,我们经常拿到的是账号的Hash凭据而不是明文口令。在这种情况下采用邮件客户端或者WEBMAIL的方式读取邮件就很麻烦,需要进行破解,NTLM的破解主要依靠字典强度,破解概率并不是很大。

<a href=[email protected]"> 388 Dec 27, 2022
The Easiest Way To Gallery Hacking

The easiest way to HACK A GALLARY, Get every part of your friends' gallery ( 100% Working ) | Tool By John Kener 🇱🇰

John Kener 34 Nov 30, 2022
An OSINT tool that searches for devices directly connected to the internet (IoT) with a user specified query. It returns results for Webcams, Traffic lights, Refridgerators, Smart TVs etc.

An OSINT tool that searches for devices directly connected to the internet (IoT) with a user specified query. It returns results for Webcams, Traffic

Richard Mwewa 48 Nov 20, 2022
A hashtag check python module

A hashtag check python module

Fayas Noushad 3 Aug 10, 2022
Log4j rce test environment and poc

log4jpwn log4j rce test environment See: https://www.lunasec.io/docs/blog/log4j-zero-day/ Experiments to trigger in various software products mentione

Leon Jacobs 307 Dec 24, 2022
Uma ferramenta de segurança da informação escrita em python3,capaz de dar acesso total ao computador de alguém!

shell-reverse Uma ferramenta de segurança da informação escrita em python3, capaz de dar acesso total ao computador de alguém! A cybersecurity tool wr

Marcus Vinícius Ribeiro Andrade 1 Nov 03, 2021