Exemplo n.º 1
0
def init_system(genesis, key):
    code = serpent.compile(open('serp/root.se').read())
    tx_make_root = transactions.Transaction.contract(0, 0, 10**12, 10000,
                                                     code).sign(key)
    root_contract = processblock.apply_tx(genesis, tx_make_root)

    root_hash = root_contract.encode('hex')

    f = lambda x: write_owner(root_hash, x)
    map(f,
        ['serp/data.se', 'serp/tag.se', 'serp/users.se', 'serp/currency.se'])

    code = serpent.compile(open('serp/data.se').read())
    tx_make_data = transactions.Transaction.contract(1, 0, 10**12, 10000,
                                                     code).sign(key)
    code = serpent.compile(open('serp/tag.se').read())
    tx_make_tag = transactions.Transaction.contract(2, 0, 10**12, 10000,
                                                    code).sign(key)
    code = serpent.compile(open('serp/users.se').read())
    tx_make_users = transactions.Transaction.contract(3, 0, 10**12, 10000,
                                                      code).sign(key)
    code = serpent.compile(open('serp/currency.se').read())
    tx_make_currency = transactions.Transaction.contract(
        4, 0, 10**12, 10000, code).sign(key)

    data_contract = processblock.apply_tx(genesis, tx_make_data)
    tag_contract = processblock.apply_tx(genesis, tx_make_tag)
    users_contract = processblock.apply_tx(genesis, tx_make_users)
    currency_contract = processblock.apply_tx(genesis, tx_make_currency)

    d_contract = data_contract.encode('hex')
    t_contract = tag_contract.encode('hex')
    u_contract = users_contract.encode('hex')
    c_contract = currency_contract.encode('hex')

    #init root
    tx_init_root = transactions.Transaction(
        5, 0, 10**12, 10000, root_contract,
        serpent.encode_datalist(
            [d_contract, t_contract, u_contract, c_contract])).sign(key)
    ans = processblock.apply_tx(genesis, tx_init_root)

    adresses = {
        root_hash: 'root',
        d_contract: 'data',
        t_contract: 'tags',
        u_contract: 'users',
        utils.privtoaddr(key): 'me',
        c_contract: 'currency'
    }

    return adresses
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
Exemplo n.º 3
0
def test_send_transaction_with_contract(test_app):
    serpent_code = '''
def main(a,b):
    return(a ^ b)
'''
    tx_to = b''
    evm_code = serpent.compile(serpent_code)
    chainservice = test_app.services.chain
    chain = test_app.services.chain.chain
    state = State(chainservice.head_candidate.state_root, chain.env)
    sender = test_app.services.accounts.unlocked_accounts[0].address
    assert state.get_balance(sender) > 0
    tx = {
        'from': address_encoder(sender),
        'to': address_encoder(tx_to),
        'data': encode_hex(evm_code)
    }
    data_decoder(test_app.client.call('eth_sendTransaction', tx))
    assert len(chainservice.head_candidate.transactions) == 1
    creates = chainservice.head_candidate.transactions[0].creates

    candidate_state_dict = State(chainservice.head_candidate.state_root,
                                 chain.env).to_dict()
    code = candidate_state_dict[encode_hex(creates)]['code']
    assert len(code) > 2
    assert code != '0x'

    test_app.mine_next_block()

    assert len(chain.head.transactions) == 1
    creates = chain.head.transactions[0].creates
    state_dict = State(chain.head.state_root, chain.env).to_dict()
    code = state_dict[encode_hex(creates)]['code']
    assert len(code) > 2
    assert code != '0x'
Exemplo n.º 4
0
def test_namecoin():
    k, v, k2, v2 = accounts()

    blk = b.genesis({v: u.denoms.ether * 1})

    code1 = serpent.compile(namecoin_code)
    tx1 = t.contract(0, gasprice, startgas, 0, code1).sign(k)
    s, addr = pb.apply_transaction(blk, tx1)

    snapshot = blk.snapshot()

    # tx2
    tx2 = t.Transaction(1, gasprice, startgas, addr, 0,
                        serpent.encode_datalist(['george', 45]))
    tx2.sign(k)
    s, o = pb.apply_transaction(blk, tx2)
    assert serpent.decode_datalist(o) == [1]

    # tx3
    tx3 = t.Transaction(2, gasprice, startgas, addr, 0,
                        serpent.encode_datalist(['george', 20])).sign(k)
    s, o = pb.apply_transaction(blk, tx3)
    assert serpent.decode_datalist(o) == [0]

    # tx4
    tx4 = t.Transaction(3, gasprice, startgas, addr, 0,
                        serpent.encode_datalist(['harry', 60])).sign(k)
    s, o = pb.apply_transaction(blk, tx4)
    assert serpent.decode_datalist(o) == [1]

    blk.revert(snapshot)

    assert blk.to_dict()
    assert blk.to_dict()['state'][addr]['code']
Exemplo n.º 5
0
def get_hash_without_ed_code():
    global _hash_without_ed_code
    if not _hash_without_ed_code:
        import serpent
        _hash_without_ed_code = get_contract_code(
            serpent.compile(open(hash_without_ed_path).read()))
    return _hash_without_ed_code
Exemplo n.º 6
0
def test_data_feeds():
    k, v, k2, v2 = accounts()
    scode3 = '''
if !contract.storage[1000]:
    contract.storage[1000] = 1
    contract.storage[1001] = msg.sender
    return(0)
elif msg.sender == contract.storage[1001] and msg.datasize == 2:
    contract.storage[msg.data[0]] = msg.data[1]
    return(1)
else:
    return(contract.storage[msg.data[0]])
'''
    code3 = serpent.compile(scode3)
    logger.debug("AST", serpent.rewrite(serpent.parse(scode3)))
    blk = b.genesis({v: 10 ** 18, v2: 10 ** 18})
    tx10 = t.contract(0, gasprice, startgas, 0, code3).sign(k)
    s, addr = pb.apply_transaction(blk, tx10)
    tx11 = t.Transaction(1, gasprice, startgas, addr, 0, '').sign(k)
    s, o = pb.apply_transaction(blk, tx11)
    tx12 = t.Transaction(2, gasprice, startgas, addr, 0,
                         serpent.encode_datalist([500])).sign(k)
    s, o = pb.apply_transaction(blk, tx12)
    assert serpent.decode_datalist(o) == [0]
    tx13 = t.Transaction(3, gasprice, startgas, addr, 0,
                         serpent.encode_datalist([500, 726])).sign(k)
    s, o = pb.apply_transaction(blk, tx13)
    assert serpent.decode_datalist(o) == [1]
    tx14 = t.Transaction(4, gasprice, startgas, addr, 0,
                         serpent.encode_datalist([500])).sign(k)
    s, o = pb.apply_transaction(blk, tx14)
    assert serpent.decode_datalist(o) == [726]
    return blk, addr
