def get_casper_ct(): import serpent global _casper_ct if not _casper_ct: _casper_ct = abi.ContractTranslator( serpent.mk_full_signature(open(casper_path).read())) return _casper_ct
def getinfo(name): info = get(name) fullname = getfullname(name) if info and new_enough(fullname, info): return info else: code = IMPORTP.sub(import_repl, open(fullname).read()) evm = '0x' + serpent.compile(code).encode('hex') sig = serpent.mk_signature(code) fullsig = serpent.mk_full_signature(code) address = RPC.eth_sendTransaction(sender=COINBASE, data=evm, gas=GAS) print Style.BRIGHT + "Waiting for " + name + " to get on chain..." check = RPC.eth_getCode(address)['result'] tries = 1 while check == '0x' and tries < TRIES: time.sleep(12) check = RPC.eth_getCode(address)['result'] tries += 1 if tries == TRIES and check == '0x': print ERROR, 'couldn\'t load contract to chain:', name print 'ABORTING' sys.exit(1) newinfo = { 'addr': address, 'sig': sig, 'fullsig': fullsig, 'mtime': os.path.getmtime(fullname) } put(name, newinfo) return newinfo
def getinfo(name): info = get(name) fullname = getfullname(name) if info and new_enough(fullname, info): return info else: code = IMPORTP.sub(import_repl, open(fullname).read()) evm = '0x' + serpent.compile(code).encode('hex') sig = serpent.mk_signature(code) fullsig = serpent.mk_full_signature(code) address = RPC.eth_sendTransaction(sender=COINBASE, data=evm, gas=GAS) print Style.BRIGHT + "Waiting for " + name + " to get on chain..." check = RPC.eth_getCode(address)['result'] tries = 1 while check == '0x' and tries < TRIES: time.sleep(12) check = RPC.eth_getCode(address)['result'] tries += 1 if tries == TRIES and check == '0x': print ERROR, 'couldn\'t load contract to chain:', name print 'ABORTING' sys.exit(1) newinfo = {'addr':address, 'sig':sig, 'fullsig':fullsig, 'mtime':os.path.getmtime(fullname)} put(name, newinfo) return newinfo
def setup_class(cls): cls.s = tester.state() cls.m = cls.s.abi_contract(cls.MARKET_CONTRACT, gas=cls.CONTRACT_GAS) cls.heap_abi = abi.ContractTranslator( mk_full_signature(cls.HEAP_CONTRACT)) cls.snapshot = cls.s.snapshot()
def test_evm(): evm_code = serpent.compile(serpent_code) translator = abi.ContractTranslator(serpent.mk_full_signature( serpent_code)) data = translator.encode('main', [2, 5]) s = tester.state() c = s.evm(evm_code) o = translator.decode('main', s.send(tester.k0, c, 0, data)) assert o == [32]
def test_evm(): evm_code = serpent.compile(serpent_code) translator = abi.ContractTranslator( serpent.mk_full_signature(serpent_code)) data = translator.encode('main', [2, 5]) s = tester.state() c = s.evm(evm_code) o = translator.decode('main', s.send(tester.k0, c, 0, data)) assert o == [32]
def test_evm(): evm_code = serpent.compile(serpent_code) translator = abi.ContractTranslator( serpent.mk_full_signature(serpent_code)) data = translator.encode('main', [2, 5]) c = tester.Chain() x = c.contract(evm_code, l='evm') o = translator.decode('main', c.tx(tester.k0, x, 0, data)) assert o == [32]
def main(): svcoin = '''\ def init(): sstore(tx.origin, 21*10**9) def sendSVCoins(to, amount): with my_bal = sload(msg.sender): if amount < my_bal: sstore(msg.sender, my_bal - amount) sstore(to, sload(to) + amount) return(1) return(-1) def mySVCoinBalance(): return(sload(msg.sender)) def getSVCoinBalance(address): return(sload(address)) ''' evm = '0x' + serpent.compile(svcoin).encode('hex') fullsig = json.loads(serpent.mk_full_signature(svcoin)) node = TestNode(log=open(os.devnull, 'w'), verbose=False) node.start() rpc = RPC_Client((node.rpchost, node.rpcport), 0) password = os.urandom(32).encode('hex') account = rpc.personal_newAccount(password)['result'] rpc.personal_unlockAccount(account, password, hex(500)) rpc.miner_start(2) balance = 0 while balance < int(MAXGAS, 16): balance = int(rpc.eth_getBalance(account)['result'], 16) txhash = rpc.eth_sendTransaction(sender=account, data=evm, gas=MAXGAS)['result'] while True: response = rpc.eth_getTransactionReceipt(txhash) receipt = response.get('result', False) if receipt: blocknumber = receipt.get('blockNumber', False) if blocknumber: address = receipt['contractAddress'] break contract = Contract(address, fullsig, rpc) print 'My balance is', contract.mySVCoinBalance(call=True) receipt = contract.sendSVCoins(2, 10000, send=True, receipt=True) print 'Sent coins to address 2, receipt:' print json.dumps(receipt, indent=4, sort_keys=True) print 'Balance at address 2 is', contract.getSVCoinBalance(2, call=True)
def update_contract_api(contract_name, contract_path, old_api): fullsig = serpent.mk_full_signature(contract_path) if type(fullsig) == str or type(fullsig) == buffer: fullsig = json.loads(fullsig) events_api = update_contract_events_api(contract_name, fullsig) functions_api = update_contract_functions_api(contract_name, fullsig, old_api) fixedpoint_output_methods = get_fixedpoint_outputs(contract_path) for method_name in fixedpoint_output_methods: functions_api[method_name]["returns"] = "unfix" return events_api, functions_api
def compile(fullname): old_dir = os.getcwd() os.chdir(os.path.dirname(fullname)) global DB if IMPORTS: code = process_imports(fullname) else: code = process_externs(fullname) with open(fullname, 'w') as f: f.write(code) # old version of serpent # fullsig = json.loads(serpent.mk_full_signature(code)) fullsig = serpent.mk_full_signature(code) shortname = get_shortname(fullname) if 'WHITELIST' in code: print "SHITS GETTING WHITELISTED BITCH" whitelist_line = code.find('\n', code.find('WHITELIST')) prefixes = get_prefixes(fullname, fullsig) whitelist_code = WHITELIST_CODE.format(prefixes=prefixes) code = code[:whitelist_line + 1] + whitelist_code + code[whitelist_line + 1:] try: evm = '0x' + serpent.compile(code).encode('hex') except: traceback.print_exc() # print 'Code that broke everything:' # print code # print 'DB dump:' # print json.dumps(DB, indent=4, sort_keys=True) sys.exit(1) address = broadcast_code(evm, code, fullname) sig = serpent.mk_signature(code) # serpent makes the contract name in the sig "main" # if the code it compiles is in a string instead of a file. sig = sig.replace('main', shortname, 1) # Also, there is a serpent bug which can't handle multiple # return types in a function signature, which causes compilation # to fail. This is a workaround... sig = sig.replace(':,', ':_,').replace(':]', ':_]') DB[shortname] = { 'address': address, 'sig': sig, 'fullsig': fullsig, 'code': code.split('\n') } os.chdir(old_dir)
def compile(fullname): if USE_EXTERNS: new_code = translate_code_with_externs(fullname) else: new_code = translate_code_with_imports(fullname) print new_code evm = "0x" + serpent.compile(new_code).encode("hex") new_address = broadcast_code(evm) short_name = os.path.split(fullname)[-1][:-3] new_sig = serpent.mk_signature(new_code).replace("main", short_name, 1).replace(":,", ":_,").replace(":]", ":_]") fullsig = serpent.mk_full_signature(new_code) new_info = {"address": new_address, "sig": new_sig, "fullsig": fullsig} set_info(short_name, new_info)
def compile(fullname): old_dir = os.getcwd() os.chdir(os.path.dirname(fullname)) global DB if IMPORTS: code = process_imports(fullname) else: code = process_externs(fullname) with open(fullname, 'w') as f: f.write(code) # old version of serpent # fullsig = json.loads(serpent.mk_full_signature(code)) fullsig = serpent.mk_full_signature(code) shortname = get_shortname(fullname) if 'WHITELIST' in code: print "SHITS GETTING WHITELISTED BITCH" whitelist_line = code.find('\n', code.find('WHITELIST')) prefixes = get_prefixes(fullname, fullsig) whitelist_code = WHITELIST_CODE.format(prefixes=prefixes) code = code[:whitelist_line+1] + whitelist_code + code[whitelist_line+1:] try: evm = '0x' + serpent.compile(code).encode('hex') except: traceback.print_exc() # print 'Code that broke everything:' # print code # print 'DB dump:' # print json.dumps(DB, indent=4, sort_keys=True) sys.exit(1) address = broadcast_code(evm, code, fullname) sig = serpent.mk_signature(code) # serpent makes the contract name in the sig "main" # if the code it compiles is in a string instead of a file. sig = sig.replace('main', shortname, 1) # Also, there is a serpent bug which can't handle multiple # return types in a function signature, which causes compilation # to fail. This is a workaround... sig = sig.replace(':,', ':_,').replace(':]', ':_]') DB[shortname] = {'address':address, 'sig':sig, 'fullsig':fullsig, 'code':code.split('\n')} os.chdir(old_dir)
def compile(fullname): old_dir = os.getcwd() os.chdir(os.path.dirname(fullname)) global DB if IMPORTS: code = process_imports(fullname) else: code = process_externs(fullname) with open(fullname, "w") as f: f.write(code) fullsig = json.loads(serpent.mk_full_signature(code)) shortname = get_shortname(fullname) if "WHITELIST" in code: whitelist_line = code.find("\n", code.find("WHITELIST")) prefixes = get_prefixes(fullname, fullsig) whitelist_code = WHITELIST_CODE.format(prefixes=prefixes) code = code[: whitelist_line + 1] + whitelist_code + code[whitelist_line + 1 :] try: evm = "0x" + serpent.compile(code).encode("hex") except: traceback.print_exc() print "Code that broke everything:" print code print "DB dump:" print json.dumps(DB, indent=4, sort_keys=True) sys.exit(1) address = broadcast_code(evm, code, fullname) sig = serpent.mk_signature(code) # serpent makes the contract name in the sig "main" # if the code it compiles is in a string instead of a file. sig = sig.replace("main", shortname, 1) # Also, there is a serpent bug which can't handle multiple # return types in a function signature, which causes compilation # to fail. This is a workaround... sig = sig.replace(":,", ":_,").replace(":]", ":_]") DB[shortname] = {"address": address, "sig": sig, "fullsig": fullsig, "code": code.split("\n")} os.chdir(old_dir)
#!/usr/bin/env python import json from serpent import mk_full_signature contracts = { 'etherex': '../contracts/etherex.se', 'sub': '../contracts/etx.se' } for c in contracts: sig = mk_full_signature(contracts[c]) # print sig abi = json.dumps(sig, indent=4, separators=(',', ': ')) # print abi with open('app/js/abi/%s.js' % c, 'w') as out: out.write("module.exports = %s;\n" % abi)
def update_code(self, contract_code): if contract_code: self.contract_code = contract_code self.signature = serpent.mk_full_signature(contract_code) self.translation = ContractTranslator(self.signature)
def update_contract_api(contract_name, contract_path, old_api): fullsig = serpent.mk_full_signature(contract_path) events_api = update_contract_events_api(contract_name, fullsig) functions_api = update_contract_functions_api(contract_name, fullsig, old_api) return events_api, functions_api
# this address is 0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae # Step 4: run # python prepare.py currency=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae # Step 5: make sure to include config.js as a javascript file in your # application. import sys import json import serpent import os solidity = None accounts = {} # Fill in contract ABI declarations for f in os.listdir(os.getcwd()): if f[-3:] == ".se": accounts[f[:-3]] = {"abi": serpent.mk_full_signature(f)} solidity_files = [f for f in os.listdir(os.getcwd()) if f[-4:] == ".sol"] if len(solidity_files): from ethereum import _solidity solidity = _solidity.get_solidity() code = '\n'.join([open(f).read() for f in solidity_files]) contracts = solidity.contract_names(code) for c in contracts: accounts[c] = { "abi": solidity.mk_full_signature(code, contract_name=c) } # Fill in previously known addresses if 'config.js' in os.listdir(os.getcwd()): data = open('config.js').read() code = json.loads(data[data.find('{'):]) # For contracts (ie. objects that contain an 'abi' parameter), if
~call(msg.gas - 10000, %s, 0, inpdata + 28, 100, outdata, 32) return outdata[0] """ % failedtest_addr) try: c.submit(test7.address) success = True except: success = False assert not success print('All tests passed') kode = serpent.compile('check_for_impurity.se') # Create transaction t = transactions.Transaction(0, 30 * 10**9, 2999999, '', 0, kode) t.startgas = t.intrinsic_gas_used + 50000 + 200 * len(kode) t.v = 27 t.r = 45 t.s = 79 print('Send %d wei to %s' % (t.startgas * t.gasprice, '0x' + utils.encode_hex(t.sender))) print('Contract address: 0x' + utils.encode_hex(utils.mk_contract_address(t.sender, 0))) print('Code: 0x' + utils.encode_hex(rlp.encode(t))) print('ABI declaration: ' + repr(serpent.mk_full_signature('check_for_impurity.se')))
def load_abi_translator(): serpent_code = open(CONTRACT_FILE).read() return abi.ContractTranslator(serpent.mk_full_signature(serpent_code))
import serpent from ethereum.tools import tester from ethereum import abi serpent_code = ''' def triple(a): return(a*3) def multiply(a, b): return(a*b) ''' s = tester.Chain() x = s.contract(serpent_code, language='serpent') translator = abi.ContractTranslator(serpent.mk_full_signature(serpent_code)) data = translator.encode('triple', [20]) result = translator.decode('triple', s.tx(tester.k0, x.address, 0, data)) print(result) data = translator.encode('multiply', [20, 4]) result = translator.decode('triple', s.tx(tester.k0, x.address, 0, data)) print(result)
# this address is 0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae # Step 4: run # python prepare.py currency=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae # Step 5: make sure to include config.js as a javascript file in your # application. import sys import json import serpent import os solidity = None accounts = {} # Fill in contract ABI declarations for f in os.listdir(os.getcwd()): if f[-3:] == ".se": accounts[f[:-3]] = {"abi": serpent.mk_full_signature(f)} elif f[-4:] == ".sol": if not solidity: from ethereum import _solidity solidity = _solidity.get_solidity() accounts[f[:-4]] = {"abi": solidity.mk_full_signature(open(f).read())} # Fill in previously known addresses if 'config.js' in os.listdir(os.getcwd()): data = open('config.js').read() code = json.loads(data[data.find('{'):]) # For contracts (ie. objects that contain an 'abi' parameter), if # we detect a .se or .sol file removed then we do not add the # associated address from the registry. For regular accounts, we # transfer all of them over for k, v in code.items(): if 'address' in v and (k in accounts or 'abi' not in v):
def test_whitelist(): top_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) whitelist_code = open(os.path.join(top_dir, "src", "data and api", "reporting.se.whitelist")).read().split("\n") # change the period length of votes so testing is feasible old_period = whitelist_code.index("macro PERIOD: 1800") whitelist_code[old_period] = "macro PERIOD: 100" whitelist_code = "\n".join(whitelist_code) # start the geth node node = TestNode(verbose=False) node.start() # create rpc client and initialize accounts rpc = RPC_Client((node.rpchost, node.rpcport), 0) accounts = setup_accounts(rpc, 10, int(MAXGAS, 16), 60 * 60) # compile code print "compiling and submitting code" evm = "0x" + serpent.compile(whitelist_code).encode("hex") fullsig = json.loads(serpent.mk_full_signature(whitelist_code)) response = rpc.eth_sendTransaction(sender=accounts[0], data=evm, gas=MAXGAS) txhash = response["result"] while True: response = rpc.eth_getTransactionReceipt(txhash) receipt = response.get("result", False) if receipt: blocknumber = receipt.get("blockNumber", False) if blocknumber: address = receipt["contractAddress"] break print "done." contract = Contract(address, fullsig, rpc) for account in accounts: while True: try: contract.addReporter( 1010101, int(account, 16), send=True, sender=account, receipt=True ) # this option forces blocking until included in a block except AssertionError as exc: error = json.loads(exc.message)["error"] code = error["code"] if code != -32603: raise exc print "nonce too low for account", account print "trying again" time.sleep(10) else: break print "account", account, "added as reporter" index = contract.repIDToIndex(1010101, int(account, 16), call=True) contract.setRep(1010101, index, 10000 * 2 ** 64, send=True, sender=account, receipt=True) contract.setWhitelist(2, [1, 3, 4, 5], send=True, receipt=True) ballot_hash = contract.propose_replacement(5, 6, call=True) contract.propose_replacement(5, 6, send=True, receipt=True) for account, _ in zip(accounts, range(6)): contract.whitelistVote(ballot_hash, sender=account) last_period = contract.getPeriod() while contract.getPeriod() == last_period: time.sleep(1) if contract.getWhitelist(2) == [1, 3, 4, 6]: print "TEST PASSED" else: print "TEST FAILED"
def test_whitelist(): top_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) whitelist_code = open( os.path.join(top_dir, 'src', 'data and api', 'reporting.se.whitelist')).read().split('\n') # change the period length of votes so testing is feasible old_period = whitelist_code.index('macro PERIOD: 1800') whitelist_code[old_period] = 'macro PERIOD: 100' whitelist_code = '\n'.join(whitelist_code) # start the geth node node = TestNode(verbose=False) node.start() # create rpc client and initialize accounts rpc = RPC_Client((node.rpchost, node.rpcport), 0) accounts = setup_accounts(rpc, 10, int(MAXGAS, 16), 60 * 60) # compile code print 'compiling and submitting code' evm = '0x' + serpent.compile(whitelist_code).encode('hex') fullsig = json.loads(serpent.mk_full_signature(whitelist_code)) response = rpc.eth_sendTransaction(sender=accounts[0], data=evm, gas=MAXGAS) txhash = response['result'] while True: response = rpc.eth_getTransactionReceipt(txhash) receipt = response.get('result', False) if receipt: blocknumber = receipt.get('blockNumber', False) if blocknumber: address = receipt['contractAddress'] break print 'done.' contract = Contract(address, fullsig, rpc) for account in accounts: while True: try: contract.addReporter( 1010101, int(account, 16), send=True, sender=account, receipt=True ) #this option forces blocking until included in a block except AssertionError as exc: error = json.loads(exc.message)['error'] code = error['code'] if code != -32603: raise exc print 'nonce too low for account', account print 'trying again' time.sleep(10) else: break print 'account', account, 'added as reporter' index = contract.repIDToIndex(1010101, int(account, 16), call=True) contract.setRep(1010101, index, 10000 * 2**64, send=True, sender=account, receipt=True) contract.setWhitelist(2, [1, 3, 4, 5], send=True, receipt=True) ballot_hash = contract.propose_replacement(5, 6, call=True) contract.propose_replacement(5, 6, send=True, receipt=True) for account, _ in zip(accounts, range(6)): contract.whitelistVote(ballot_hash, sender=account) last_period = contract.getPeriod() while contract.getPeriod() == last_period: time.sleep(1) if contract.getWhitelist(2) == [1, 3, 4, 6]: print 'TEST PASSED' else: print 'TEST FAILED'