Пример #1
0
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)
Пример #2
0
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)
Пример #3
0
def main():
    global BLOCKTIME
    global USE_EXTERNS
    global RPC
    global COINBASE
    global FROM_DB
    start = 0
    verbose = False
    debug = False
    for arg in sys.argv:
        if arg.startswith("--BLOCKTIME="):
            BLOCKTIME = float(arg.split("=")[1])
        if arg.startswith("--contract="):
            FROM_DB = True
            start = arg.split("=")[1]
        if arg == "--use-externs":
            USE_EXTERNS = True
        if arg == "--verbose":
            verbose = True
        if arg == "--debug":
            debug = True
    deps, nodes = get_compile_order()
    if type(start) == str:
        deps = optimize_deps(deps, nodes, start)
        start = 0
    RPC = RPC_Client(default="GETH", verbose=verbose, debug=debug)
    COINBASE = RPC.eth_coinbase()["result"]
    for i in range(start, len(deps)):
        fullname = get_fullname(deps[i])
        print "compiling", fullname
        compile(fullname)
    if not FROM_DB:
        sys.stdout.write("dumping new addresses to DB")
        sys.stdout.flush()
        for k, v in INFO.items():
            DB.Put(k, json.dumps(v))
            sys.stdout.write(".")
            sys.stdout.flush()
        print
    return 0
Пример #4
0
def test_compile_imports():
    make_tree(test_code)
    node = start_test_node()

    rpc = RPC_Client((test_node.HOST, test_node.PORT), 0)
    coinbase = rpc.eth_coinbase()['result']
    gas_price = int(rpc.eth_gasPrice()['result'], 16)
    balance = 0

    while balance/gas_price < int(MAXGAS, 16):
        balance = int(rpc.eth_getBalance(coinbase)['result'], 16)
        time.sleep(1)

    subprocess.check_call(['python',
                           'load_contracts.py',
                           '-p', '9696',
                           '-b', '2',
                           '-d', 'test_load_contracts.json',
                           '-s', 'foobar'])

    db = json.load(open("test_load_contracts.json"))
    func1 = db['foo']['fullsig'][0]['name']
    prefix = sha3.sha3_256(func1.encode('ascii')).hexdigest()[:8]
    arg = hex(1 << 65)[2:].strip('L').rjust(64, '0')
    r1 = rpc.eth_call(sender=coinbase,
                      to=db['foo']['address'],
                      data=('0x' + prefix + arg),
                      gas=hex(3*10**6))['result']

    r1 = int(r1, 16)
    if r1 > 2**255:
        r1 -= 2**256
    r2 = bar(1 << 65)
    if r1 == r2:
        print 'TEST PASSED'
    else:
        print 'TEST FAILED: <r1 {}> <r2 {}>'.format(r1, r2)
    rm_tree(test_code)
    node.send_signal(signal.SIGINT)
    node.wait()
Пример #5
0
#!/usr/bin/python
'''A script for using interacting with a local Ethereum node using JSON RPC.'''
from pyrpctools import RPC_Client
import sys
import re

GETHRPC = RPC_Client(default='GETH', debug=True)
COINBASE = GETHRPC.eth_coinbase()['result']

kwd_p = re.compile(r'--(?P<key>\D{2,})=(?P<val>.*)')
def parse_args():
    args = []
    kwds = {}
    for arg in sys.argv[2:]:
        m = kwd_p.match(arg)
        if m:
            d = m.groupdict()
            if d['val'] == 'COINBASE':
                d['val'] = COINBASE
            kwds[d['key']] = d['val']
        else:
            args.append(arg)
    return args, kwds

if __name__ == '__main__':
    rpc_cmd = sys.argv[1]
    args, kwds = parse_args()
    result = getattr(GETHRPC, rpc_cmd)(*args, **kwds)
def test_compile_imports():
    test_dir = os.path.dirname(os.path.realpath(__file__))

    try:
        make_tree(test_code, dirname=test_dir)
    except:
        shutil.rmtree(os.path.join(test_dir, 'foobar'))
        make_tree(test_code, dirname=test_dir)

    node = TestNode(log=open(os.path.join(test_dir,
                                          'test_compile_imports.log'), 
                             'w'))
    node.start()

    try:
        rpc = RPC_Client((node.rpchost, node.rpcport), 0)
        password = os.urandom(32).encode('hex')
        coinbase = rpc.personal_newAccount(password)['result']
        rpc.personal_unlockAccount(coinbase, password, 10**10)
        rpc.miner_start(2)

        gas_price = int(rpc.eth_gasPrice()['result'], 16)
        balance = 0

        print Style.BRIGHT + 'Mining coins...' + Style.RESET_ALL
        while balance/gas_price < int(MAXGAS, 16):
            balance = int(rpc.eth_getBalance(coinbase)['result'], 16)
            time.sleep(1)

        load_contracts = os.path.join(os.path.dirname(test_dir), 'load_contracts.py')

        subprocess.check_call(['python',
                               load_contracts,
                               '-C', test_dir,
                               '-p', '9696',
                               '-b', '2',
                               '-d', 'test_load_contracts.json',
                               '-s', 'foobar'])

        db = json.load(open(os.path.join(test_dir, "test_load_contracts.json")))
        func1 = db['foo']['fullsig'][0]['name']
        prefix = sha3.sha3_256(func1.encode('ascii')).hexdigest()[:8]
        arg = 8
        expected = round((2 * 8**0.5) / (8**0.5 - 1), 6)
        encoded_arg = hex(arg*2**64)[2:].strip('L').rjust(64, '0')
        result = rpc.eth_call(sender=coinbase,
                              to=db['foo']['address'],
                              data=('0x' + prefix + encoded_arg),
                              gas=hex(3*10**6))['result']

        result = int(result, 16)
        if result > 2**255:
            result -= 2**256
    
        #the different internal representations
        #used in the calculations lead to some difference,
        #but the answers should be approximately the same.
        result = round(float(result)/2**64, 6)

        if result == expected:
            print 'TEST PASSED'
        else:
            print 'TEST FAILED: <expected {}> <result {}>'.format(expected, result)
    except Exception as exc:
        traceback.print_exc()
    finally:
        shutil.rmtree(os.path.join(test_dir, 'foobar'))
        os.remove(os.path.join(test_dir, 'math_macros.sm'))
        os.remove(os.path.join(test_dir, 'test_load_contracts.json'))