Exemplo n.º 7
0
def get_finalizer_code():
    global _finalizer_code
    if not _finalizer_code:
        import serpent
        _finalizer_code = get_contract_code(
            serpent.compile(open(finalizer_path).read()))
    return _finalizer_code
Exemplo n.º 8
0
def test_send_raw_transaction_with_contract(test_app):
    serpent_code = '''
def main(a,b):
    return(a ^ b)
'''
    tx_to = b''
    evm_code = serpent.compile(serpent_code)
    chain = test_app.services.chain.chain
    assert chain.head_candidate.get_balance(tx_to) == 0
    sender = test_app.services.accounts.unlocked_accounts[0].address
    assert chain.head_candidate.get_balance(sender) > 0
    nonce = chain.head_candidate.get_nonce(sender)
    tx = ethereum.transactions.Transaction(nonce, default_gasprice, default_startgas, tx_to, 0, evm_code, 0, 0, 0)
    test_app.services.accounts.sign_tx(sender, tx)
    raw_transaction = data_encoder(rlp.codec.encode(tx, ethereum.transactions.Transaction))
    data_decoder(test_app.client.call('eth_sendRawTransaction', raw_transaction))
    creates = chain.head_candidate.get_transaction(0).creates

    code = chain.head_candidate.account_to_dict(creates)['code']
    assert len(code) > 2
    assert code != '0x'

    test_app.mine_next_block()

    creates = chain.head.get_transaction(0).creates
    code = chain.head.account_to_dict(creates)['code']
    assert len(code) > 2
    assert code != '0x'
Exemplo n.º 9
0
def test_send_transaction_with_contract(test_app):
    serpent_code = '''
def main(a,b):
    return(a ^ b)
'''
    tx_to = b''
    evm_code = serpent.compile(serpent_code)
    chain = test_app.services.chain.chain
    assert chain.head_candidate.get_balance(tx_to) == 0
    sender = test_app.services.accounts.unlocked_accounts[0].address
    assert chain.head_candidate.get_balance(sender) > 0
    tx = {
        'from': address_encoder(sender),
        'to': address_encoder(tx_to),
        'data': evm_code.encode('hex')
    }
    data_decoder(test_app.client.call('eth_sendTransaction', tx))
    creates = chain.head_candidate.get_transaction(0).creates

    code = chain.head_candidate.account_to_dict(creates)['code']
    assert len(code) > 2
    assert code != '0x'

    test_app.mine_next_block()

    creates = chain.head.get_transaction(0).creates
    code = chain.head.account_to_dict(creates)['code']
    assert len(code) > 2
    assert code != '0x'
Exemplo n.º 10
0
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
Exemplo n.º 11
0
def compile(f):
    t = open(f).readlines()
    i = 0
    while 1:
        o = []
        while i < len(t) and (not len(t[i]) or t[i][0] != '='):
            o.append(t[i])
            i += 1
        i += 1
        print '================='
        text = '\n'.join(o).replace('\n\n', '\n')

        lll = serpent.compile_to_lll(text)
        print "LLL:", lll
        print ""

        aevm = serpent.pretty_compile_lll(lll)
        print "AEVM:", aevm
        print ""

        code = serpent.compile(text)
        print "HEX:", code.encode('hex')
        print ""

        if i >= len(t):
            break
Exemplo n.º 12
0
def test_send_transaction_with_contract(test_app):
    serpent_code = '''
def main(a,b):
    return(a ^ b)
'''
    tx_to = b''
    evm_code = serpent.compile(serpent_code)
    chain = test_app.services.chain.chain
    assert chain.head_candidate.get_balance(tx_to) == 0
    sender = test_app.services.accounts.unlocked_accounts[0].address
    assert chain.head_candidate.get_balance(sender) > 0

    eth = test_app.services.console.console_locals['eth']
    tx = eth.transact(to='', data=evm_code, startgas=500000, sender=sender)

    code = chain.head_candidate.account_to_dict(tx.creates)['code']
    assert len(code) > 2
    assert code != '0x'

    test_app.mine_next_block()

    creates = chain.head.get_transaction(0).creates
    code = chain.head.account_to_dict(creates)['code']
    assert len(code) > 2
    assert code != '0x'
Exemplo n.º 13
0
def compile(f):
  t = open(f).readlines()
  i = 0
  while 1:
    o = []
    while i < len(t) and (not len(t[i]) or t[i][0] != '='):
      o.append(t[i])
      i += 1
    i += 1
    print '================='
    text = '\n'.join(o).replace('\n\n', '\n')

    lll = serpent.compile_to_lll(text)
    print "LLL:", lll
    print ""

    aevm = serpent.pretty_compile_lll(lll)
    print "AEVM:", aevm
    print ""

    code = serpent.compile(text)
    print "HEX:", code.encode('hex')
    print ""

    if i >= len(t):
      break
Exemplo n.º 14
0
def test_send_transaction_with_contract(test_app):
    serpent_code = '''
def main(a,b):
    return(a ^ b)
'''
    tx_to = b''
    evm_code = serpent.compile(serpent_code)
    chain = test_app.services.chain.chain
    chainservice = test_app.services.chain
    hc_state = State(chainservice.head_candidate.state_root, chain.env)
    sender = test_app.services.accounts.unlocked_accounts[0].address
    assert hc_state.get_balance(sender) > 0

    eth = test_app.services.console.console_locals['eth']
    tx = eth.transact(to='', data=evm_code, startgas=500000, sender=sender)

    hc_state_dict = State(chainservice.head_candidate.state_root,
                          chain.env).to_dict()
    code = hc_state_dict[encode_hex(tx.creates)]['code']
    assert len(code) > 2
    assert code != '0x'

    test_app.mine_next_block()

    creates = chain.head.transactions[0].creates
    code = chain.state.to_dict()[encode_hex(creates)]['code']
    assert len(code) > 2
    assert code != '0x'
