예제 #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)
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'))
예제 #4
0
from test_node import TestNode
from test_link import TestLink
from test_graph import TestGraph
from test_euler import TestEuler

if __name__ == "__main__":
    test = TestNode()
    test.test_all()
    test = TestLink()
    test.test_all()
    test = TestGraph()
    test.test_all()
    test = TestEuler()
    test.test_all()
예제 #5
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'))
예제 #6
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'
예제 #7
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"