Пример #7
0
def get_network_id(rpc_host, rpc_port):
    return RPC_Client((RPCHOST, RPCPORT), 0).net_version()["result"]
Пример #8
0
#!/usr/bin/python
'''A script for using interacting with a local Ethereum node using JSON RPC.'''
from pyrpctools import RPC_Client
import sys
import re

GETHRPC = RPC_Client(default='GETH', debug=True)
COINBASE = GETHRPC.eth_coinbase()['result']

kwd_p = re.compile(r'--(?P<key>\D{2,})=(?P<val>.*)')


def parse_args():
    args = []
    kwds = {}
    for arg in sys.argv[2:]:
        m = kwd_p.match(arg)
        if m:
            d = m.groupdict()
            if d['val'] == 'COINBASE':
                d['val'] = COINBASE
            kwds[d['key']] = d['val']
        else:
            args.append(arg)
    return args, kwds


if __name__ == '__main__':
    rpc_cmd = sys.argv[1]
    args, kwds = parse_args()
    result = getattr(GETHRPC, rpc_cmd)(*args, **kwds)
Пример #9
0
def test_compile_imports():
    test_dir = os.path.dirname(os.path.realpath(__file__))

    try:
        make_tree(test_code, dirname=test_dir)
    except:
        shutil.rmtree(os.path.join(test_dir, 'foobar'))
        make_tree(test_code, dirname=test_dir)

    node = TestNode(
        log=open(os.path.join(test_dir, 'test_compile_imports.log'), 'w'))
    node.start()

    try:
        rpc = RPC_Client((node.rpchost, node.rpcport), 0)
        password = os.urandom(32).encode('hex')
        coinbase = rpc.personal_newAccount(password)['result']
        rpc.personal_unlockAccount(coinbase, password, 10**10)
        rpc.miner_start(2)

        gas_price = int(rpc.eth_gasPrice()['result'], 16)
        balance = 0

        print Style.BRIGHT + 'Mining coins...' + Style.RESET_ALL
        while balance / gas_price < int(MAXGAS, 16):
            balance = int(rpc.eth_getBalance(coinbase)['result'], 16)
            time.sleep(1)

        load_contracts = os.path.join(os.path.dirname(test_dir),
                                      'load_contracts.py')

        subprocess.check_call([
            'python', load_contracts, '-C', test_dir, '-p', '9696', '-b', '2',
            '-d', 'test_load_contracts.json', '-s', 'foobar'
        ])

        db = json.load(open(os.path.join(test_dir,
                                         "test_load_contracts.json")))
        func1 = db['foo']['fullsig'][0]['name']
        prefix = sha3.sha3_256(func1.encode('ascii')).hexdigest()[:8]
        arg = 8
        expected = round((2 * 8**0.5) / (8**0.5 - 1), 6)
        encoded_arg = hex(arg * 2**64)[2:].strip('L').rjust(64, '0')
        result = rpc.eth_call(sender=coinbase,
                              to=db['foo']['address'],
                              data=('0x' + prefix + encoded_arg),
                              gas=hex(3 * 10**6))['result']

        result = int(result, 16)
        if result > 2**255:
            result -= 2**256

        #the different internal representations
        #used in the calculations lead to some difference,
        #but the answers should be approximately the same.
        result = round(float(result) / 2**64, 6)

        if result == expected:
            print 'TEST PASSED'
        else:
            print 'TEST FAILED: <expected {}> <result {}>'.format(
                expected, result)
    except Exception as exc:
        traceback.print_exc()
    finally:
        shutil.rmtree(os.path.join(test_dir, 'foobar'))
        os.remove(os.path.join(test_dir, 'math_macros.sm'))
        os.remove(os.path.join(test_dir, 'test_load_contracts.json'))
Пример #10
0
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'
Пример #11
0
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"
Пример #12
0
#!/usr/bin/python
from colorama import init, Style, Fore; init()
import warnings; warnings.simplefilter('ignore')
from pyrpctools import RPC_Client, DB
from pyepm.api import abi_data
import json
import time
import sys
import re

RPC = RPC_Client(default='GETH')
COINBASE = RPC.eth_coinbase()['result']
MAXTRIES = 10
BLOCKTIME = 12
GAS = hex(3*10**6)

def get_sym(arg):
    '''Get the symbol used for serpent signatures.'''
    if type(arg) in (int, long):
        return 'i'
    if type(arg) == list:
        return 'a'
    else:
        return 's'

def safe_eval(thing):
    '''Evaluates a string into a python object, or returns the string.'''
    if thing in ['--call', '--sendtx']:
        return None
    try:
        thing = eval(thing)