Exemplo n.º 15
0
def get_rlp_decoder_code():
    global _rlp_decoder_code
    if not _rlp_decoder_code:
        import serpent
        _rlp_decoder_code = get_contract_code(
            serpent.compile(open(rlp_decoder_path).read()))
    return _rlp_decoder_code
Exemplo n.º 16
0
def cmd_create(args):
    instance = api.Api()
    contract = compile(open(CONTRACT_FILE).read()).encode('hex')
    contract_address = instance.create(contract, gas=CONTRACT_GAS)
    print "Contract will be available at %s" % contract_address
    if args.wait:
        instance.wait_for_next_block(verbose=True)
    print "Is contract?", instance.is_contract_at(contract_address)
Exemplo n.º 17
0
    def create_contract(self, contract_code, value=0, from_address=None, gas=None, gas_price=None):
        self.update_code(contract_code)
        byte_code = serpent.compile(contract_code)

        self.contract_address = self.eth_sendTransaction(
            data=byte_code, value=value, from_address=from_address, gas=gas, gas_price=gas_price
        )
        return self.contract_address
Exemplo n.º 18
0
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]
Exemplo n.º 19
0
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]
Exemplo n.º 20
0
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]
Exemplo n.º 21
0
def generate_validation_code(addr):
    import serpent
    code = """
# First 32 bytes of input = hash, remaining 96 = signature
mustbe = %s
a = ecrecover(~calldataload(0), ~calldataload(32), ~calldataload(64), ~calldataload(96))
if a != mustbe:
    ~invalid()
return(1)
    """ % ('0x' + utils.normalize_address(addr).encode('hex'))
    return get_contract_code(serpent.compile(code))
Exemplo n.º 22
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)
Exemplo n.º 23
0
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)
Exemplo n.º 24
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)
Exemplo n.º 25
0
    def __init__(self, root_user):
        self.user = root_user
        self.code = serpent.compile(open('./crowdfund.se').read())
        tx = transactions.contract(NonceSingleton.inc(root_user),
                                   Message.DEFAULT_GASPRICE,
                                   Message.DEFAULT_STARTGAS, 0,
                                   self.code).sign(root_user.private_key)

        print "Made crowdfund tx: {}".format(tx)

        self.contract = self._wrap_contract_response(
            processblock.apply_transaction(root_user.genesis, tx))
Exemplo n.º 26
0
    def __init__(self, root_user):
        self.user = root_user
        self.code = serpent.compile(open('./crowdfund.se').read())
        tx = transactions.contract(NonceSingleton.inc(root_user),
                                   Message.DEFAULT_GASPRICE,
                                   Message.DEFAULT_STARTGAS,
                                   0,
                                   self.code).sign(root_user.private_key)

        print "Made crowdfund tx: {}".format(tx)

        self.contract = self._wrap_contract_response(
            processblock.apply_transaction(root_user.genesis, tx))
Exemplo n.º 27
0
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)
Exemplo n.º 28
0
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)
Exemplo n.º 29
0
 def create_contract(self,
                     contract_code,
                     value=0,
                     from_address=None,
                     gas=0,
                     gas_price=0):
     self.update_code(contract_code)
     byte_code = serpent.compile(contract_code)
     self.contract_address = self.eth_sendTransaction(
         data=byte_code,
         value=value,
         from_address=from_address,
         gas=gas,
         gas_price=gas_price)
     return self.contract_address
def init_system(genesis, key):
    code = serpent.compile(open('serp/root.se').read())
    tx_make_root = transactions.Transaction.contract(0,0,10**12, 10000, code).sign(key)
    root_contract = processblock.apply_tx(genesis, tx_make_root)
    
    root_hash = root_contract.encode('hex')

    f = lambda x: write_owner(root_hash, x)
    map(f, ['serp/data.se', 'serp/tag.se', 'serp/users.se', 'serp/currency.se'])

    code = serpent.compile(open('serp/data.se').read())
    tx_make_data = transactions.Transaction.contract(1,0,10**12, 10000, code).sign(key)
    code = serpent.compile(open('serp/tag.se').read())
    tx_make_tag = transactions.Transaction.contract(2,0,10**12, 10000, code).sign(key)
    code = serpent.compile(open('serp/users.se').read())
    tx_make_users = transactions.Transaction.contract(3,0,10**12, 10000, code).sign(key)
    code = serpent.compile(open('serp/currency.se').read())
    tx_make_currency = transactions.Transaction.contract(4,0,10**12, 10000, code).sign(key)

    data_contract = processblock.apply_tx(genesis, tx_make_data)
    tag_contract = processblock.apply_tx(genesis, tx_make_tag)
    users_contract = processblock.apply_tx(genesis, tx_make_users)
    currency_contract = processblock.apply_tx(genesis, tx_make_currency)

    d_contract = data_contract.encode('hex')
    t_contract = tag_contract.encode('hex')
    u_contract = users_contract.encode('hex')
    c_contract = currency_contract.encode('hex')

    #init root
    tx_init_root = transactions.Transaction(5, 0, 10**12, 10000, root_contract, serpent.encode_datalist([d_contract, t_contract, u_contract, c_contract])).sign(key)
    ans = processblock.apply_tx(genesis, tx_init_root)

    adresses = {root_hash:'root', d_contract:'data', t_contract:'tags', u_contract:'users', utils.privtoaddr(key):'me', c_contract:'currency'}

    return adresses
Exemplo n.º 31
0
    def try_create_deploy(self, contract, from_, gas, gas_price, value, retry, skip, wait, verbose, contract_names):
        instance = api.Api(self.config)
        tx_hashes = []

        if contract[-3:] == 'sol' or isinstance(contract_names, list):
            contracts = self.compile_solidity(contract, contract_names)

            for contract_name, contract in contracts:
                logger.debug("%s: %s" % (contract_name, contract))

                tx_hash = self.try_create(contract, contract_name=contract_name, from_=from_, gas=gas, gas_price=gas_price, value=value)

                if not retry:
                    instance.wait_for_transaction(tx_hash, defaultBlock='pending', retry=retry, skip=skip, verbose=verbose)
                    # TODO ... once it's fixed
                    # address = instance.get_contract_address(tx_hash)
                    # self.log_contract(address, contract_name)
                else:
                    successful = False
                    while not successful:
                        successful = instance.wait_for_transaction(tx_hash, defaultBlock='pending', retry=retry, skip=skip, verbose=verbose)
                        if not successful:
                            tx_hash = self.try_create(contract, contract_name=contract_name, from_=from_, gas=gas, gas_price=gas_price, value=value)
                            # TODO ... once it's fixed
                            # address = instance.get_contract_address(tx_hash)
                            # self.log_contract(address, contract_name)

                if wait:
                    if not retry:
                        instance.wait_for_transaction(tx_hash, retry=retry, skip=skip, verbose=verbose)
                    else:
                        successful = False
                        while not successful:
                            successful = instance.wait_for_transaction(tx_hash, retry=retry, skip=skip, verbose=verbose)
                            if not successful:
                                tx_hash = self.try_create(contract, contract_name=contract_name, from_=from_, gas=gas, gas_price=gas_price, value=value)

                # TODO ... once it's fixed, move on up
                address = instance.get_contract_address(tx_hash)
                self.log_contract(address, contract_name)
                tx_hashes.append(tx_hash)
        else:
            contract = compile(open(contract).read()).encode('hex')
            tx_hash = self.try_create(contract, contract_name=contract_names, from_=from_, gas=gas, gas_price=gas_price, value=value)

        if tx_hashes:
            return tx_hashes
        return tx_hash
Exemplo n.º 32
0
def cmd_create(instance, args):
    creator_balance = instance.balance_at(args.from_address)
    balance_required = CONTRACT_GAS * 1e+13 + args.endowment * ETHER
    if creator_balance < balance_required:
        print "Insufficient balance to cover gas for contract creation."
        print "You need at least %d wei in account %s (current balance is %d wei)." % \
            (balance_required, args.from_address, creator_balance)
        return

    contract = serpent.compile(open(CONTRACT_FILE).read()).encode('hex')

    contract_address = instance.create(contract, gas=CONTRACT_GAS, endowment=args.endowment * ETHER)

    print "Contract will be available at %s" % contract_address
    instance.wait_for_contract(contract_address, verbose=True)
    print "Is contract?", instance.is_contract_at(contract_address)
Exemplo n.º 33
0
def test_gas_deduction():
    k, v, k2, v2 = accounts()
    blk = blocks.genesis({v: utils.denoms.ether * 1})
    v_old_balance = blk.get_balance(v)
    assert blk.get_balance(blk.coinbase) == 0
    gasprice = 1
    startgas = 10000
    code1 = serpent.compile(namecoin_code)
    tx1 = transactions.contract(0, gasprice, startgas, 0, code1).sign(k)
    success, addr = processblock.apply_transaction(blk, tx1)
    assert success
    assert blk.coinbase != v
    assert v_old_balance > blk.get_balance(v)
    assert v_old_balance == blk.get_balance(v) + blk.get_balance(blk.coinbase)
    intrinsic_gas_used = processblock.GTXCOST + \
        processblock.GTXDATA * len(tx1.data)
    assert v_old_balance - blk.get_balance(v) >= intrinsic_gas_used * gasprice
Exemplo n.º 34
0
def test_gas_deduction():
    k, v, k2, v2 = accounts()
    blk = blocks.genesis({v: utils.denoms.ether * 1})
    v_old_balance = blk.get_balance(v)
    assert blk.get_balance(blk.coinbase) == 0
    gasprice = 1
    startgas = 10000
    code1 = serpent.compile(namecoin_code)
    tx1 = transactions.contract(0, gasprice, startgas, 0, code1).sign(k)
    success, addr = processblock.apply_transaction(blk, tx1)
    assert success
    assert blk.coinbase != v
    assert v_old_balance > blk.get_balance(v)
    assert v_old_balance == blk.get_balance(v) + blk.get_balance(blk.coinbase)
    intrinsic_gas_used = processblock.GTXCOST + \
        processblock.GTXDATA * len(tx1.data)
    assert v_old_balance - blk.get_balance(v) >= intrinsic_gas_used * gasprice
Exemplo n.º 35
0
def test_currency():
    k, v, k2, v2 = accounts()
    scode2 = '''
if !contract.storage[1000]:
    contract.storage[1000] = 1
    contract.storage[0x%s] = 1000
    return(1)
elif msg.datasize == 1:
    addr = msg.data[0]
    return(contract.storage[addr])
else:
    from = msg.sender
    fromvalue = contract.storage[from]
    to = msg.data[0]
    value = msg.data[1]
    if fromvalue >= value:
        contract.storage[from] = fromvalue - value
        contract.storage[to] = contract.storage[to] + value
        return(1)
    else:
        return(0)
    ''' % v
    code2 = serpent.compile(scode2)
    blk = b.genesis({v: 10 ** 18})
    tx4 = t.contract(0, gasprice, startgas, 0, code2).sign(k)
    s, addr = pb.apply_transaction(blk, tx4)
    tx5 = t.Transaction(1, gasprice, startgas, addr, 0, '').sign(k)
    s, o = pb.apply_transaction(blk, tx5)
    assert serpent.decode_datalist(o) == [1]
    tx6 = t.Transaction(2, gasprice, startgas, addr, 0,
                        serpent.encode_datalist([v2, 200])).sign(k)
    s, o = pb.apply_transaction(blk, tx6)
    assert serpent.decode_datalist(o) == [1]
    tx7 = t.Transaction(3, gasprice, startgas, addr, 0,
                        serpent.encode_datalist([v2, 900])).sign(k)
    s, o = pb.apply_transaction(blk, tx7)
    assert serpent.decode_datalist(o) == [0]
    tx8 = t.Transaction(4, gasprice, startgas, addr, 0,
                        serpent.encode_datalist([v])).sign(k)
    s, o = pb.apply_transaction(blk, tx8)
    assert serpent.decode_datalist(o) == [800]
    tx9 = t.Transaction(5, gasprice, startgas, addr, 0,
                        serpent.encode_datalist([v2])).sign(k)
    s, o = pb.apply_transaction(blk, tx9)
    assert serpent.decode_datalist(o) == [200]
Exemplo n.º 36
0
def cmd_create(instance, args):
    creator_balance = instance.balance_at(args.from_address)
    balance_required = CONTRACT_GAS * 1e+13 + args.endowment * ETHER
    if creator_balance < balance_required:
        print "Insufficient balance to cover gas for contract creation."
        print "You need at least %d wei in account %s (current balance is %d wei)." % \
            (balance_required, args.from_address, creator_balance)
        return

    contract = serpent.compile(open(CONTRACT_FILE).read()).encode('hex')

    contract_address = instance.create(contract,
                                       gas=CONTRACT_GAS,
                                       endowment=args.endowment * ETHER)

    print "Contract will be available at %s" % contract_address
    instance.wait_for_contract(contract_address, verbose=True)
    print "Is contract?", instance.is_contract_at(contract_address)
Exemplo n.º 37
0
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)
Exemplo n.º 38
0
    def setup_class(self):
        self.state = tester.state()  # Create test blockchain

        # Solidity version
        _, self.mul7_evm = solc(self.mul7)  # Compile
        print('>>> Solidity evm: {}'.format(self.mul7_evm))
        self.addr = self.state.contract(self.mul7_evm, OWNER['key'], 0)
        print('>>> Solidity contract address: {}'.format(self.addr))
        #self.mul7_evm = '0x{}'.format(self.mul7_evm)
        self.mul7_decoded = self.mul7_evm.decode('hex')
        print('>>> Solidity decode-hex: {}'.format(
            self.mul7_evm.decode('hex')))
        #self.state.evm(self.mul7_evm, sender=self.OWNER, endowment=0)
        self.state.evm(self.mul7_decoded, sender=self.OWNER, endowment=0)

        # Serpent version
        #self.mul7se_evm = self.state.abi_contract(self.mul7se)
        self.mul7se_evm = serpent.compile(open(self.mul7se).read())
        self.mul7se_rlp_decode = rlp.decode(self.mul7se_evm)
        print('>>> Serpent compile: {}'.format(self.mul7se_evm))
Exemplo n.º 39
0
def test_send_transaction_with_contract(test_app, serpent_code, sender_id,
                                        receiver_id):
    evm_code = serpent.compile(serpent_code)
    chain = test_app.services.chain.chain
    chainservice = test_app.services.chain
    hc_state = State(chainservice.head_candidate.state_root, chain.env)
    sender = test_app.services.accounts.unlocked_accounts[sender_id].address
    receiver = test_app.services.accounts.unlocked_accounts[
        receiver_id].address
    print sender
    print type(sender)

    assert hc_state.get_balance(sender) > 0

    eth = test_app.services.console.console_locals['eth']
    tx = eth.transact(to=receiver,
                      value=1,
                      data=evm_code,
                      startgas=500000,
                      sender=sender)

    test_app.mine_next_block()
    return tx
Exemplo n.º 40
0
    def create(self, contract, from_, gas, gas_price, value, wait, contract_names=None):
        instance = api.Api(self.config)
        if wait:
            from_block = instance.last_block()

        contract_addresses = []
        if contract[-3:] == 'sol' or contract_names:
            contracts = self.compile_solidity(contract, contract_names)
            if contract_names:
                for contract_name, contract in contracts:
                    logger.debug("%s: %s" % (contract_name, contract))
                    contract_address = instance.create(contract, from_=from_, gas=gas, gas_price=gas_price, endowment=value)
                    contract_addresses.append(contract_address)
                    logger.info("      Contract '%s' will be available at %s" % (contract_name, contract_address))
                    instance.wait_for_contract(
                        address=contract_address,
                        defaultBlock='pending',
                        verbose=(True if self.config.get('misc', 'verbosity') > 1 else False))
            else:
                contract_address = instance.create(contract, from_=from_, gas=gas, gas_price=gas_price, endowment=value)
                logger.info("      Contract will be available at %s" % contract_address)
        else:
            contract = compile(open(contract).read()).encode('hex')
            contract_address = instance.create(contract, from_=from_, gas=gas, gas_price=gas_price, endowment=value)
            logger.info("      Contract will be available at %s" % contract_address)

        instance.wait_for_contract(
            address=contract_address,
            defaultBlock='pending',
            verbose=(True if self.config.get('misc', 'verbosity') > 1 else False))

        if wait:
            instance.wait_for_next_block(from_block=from_block, verbose=(True if self.config.get('misc', 'verbosity') > 1 else False))

        if contract_addresses:
            return contract_addresses
        return contract_address
Exemplo n.º 41
0
		h = "%02x"%n
	l = len(h)
	return "0"*(32-l)+h

nargs = pad32(1)
d0 = pad32('hi')
print nargs, d0
msg_hash = utils.sha3(nargs+d0)
v, r, s = bitcoin.ecdsa_raw_sign(msg_hash, key)
pubkey = bitcoin.privkey_to_pubkey(key)
verified = bitcoin.ecdsa_raw_verify(msg_hash, (v,r,s), pubkey)

gen = blocks.genesis({addr: 10**18})

print serpent.compile_to_assembly(open("DAOist frame.se").read())
DAOcode = serpent.compile(open("DAOist frame.se").read())

DAOcontract = transactions.contract(0, 1, 10**12, 100, DAOcode)

DAOcontract.sign(key)

success, contract_address = processblock.apply_tx(gen, DAOcontract)

DCP = transactions.Transaction(1,10**12, 10000, contract_address, 0, serpent.encode_datalist([1,1,v,r,s,1,'hi']))
DCP.sign(key)

success, result = processblock.apply_tx(gen, DCP)

print "success: ", success
print serpent.decode_datalist(result)
Exemplo n.º 42
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"
Exemplo n.º 43
0
    def lint(self):
        self.exit_code = 0

        self.checks = []
        self.logged_messages = []
        self.scope = defaultdict(dict)

        self.data = []
        self.events = []
        self.macros = []
        self.methods = []
        # self.structs = {}

        # ('Error (file "main", line 2, char 12): Invalid argument count ...
        try:
            # override stdout since serpent tries to print the exception itself
            with stdout_redirected(), merged_stderr_stdout():
                serpent.compile(self.code)
        except Exception as e:
            match = RE_EXCEPTION.search(e.args[0])

            if match:
                self.log_message(match.group('line'),
                                 match.group('character'),
                                 COMPILE_ERROR,
                                 match.group('message'),
                                 reposition=False)
            else:
                click.echo('Exception: {}'.format(e.args[0]), err=True)

                sys.exit(1)

        # ('Error (file "main", line 2, char 12): Invalid argument count ...
        try:
            # override stdout since serpent tries to print the exception itself
            with stdout_redirected(), merged_stderr_stdout():
                contract_ast = serpent.parse(self.code)
        except Exception as e:
            match = RE_EXCEPTION.search(e.args[0])

            if match:
                self.log_message(match.group('line'),
                                 match.group('character'),
                                 PARSE_ERROR,
                                 match.group('message'),
                                 reposition=False)
            else:
                click.echo('Exception: {}'.format(e.args[0]), err=True)

            sys.exit(1)

        self.traverse(contract_ast)

        self.resolve_checks()

        for method, variables in self.scope.items():
            if not method:
                continue

            for variable, metadata in variables.items():
                if not metadata['accessed']:
                    if metadata['type'] == 'argument':
                        self.log_message(
                            metadata['token'].metadata.ln,
                            metadata['token'].metadata.ch, UNUSED_ARGUMENT,
                            'Unused argument "{}"'.format(variable))
                    elif (metadata['type'] == 'assignment'
                          and variable not in GLOBALS):
                        self.log_message(
                            metadata['token'].metadata.ln,
                            metadata['token'].metadata.ch,
                            UNREFERENCED_ASSIGNMENT,
                            'Unreferenced assignment "{}"'.format(variable))

        if self.debug:
            from pprint import pformat

            click.echo('scope ' + pformat(self.scope.items()))

            click.echo('data ' + pformat(self.data))
            click.echo('events ' + pformat(self.events))
            click.echo('macros ' + pformat(self.macros))
            click.echo('methods ' + pformat(self.methods))
            # click.echo('structs', pformat(self.structs))

        return self.exit_code
Exemplo n.º 44
0
# Give tx2 some money
tx = t.Transaction(0, 10**16, 10**12, 1000, v2, '').sign(k)
pb.apply_tx(blk, tx)
print "New balance of v1: ", blk.get_balance(v)
print "New balance of v2: ", blk.get_balance(v2)

print "Starting namecoin tests"
blk = b.Block.genesis({v: 10**18})
scode1 = '''
if !contract.storage[msg.data[0]]:
    contract.storage[msg.data[0]] = msg.data[1]
    return(1)
else:
    return(0)
'''
code1 = serpent.compile(scode1)
print "AST", serpent.rewrite(serpent.parse(scode1))
print "Assembly", serpent.compile_to_assembly(scode1)
tx1 = t.Transaction.contract(0, 0, 10**12, 1000, code1).sign(k)
addr = pb.apply_tx(blk, tx1)
snapshot = blk.snapshot()
print "Contract address", addr.encode('hex')
tx2 = t.Transaction(1, 0, 10**12, 1000, addr,
                    serpent.encode_datalist(['george', 45]))
tx2.sign(k)
o = pb.apply_tx(blk, tx2)
print "Result of registering george:45: ", serpent.decode_datalist(o)
tx3 = t.Transaction(2, 0, 10**12, 1000, addr,
                    serpent.encode_datalist(['george', 20])).sign(k)
o = pb.apply_tx(blk, tx3)
print "Result of registering george:20: ", serpent.decode_datalist(o)
Exemplo n.º 45
0
# customize VM log output to your needs
# hint: use 'py.test' with the '-s' option to dump logs to the console
tester.set_logging_level(2)

gasprice = 0
startgas = 10000


# Test EVM contracts
serpent_code = '''
def main(a,b):
    return(a ^ b)
'''

evm_code = serpent.compile(serpent_code)


def test_evm():
    s = tester.state()
    c = s.evm(evm_code)
    o = s.call(tester.k0, c, 0, 'main', 'ii', [2, 5])
    assert o == [32]


# Test serpent compilation of variables using _with_, doing a simple
# arithmetic calculation 20 * 30 + 10 = 610
sixten_code =\
    '''
(with 'x 10
    (with 'y 20
Exemplo n.º 46
0
    elif msg.datasize == 1:
        #check if all the tickets are sold
        if contract.storage[1] < MAXIMUM_TICKETS:
            return(2)
        if block.timestamp - contract.storage[2] < 100:
            return(2)
        #start drawing
        t = block.prevhash%MAXIMUM_TICKETS
        send(1000, contract.storage[3+t+1], MAXIMUM_TICKETS*(10**15))
        return (3+t+1)
'''
import serpent
from pyethereum import transactions, blocks, processblock, utils
import time

code = serpent.compile(lottery)
key = utils.sha3('cow')
addr = utils.privtoaddr(key)
key2 = utils.sha3('cow2')
addr2 = utils.privtoaddr(key2)
key_host = utils.sha3('host')
add_host = utils.privtoaddr(key_host)


#initialize the block
genesis = blocks.genesis({addr: 10**18, addr2: 10**18, add_host: 10**18})

#This is to initialize the contract
tx1 = transactions.contract(0,10**12,10000,0,code).sign(key_host)
result, contract = processblock.apply_transaction(genesis, tx1)
Exemplo n.º 47
0
def mk_validation_code(address):
    return serpent.compile(code_template % (utils.checksum_encode(address)))
Exemplo n.º 48
0
Arquivo: build.py Projeto: krl/zeroid
import serpent, json, random
from pyethereum import transactions, blocks, processblock,utils

NUM_ACCOUNTS=4

root_code = serpent.compile(open('zeroid.se').read())
root_key = utils.sha3('cow')
root_addr = utils.privtoaddr(root_key)

keys = {}

for x in range(NUM_ACCOUNTS):
  key  = utils.sha3(str(x+4))
  addr = utils.privtoaddr(key)
  keys[addr] = key

endowment = {root_addr: 10**18}

for x in keys:
  endowment[x] = 10**18

genesis = blocks.genesis(endowment)

tx1 = transactions.contract(0, 10**12, 100000, 0, root_code).sign(root_key)

result, contract = processblock.apply_transaction(genesis, tx1)

nonce=1

for address in keys:
Exemplo n.º 49
0
import serpent
import rlp
from ethereum import utils
from ethereum import tester
from ethereum import transactions

sighash = serpent.compile('sighash.se.py')

tests = [
    [b"\x01"],
    [b"\x80", "a"],
    [b"\x81", "b"],
    [b""],
    [b"", b"\x01", b""],
    [b"", b"\x81", b""],
    [b"dog", b"c" * 54, b"\x01"],
    [b"\x01", b"c" * 55, b"pig"],
    [b"moose", b"c" * 56, b"\x00"],
    [b'\x01', b'55555555555555555555555555555555', b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'', b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1b\x88\xa7\x85r\x1b3\x17\xcaP\x96\xca\xd3S\xfcgM\xec\xe0\xf5!\xc8\xb4m\xd9\xb7E\xf3\x81d\x87\x93VD\xe0Ej\xcd\xec\x80\x11\x86(qZ\x9b\x80\xbf\xce\xe5*\r\x9d.o\xcd\x11s\xc5\xbc\x8c\xcb\xb9\xa9 ']
]

s = tester.state()
c = s.evm(sighash, sender=tester.k0, endowment=0)

for test in tests:
    z = s.send(tester.k0, c, 0, rlp.encode(test)) 
    assert z == utils.sha3(rlp.encode(test[:-1]))
    print("Passed test, gas consumed: ", s.state.receipts[-1].gas_used - s.state.receipts[-2].gas_used - s.last_tx.intrinsic_gas_used)

# Create transaction
Exemplo n.º 50
0
def test_hedge():
    k, v, k2, v2 = accounts()
    blk, addr = test_data_feeds()
    scode4 = '''
if !contract.storage[1000]:
    contract.storage[1000] = msg.sender
    contract.storage[1002] = msg.value
    contract.storage[1003] = msg.data[0]
    return(1)
elif !contract.storage[1001]:
    ethvalue = contract.storage[1002]
    if msg.value >= ethvalue:
        contract.storage[1001] = msg.sender
    othervalue = ethvalue * call(0x%s,[contract.storage[1003]],1)
    contract.storage[1004] = othervalue
    contract.storage[1005] = block.timestamp + 86400
    return([2,othervalue],2)
else:
    othervalue = contract.storage[1004]
    ethvalue = othervalue / call(0x%s,contract.storage[1003])
    if ethvalue >= contract.balance:
        send(contract.storage[1000],contract.balance)
        return(3)
    elif block.timestamp > contract.storage[1005]:
        send(contract.storage[1001],contract.balance - ethvalue)
        send(contract.storage[1000],ethvalue)
        return(4)
    else:
        return(5)
''' % (addr, addr)
    code4 = serpent.compile(scode4)
    logger.debug("AST", serpent.rewrite(serpent.parse(scode4)))
    # important: no new genesis block
    tx15 = t.contract(5, gasprice, startgas, 0, code4).sign(k)
    s, addr2 = pb.apply_transaction(blk, tx15)
    tx16 = t.Transaction(6, gasprice, startgas, addr2, 10 ** 17,
                         serpent.encode_datalist([500])).sign(k)
    s, o = pb.apply_transaction(blk, tx16)
    assert serpent.decode_datalist(o) == [1]
    tx17 = t.Transaction(0, gasprice, startgas, addr2, 10 ** 17,
                         serpent.encode_datalist([500])).sign(k2)
    s, o = pb.apply_transaction(blk, tx17)
    assert serpent.decode_datalist(o) == [2, 72600000000000000000L]
    snapshot = blk.snapshot()
    tx18 = t.Transaction(7, gasprice, startgas, addr2, 0, '').sign(k)
    s, o = pb.apply_transaction(blk, tx18)
    assert serpent.decode_datalist(o) == [5]
    tx19 = t.Transaction(8, gasprice, startgas, addr, 0,
                         serpent.encode_datalist([500, 300])).sign(k)
    s, o = pb.apply_transaction(blk, tx19)
    assert serpent.decode_datalist(o) == [1]
    tx20 = t.Transaction(9, gasprice, startgas, addr2, 0, '').sign(k)
    s, o = pb.apply_transaction(blk, tx20)
    assert serpent.decode_datalist(o) == [3]
    blk.revert(snapshot)
    blk.timestamp += 200000
    tx21 = t.Transaction(7, gasprice, startgas, addr, 0,
                         serpent.encode_datalist([500, 1452])).sign(k)
    s, o = pb.apply_transaction(blk, tx21)
    assert serpent.decode_datalist(o) == [1]
    tx22 = t.Transaction(8, gasprice, 2000, addr2, 0, '').sign(k)
    s, o = pb.apply_transaction(blk, tx22)
    assert serpent.decode_datalist(o) == [4]
Exemplo n.º 51
0
def compile(f):
  t = open(f).readlines()
  i = 0
  while 1:
    o = []
    while i < len(t) and (not len(t[i]) or t[i][0] != '='):
      o.append(t[i])
      i += 1
    i += 1
    print '================='
    text = '\n'.join(o).replace('\n\n', '\n')
    # print text

    # ast = serpent.parse(text)
    # print "AST:", ast
    # print ""

    lll = serpent.compile_to_lll(text)
    print "LLL:", lll
    print ""

    aevm = serpent.pretty_compile_lll(lll)
    print "AEVM:", aevm # .encode('hex') # ' '.join([str(x) for x in aevm])
    print ""

    # print ' '.join([str(x) for x in aevm])
    # s = open(f).read()
    code = serpent.compile(text)
    print "HEX:", code.encode('hex')
    print ""
    # code = compiler.decode_datalist(compiler.encode_datalist(ast))

    # ops = serpent.analyze(ast)
    # print "Analysis:", ops
    # print ""

    # code = serpent.assemble(aevm)
    # print "Output:", aevm
    # print "0x" + code.encode('hex') #' '.join([str(x) for x in aevm])

    # print "Int:"
    # asint = int(code.encode('hex'), 16)
    # print asint
    # print ""
    # aslist = compiler.decode_datalist("0x" + code.encode('hex'))

    # print "Datalist of size %d:" % len(aslist)
    # hexlist = list()
    # for item in aslist:
    #   hexlist.append(hex(item)[:-1])
    # print hexlist
    # print ""

    # print "Decoded hex:"
    # ashex = list()
    # for item in hexlist:
    #   ashex.append(int(item, 16))
    # ascode = compiler.encode_datalist(ashex).replace('\n', '')
    # print ascode

    # print "Serialized:"
    # print compile_from_assembly(json.dumps(ast))
    # print ""

    # strcode = "0x" + code.encode('hex')
    # print strcode
    # print (type(ascode), type(strcode), len(ascode), len(strcode))
    # print (intern(strcode) == intern(ascode))
    # if (intern(ascode) == intern(strcode)):
    #   print "Code OK"
    # else:
    #   print "Code mismatch"

    if i >= len(t):
      break
Exemplo n.º 52
0
def load_serpent(filename):
    return serpent.compile(open(filename).read())
Exemplo n.º 53
0
# Give tx2 some money
tx = t.Transaction(0,10**16,10**12,1000,v2,'').sign(k)
pb.apply_tx(blk,tx)
print "New balance of v1: ", blk.get_balance(v)
print "New balance of v2: ", blk.get_balance(v2)

print "Starting namecoin tests"
blk = b.Block.genesis({ v: 10**18 })
scode1 = '''
if !contract.storage[msg.data[0]]:
    contract.storage[msg.data[0]] = msg.data[1]
    return(1)
else:
    return(0)
'''
code1 = serpent.compile(scode1)
print "AST", serpent.rewrite(serpent.parse(scode1))
print "Assembly", serpent.compile_to_assembly(scode1)
tx1 = t.Transaction.contract(0,0,10**12,1000,code1).sign(k)
addr = pb.apply_tx(blk,tx1)
snapshot = blk.snapshot()
print "Contract address", addr.encode('hex')
tx2 = t.Transaction(1,0,10**12,1000,addr,serpent.encode_datalist(['george',45]))
tx2.sign(k)
o = pb.apply_tx(blk,tx2)
print "Result of registering george:45: ", serpent.decode_datalist(o)
tx3 = t.Transaction(2,0,10**12,1000,addr,serpent.encode_datalist(['george',20])).sign(k)
o = pb.apply_tx(blk,tx3)
print "Result of registering george:20: ", serpent.decode_datalist(o)
tx4 = t.Transaction(3,0,10**12,1000,addr,serpent.encode_datalist(['harry',60])).sign(k)
o = pb.apply_tx(blk,tx4)
Exemplo n.º 54
0
def new_config(data_dir=None):
    cfg = _get_default_config()
    if not data_dir:
        tempfile.mktemp()
    cfg.set('misc', 'data_dir', data_dir)
    return cfg


### From here is pasted together from earlier version of pyetherem

import serpent
from pyethereum import transactions, blocks, processblock, utils

#processblock.print_debug = 1
from pyethereum import slogging
slogging.set_level('eth.tx',"DEBUG")

code = serpent.compile(namecoin_code)
key = utils.sha3('cow')
addr = utils.privtoaddr(key)
genesis = blocks.genesis(new_db(), { addr: 10**18 })
tx1 = transactions.contract(nonce=0,gasprice=10**12,startgas=10000,endowment=0,code=code).sign(key)
result, contract = processblock.apply_transaction(genesis,tx1)
print genesis.to_dict()
tx2 = transactions.Transaction(nonce=1,gasprice=10**12,startgas=10000,to=contract,value=0,
                               data=serpent.encode_abi(0,1,45)).sign(key)
result, ans = processblock.apply_transaction(genesis,tx2)
serpent.decode_datalist(ans)
#print genesis.to_dict()
Exemplo n.º 55
0
        return(0)


        
'''
import serpent
from pyethereum import transactions, blocks, processblock, utils
import time
import sys

#require command line args
if len(sys.argv) < 3:
    print("Usage: %s [price] [recipient: transcation success: 2, transcation deny: 3]  [sender: transcation success: 2, transcation deny: 3]" %sys.argv[0])
    sys.exit(1)

code = serpent.compile(escrow)
sender_key = utils.sha3('sender')
sender_addr = utils.privtoaddr(sender_key)
recipient_key = utils.sha3('recipient')
recipient_addr = utils.privtoaddr(recipient_key)
host_key = utils.sha3('host')
host_addr = utils.privtoaddr(host_key)

#initialize the block
genesis = blocks.genesis({sender_addr: 10**18, recipient_addr: 10**18, host_addr: 10**18})

#initialize the contract
tx1 = transactions.contract(0, 10**12, 10000, 0, code).sign(host_key)
result, contract = processblock.apply_transaction(genesis, tx1)

#execute escrow transaction
Exemplo n.º 56
0
This script loads serpent contracts onto the block chain using the geth RPC
To load a contract onto the chain, do something like:
    ./load_contract.py junk.se
This script will compile the file using serpent, and send it to a locally running geth node.
In order to use this script successfully, you need to prepare your geth node.
Start up a geth console using:
    geth --loglevel 0 console
Once there, make a new account if needed:
    admin.newAccount()
This will ask you to set a password, which you must remember!!!
If you don't have any money, you will have to mine for it:
    admin.miner.start()
You will also have to start the RPC server:
    admin.startRPC('127.0.0.1', 8545)
And then finally you will have to unlock your account:
    admin.unlock(eth.coinbase, undefined, 60*60*24*30*12)
This will prompt you for the password you chose earlier.
'''
import warnings; warnings.simplefilter('ignore')
from colorama import init, Fore, Style
from tests.gethrpc import GethRPC, dumps
import serpent
import sys

init()
rpc = GethRPC()
coinbase_data = rpc.eth_coinbase()
coinbase = coinbase_data['result']
evm = '0x' + serpent.compile(sys.argv[1]).encode('hex')
data = rpc.eth_sendTransaction(sender=coinbase, gas=hex(3141500), data=evm)