Esempio n. 1
0
    def acceptInputs(self, r, payL, payR, wdrawL, wdrawR):
        assert self.status == "OK"
        assert r == self.lastRound + 1
        # Assumption - don't call acceptInputs(r,...) multiple times

        depositsL    = contract.deposits(0);
        depositsR    = contract.deposits(1);
        withdrawalsL = contract.withdrawals(0);
        withdrawalsR = contract.withdrawals(1);

        _, (creditsL, creditsR, withdrawnL, withdrawnR) = self.lastCommit

	assert payL <= depositsL + creditsL
	assert payR <= depositsR + creditsR
	assert wdrawL <= depositsL + creditsL - payL
	assert wdrawR <= depositsR + creditsR - payR

	creditsL += payR - payL - wdrawL
	creditsR += payL - payR - wdrawR
        withdrawalsL += wdrawL
        withdrawalsR += wdrawR

        self.lastProposed = (creditsL, creditsR, withdrawalsL, withdrawalsR)

        self.h = utils.sha3(zfill(utils.int_to_bytes(r)) +
                            zfill(int_to_bytes(creditsL)) +
                            zfill(int_to_bytes(creditsR)) +
                            zfill(utils.int_to_bytes(withdrawalsL)) +
                            zfill(utils.int_to_bytes(withdrawalsR)))
        sig = sign(self.h, self.sk)
        broadcast(self, r, self.h, sig)
        return sig
Esempio n. 2
0
def state_to_bytes(contract, r, credits_L, credits_R, withdrawal_L,
                   withdrawal_R):
    return contract +\
           zfill(utils.int_to_bytes(r)) +\
           zfill(int_to_bytes(credits_L)) +\
           zfill(int_to_bytes(credits_R)) +\
           zfill(utils.int_to_bytes(withdrawal_L)) +\
           zfill(utils.int_to_bytes(withdrawal_R))
Esempio n. 3
0
def serialize_block(block, full_transactions):
    if full_transactions:
        transactions = [
            serialize_txn(block, txn, txn_index)
            for txn_index, txn in enumerate(block.transaction_list)
        ]
    else:
        transactions = [encode_hex(txn.hash) for txn in block.transaction_list]

    unpadded_logs_bloom = ethereum_utils.int_to_bytes(block.bloom)
    logs_bloom = "\x00" * (256 - len(unpadded_logs_bloom)) + unpadded_logs_bloom

    return {
        "number": int_to_hex(block.number),
        "hash": "0x" + encode_hex(block.hash),
        "parentHash": "0x" + encode_hex(block.prevhash),
        "nonce": "0x" + encode_hex(block.nonce),
        "sha3Uncles": "0x" + encode_hex(block.uncles_hash),
        # TODO logsBloom / padding
        "logsBloom": logs_bloom,
        "transactionsRoot": "0x" + encode_hex(block.tx_list_root),
        "stateRoot": "0x" + encode_hex(block.state_root),
        "miner": "0x" + encode_hex(block.coinbase),
        "difficulty": int_to_hex(block.difficulty),
        # https://github.com/ethereum/pyethereum/issues/266
        # "totalDifficulty": int_to_hex(block.chain_difficulty()),
        "size": int_to_hex(len(ethereum_utils.rlp.encode(block))),
        "extraData": "0x" + encode_hex(block.extra_data),
        "gasLimit": int_to_hex(block.gas_limit),
        "gasUsed": int_to_hex(block.gas_used),
        "timestamp": int_to_hex(block.timestamp),
        "transactions": transactions,
        "uncles": block.uncles
    }
Esempio n. 4
0
def serialize_block(block, full_transactions):
    if full_transactions:
        transactions = [
            serialize_txn(block, txn, txn_index)
            for txn_index, txn in enumerate(block.transaction_list)
        ]
    else:
        transactions = [encode_hex(txn.hash) for txn in block.transaction_list]

    unpadded_logs_bloom = ethereum_utils.int_to_bytes(block.bloom)
    logs_bloom = "\x00" * (256 -
                           len(unpadded_logs_bloom)) + unpadded_logs_bloom

    return {
        "number": int_to_hex(block.number),
        "hash": "0x" + encode_hex(block.hash),
        "parentHash": "0x" + encode_hex(block.prevhash),
        "nonce": "0x" + encode_hex(block.nonce),
        "sha3Uncles": "0x" + encode_hex(block.uncles_hash),
        # TODO logsBloom / padding
        "logsBloom": logs_bloom,
        "transactionsRoot": "0x" + encode_hex(block.tx_list_root),
        "stateRoot": "0x" + encode_hex(block.state_root),
        "miner": "0x" + encode_hex(block.coinbase),
        "difficulty": int_to_hex(block.difficulty),
        # https://github.com/ethereum/pyethereum/issues/266
        # "totalDifficulty": int_to_hex(block.chain_difficulty()),
        "size": int_to_hex(len(ethereum_utils.rlp.encode(block))),
        "extraData": "0x" + encode_hex(block.extra_data),
        "gasLimit": int_to_hex(block.gas_limit),
        "gasUsed": int_to_hex(block.gas_used),
        "timestamp": int_to_hex(block.timestamp),
        "transactions": transactions,
        "uncles": block.uncles
    }
Esempio n. 5
0
def decompress(data):
    o = b''
    i = 0
    while i < len(data):
        if int_to_bytes(data[i]) == b'\xfe':
            if i == len(data) - 1:
                raise Exception("Invalid encoding, \\xfe at end")
            elif int_to_bytes(data[i + 1]) == b'\x00':
                o += b'\xfe'
            elif int_to_bytes(data[i + 1]) == b'\x01':
                o += NULLSHA3
            else:
                o += b'\x00' * safe_ord(data[i + 1])
            i += 1
        else:
            o += int_to_bytes(data[i])
        i += 1
    return o
Esempio n. 6
0
def decompress(data):
    o = b''
    i = 0
    while i < len(data):
        if int_to_bytes(data[i]) == b'\xfe':
            if i == len(data) - 1:
                raise Exception("Invalid encoding, \\xfe at end")
            elif int_to_bytes(data[i + 1]) == b'\x00':
                o += b'\xfe'
            elif int_to_bytes(data[i + 1]) == b'\x01':
                o += NULLSHA3
            else:
                o += b'\x00' * safe_ord(data[i + 1])
            i += 1
        else:
            o += int_to_bytes(data[i])
        i += 1
    return o
def encode_balance(balances):
    assert len(balances) <= 32
    assert sum(balances) <= 100
    assert all(0 <= b < 256 for b in balances)
    val = 0
    for b in balances[::-1]:
        val *= 256
        val += b
    return zfill(utils.int_to_bytes(val))
Esempio n. 8
0
def make_block_from_txs(db, txs):
    merkle_leaves = []
    for t in txs:
        offset = int_to_bytes(t['contents']['offset']).rjust(8, b"\x00")
        tx_hash = sha3(json.dumps(t))
        leaf = b''.join([tx_hash, offset])  # hash = leaf[:32] & sum = leaf[32:]
        db.put(leaf, json.dumps(t))
        merkle_leaves.append(leaf)
    merkle_root = construct_tree(db, merkle_leaves)
    return merkle_root
Esempio n. 9
0
def compress(data):
    o = b''
    i = 0
    while i < len(data):
        if int_to_bytes(data[i]) == b'\xfe':
            o += b'\xfe\x00'
        elif data[i:i + 32] == NULLSHA3:
            o += b'\xfe\x01'
            i += 31
        elif data[i:i + 2] == b'\x00\x00':
            p = 2
            while p < 255 and i + p < len(data) and int_to_bytes(data[i + p]) == b'':
                p += 1
            o += b'\xfe' + ascii_chr(p)
            i += p - 1
        else:
            o += int_to_bytes(data[i])
        i += 1
    return o
Esempio n. 10
0
def generate_dummy_block(db, num_txs, random_interval, total_deposits):
    full_tx_list = fill_tx_list_with_notxs(generate_dummy_txs(num_txs, random_interval, total_deposits))
    merkle_leaves = []
    for t in full_tx_list:
        offset = int_to_bytes(t['contents']['offset']).rjust(8, b"\x00")
        tx_hash = sha3(json.dumps(t))
        leaf = b''.join([tx_hash, offset])  # hash = leaf[:32] & sum = leaf[32:]
        db.put(leaf, json.dumps(t))
        merkle_leaves.append(leaf)
    merkle_root = construct_tree(db, merkle_leaves)
    return merkle_root
Esempio n. 11
0
def compress(data):
    o = b''
    i = 0
    while i < len(data):
        if int_to_bytes(data[i]) == b'\xfe':
            o += b'\xfe\x00'
        elif data[i:i + 32] == NULLSHA3:
            o += b'\xfe\x01'
            i += 31
        elif data[i:i + 2] == b'\x00\x00':
            p = 2
            while p < 255 and i + \
                    p < len(data) and int_to_bytes(data[i + p]) == b'\x00':
                p += 1
            o += b'\xfe' + ascii_chr(p)
            i += p - 1
        else:
            o += int_to_bytes(data[i])
        i += 1
    return o
Esempio n. 12
0
 def verify_merkle_proof(self, blockhash, tx, proof):
     h = get_sum_hash_of_tx(tx)
     for i in range(0, len(proof) - 1):
         if proof[i][0] == 'left':
             new_value = b''.join([h, proof[i][1]])
         else:
             new_value = b''.join([proof[i][1], h])
         new_sum = int_to_bytes(
             bytes_to_int(h[32:]) + bytes_to_int(proof[i][1][32:])).rjust(
                 8, b"\x00")
         h = b''.join([sha3(new_value), new_sum])
     return h == proof[-1]
Esempio n. 13
0
 def subprotocolOutput(self, r, hashes, m):
     assert not self.isTriggered
     assert len(hashes) == self.n
     assert r == self.lastOpenRound + 1
     assert self.lastOpenRound == self.lastClosedRound
     assert hashes[self.i] == utils.sha3(m)
     self.hashes = hashes
     self.h = utils.sha3(zfill(utils.int_to_bytes(r)) + ''.join(hashes))
     self.m = m
     sig = sign(self.h, self.sk)
     broadcast(self, r, self.h, sig)
     self.lastOpenRound += 1
     self.sigs = None  # We don't have signatures for the open round yet
     return sig
Esempio n. 14
0
def construct_tree(db, nodes):
    if len(nodes) < 2:
        return nodes[0]
    remaining_nodes = []
    for i in range(0, len(nodes), 2):
        if i+1 == len(nodes):
            remaining_nodes.append(nodes[i])
            break
        new_value = b''.join([nodes[i], nodes[i+1]])
        new_sum = int_to_bytes(bytes_to_int(nodes[i+1][32:]) + bytes_to_int(nodes[i][32:])).rjust(8, b"\x00")
        new_hash = b''.join([sha3(new_value), new_sum])
        print('Left:', encode_hex(nodes[i]), 'parent:', encode_hex(new_hash))
        print('Right:', encode_hex(nodes[i+1]), 'parent:', encode_hex(new_hash))
        db.put(new_hash, new_value)
        remaining_nodes.append(new_hash)
    return construct_tree(db, remaining_nodes)
Esempio n. 15
0
def eth_sign_with_keyfile(message: bytes, raw: bool, keyfile: str, password: str):
    assert(isinstance(message, bytes))
    assert(isinstance(raw, bool))
    assert(isinstance(keyfile, str))
    assert(isinstance(password, str))

    if not raw:
        message = hexstring_to_bytes(Eth._recoveryMessageHash(data=message))

    key = eth_keyfile.decode_keyfile_json(eth_keyfile.load_keyfile(keyfile), bytes(password, 'utf-8'))
    pk = PrivateKey(key, raw=True)
    signature = pk.ecdsa_recoverable_serialize(
        pk.ecdsa_sign_recoverable(message, raw=True)
    )

    signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
    signature_hex = signature.hex()[0:128] + int_to_bytes(ord(bytes.fromhex(signature.hex()[128:130]))+27).hex()

    return '0x' + signature_hex
Esempio n. 16
0
def eth_sign(message: bytes, web3: Web3):
    assert(isinstance(message, bytes))
    assert(isinstance(web3, Web3))

    # as `EthereumTesterProvider` does not support `eth_sign`, we implement it ourselves
    if str(web3.providers[0]) == 'EthereumTesterProvider':
        key = k0
        msg = hexstring_to_bytes(Eth._recoveryMessageHash(data=message))

        pk = PrivateKey(key, raw=True)
        signature = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(msg, raw=True)
        )

        signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
        signature_hex = signature.hex()[0:128] + int_to_bytes(ord(bytes.fromhex(signature.hex()[128:130]))+27).hex()

        return '0x' + signature_hex

    return web3.manager.request_blocking(
        "eth_sign", [web3.eth.defaultAccount, encode_hex(message)],
    )
Esempio n. 17
0
def int_to_bytes(x):
    # pyethereum int to bytes does not handle negative numbers
    assert -(1<<255) <= x < (1<<255)
    return utils.int_to_bytes((1<<256) + x if x < 0 else x)
Esempio n. 18
0
    elif x_str[0] in ['2', '3']:
        bitlen -= 2
    elif x_str[0] in ['4', '5', '6', '7']:
        bitlen -= 1
    return bitlen


if __name__ == '__main__':

    key = []
    rand = []

    p = 153098272504387072266936256155440771844922582242861823323292219309209807318109992190455717597749270325963123403359939192028947724926144342818770586136136126337375436706876614423863264051678326206739626203872223116203206738831155125839612432933059096643057013804321361170650382385182136069811475540151279147259
    g = 48095861804730928538428071688224004229592704416264787635743716356958582448226167154685924895443220005707859651277553435409220536317215422963672871914841517783042349761227906722244783116777179995820326154186287286353935949308174273056377987690394866714089833749644657555907806410435558837920979345110898160449
    k = 10022446701738583271276071804010446073913280425189472942303437612418862851223244723245226017322005926246813100742541609377103046893136104044015161562561526985453585647020566093167977121428923628169372925889701872928538625011078052920813557913682354018653924330859466163743103828247525446549945542160664745508

    c_val = sha3(int_to_bytes(g) + int_to_bytes(p) + int_to_bytes(k))

    c = int.from_bytes(c_val, byteorder='big')

    print("c:", count_bitlen(c), ":", c)

    for j in range(0, 1):
        key_bytes = get_random_bytes(128)
        rand_bytes = get_random_bytes(32)
        #print("r ",j, ":", rand_bytes)
        key.append(int.from_bytes(key_bytes, byteorder='big'))
        rand.append(int.from_bytes(rand_bytes, byteorder='big'))
        print("k ", j, ":", key[j])
        print("r ", j, ":", rand[j])
class Player():
    def __init__(self, sk, i, PM, contract):
        self.sk = sk
        self.i = i
        self.PM = PM
        self.contract = contract
        self.status = "OK"
        self.lastRound = -1
        #       credL, credR, wdrawL, wdrawR, hash, expiry, amount
        self.lastCommit = None, (0, 0, 0, 0, '', 0, 0)
        self.lastProposed = None

    def deposit(self, amt):
        self.contract.deposit(value=amt, sender=self.sk)

    def acceptInputs(self, r, payL, payR, wdrawL, wdrawR, cmd):
        assert self.status == "OK"
        assert r == self.lastRound + 1
        # Assumption - don't call acceptInputs(r,...) multiple times

        depositsL = contract.deposits(0)
        depositsR = contract.deposits(1)

        _, (creditsL, creditsR, withdrawalsL, withdrawalsR, h, expiry,
            amount) = self.lastCommit

        # Code for handling conditional payments
        try:
            # Opening a new conditional payment
            if cmd[0] == 'open':
                _h, _expiry, _amount = cmd[1:]
                assert amount == 0  # No inflight payment
                assert _amount <= depositsL + creditsL  # No overpayment
                assert _expiry >= s.block.number + 10
                h = _h
                expiry = _expiry
                amount = _amount
                creditsL -= _amount  # Reserve the amount for the conditional payment
        except TypeError, IndexError:
            pass
        if cmd == 'cancel':
            # Should only be invoked with permission from R
            assert amount > 0
            creditsL += amount
            amount = 0
        if cmd == 'complete':
            # Should only be invoked with permission from L
            assert amount > 0
            creditsR += amount
            amount = 0

        assert payL <= depositsL + creditsL
        assert payR <= depositsR + creditsR
        assert wdrawL <= depositsL + creditsL - payL
        assert wdrawR <= depositsR + creditsR - payR

        creditsL += payR - payL - wdrawL
        creditsR += payL - payR - wdrawR
        withdrawalsL += wdrawL
        withdrawalsR += wdrawR

        self.lastProposed = (creditsL, creditsR, withdrawalsL, withdrawalsR, h,
                             expiry, amount)

        self.h = utils.sha3(
            zfill(utils.int_to_bytes(r)) + zfill(int_to_bytes(creditsL)) +
            zfill(int_to_bytes(creditsR)) +
            zfill(utils.int_to_bytes(withdrawalsL)) +
            zfill(utils.int_to_bytes(withdrawalsR)) + zfill(h) +
            zfill(utils.int_to_bytes(expiry)) +
            zfill(utils.int_to_bytes(amount)))
        sig = sign(self.h, self.sk)
        #broadcast(self, r, self.h, sig)
        return sig
Esempio n. 20
0
    bin = '0x608060405260a060405190810160405280608081526020017f447da3cd62f803c191a7f65e91e582a2c56002c59c6205676b561b7e43dee69d81526020017f889e8a7e4e22cb6ca321f7f0ff29005d1b7aca5f0afa26f88e6bce1d2b4503c881526020017f9ff55640b109eb0ceb6b304c8d1f0b3015d5f656a49df24aae9daeabf06085bf81526020017f3b554dc5628fc3a4b0b1d3849ae8530a415219818afadccc05e40c0c9e19b34181525060009080519060200190620000c49291906200060c565b506000600160006101000a81548160ff0219169083151502179055506103ff60025560a060405190810160405280608081526020017fbd49fe4da96732c03a350fa45cd8ea71fd30d768f08c9bfc896fb03daaf8d3fb81526020017fcf6c9c08fdd65e089ae96db1b0051e9b620a9debffabf1c7f4ce663c1e9740cd81526020017fb1654a9f09a83051a75cadf9869d34a25c7ccfac84f9cda891f0130eb7b98cdf81526020017fba3c1e7d2efcc5c3b328d770989329537c8d56b4a16921ef56594f7406caf94d81525060039080519060200190620001a69291906200060c565b506000600460006101000a81548160ff02191690831515021790555061040060055560a060405190810160405280608081526020017fda04e8c7457591a5f303377378fdf9777bc7f9bb2957458b40107605692fd8a981526020017f38e34c8cc0f63486d375ffc9f17ff170c06b1d9d4d6c40d16bc34b5f145f365981526020017f8c987c624d60c25335b258460f1dcaaa15df44e1c8dff6b556fa5283198956f481526020017f864dbca5ff6a2cb02f551a6e17c45e9efc0b540f21c36d56d6763a188459d8fb81525060069080519060200190620002889291906200060c565b506000600760006101000a81548160ff02191690831515021790555061040060085560606040519081016040528060008054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015620003505780601f10620003245761010080835404028352916020019162000350565b820191906000526020600020905b8154815290600101906020018083116200033257829003601f168201915b50505050508152602001600160009054906101000a900460ff1615158152602001600254815250600960008201518160000190805190602001906200039792919062000693565b5060208201518160010160006101000a81548160ff02191690831515021790555060408201518160020155505060606040519081016040528060038054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156200046a5780601f106200043e576101008083540402835291602001916200046a565b820191906000526020600020905b8154815290600101906020018083116200044c57829003601f168201915b50505050508152602001600460009054906101000a900460ff1615158152602001600554815250600c6000820151816000019080519060200190620004b192919062000693565b5060208201518160010160006101000a81548160ff02191690831515021790555060408201518160020155505060606040519081016040528060068054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015620005845780601f10620005585761010080835404028352916020019162000584565b820191906000526020600020905b8154815290600101906020018083116200056657829003601f168201915b50505050508152602001600760009054906101000a900460ff1615158152602001600854815250600f6000820151816000019080519060200190620005cb92919062000693565b5060208201518160010160006101000a81548160ff0219169083151502179055506040820151816002015550503480156200060557600080fd5b5062000742565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200064f57805160ff191683800117855562000680565b8280016001018555821562000680579182015b828111156200067f57825182559160200191906001019062000662565b5b5090506200068f91906200071a565b5090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620006d657805160ff191683800117855562000707565b8280016001018555821562000707579182015b8281111562000706578251825591602001919060010190620006e9565b5b5090506200071691906200071a565b5090565b6200073f91905b808211156200073b57600081600090555060010162000721565b5090565b90565b6106c080620007526000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063326cf61c1461005157806358223dc8146100fb575b600080fd5b34801561005d57600080fd5b5061008060048036038101908080356000191690602001909291905050506101f2565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100c05780820151818401526020810190506100a5565b50505050905090810190601f1680156100ed5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561010757600080fd5b5061016c600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610223565b604051808315151515815260200180602001828103825283818151815260200191508051906020019080838360005b838110156101b657808201518184015260208101905061019b565b50505050905090810190601f1680156101e35780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b6060816040516020018082600019166000191681526020019150506040516020818303038152906040529050919050565b6000606061022f610670565b610237610670565b610361600660006003604051808480546001816001161561010002031660029004801561029b5780601f1061027957610100808354040283529182019161029b565b820191906000526020600020905b815481529060010190602001808311610287575b5050838054600181600116156101000203166002900480156102f45780601f106102d25761010080835404028352918201916102f4565b820191906000526020600020905b8154815290600101906020018083116102e0575b50508280546001816001161561010002031660029004801561034d5780601f1061032b57610100808354040283529182019161034d565b820191906000526020600020905b815481529060010190602001808311610339575b5050935050505060405180910390206101f2565b826000018190525060008260200190151590811515815250508482604001818152505085816000018190525060008160200190151590811515815250508481604001818152505060006103b6838360016104b7565b1415610437577f0b2d8b0c64417145fffc6fbacdebf625b399a33101f3173dd19f63c9928ab3526040518080602001828103825260068152602001807f457175616c21000000000000000000000000000000000000000000000000000081525060200191505060405180910390a160018260000151809050935093506104ae565b7f0b2d8b0c64417145fffc6fbacdebf625b399a33101f3173dd19f63c9928ab35260405180806020018281038252600a8152602001807f4e6f7420457175616c210000000000000000000000000000000000000000000081525060200191505060405180910390a160008260000151809050935093505b50509250929050565b600080600080600080600080600196508815610589578a6020015180156104df575089602001515b1561050c577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9650610588565b600015158b60200151151514801561052c5750600115158a602001511515145b1561053a5760019750610662565b600115158b60200151151514801561055a5750600015158a602001511515145b15610587577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9750610662565b5b5b89604001518b6040015111156105a457866001029750610662565b8a604001518a6040015111156105de57867fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff029750610662565b8a6000015151915060208b5101955060208a51019450600090505b8181101561065d578086015193508085015192508284111561062057866001029750610662565b8383111561065257867fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff029750610662565b6020810190506105f9565b600097505b505050505050509392505050565b606060405190810160405280606081526020016000151581526020016000815250905600a165627a7a723058209ffcbb3cd68c629c839ed1ec686fb031e1dd48d3ed52990269ced068ae7ad6f10029'
    addr = Web3.toChecksumAddress('0xf3bA0e58C39eEf4e94144fb3a6c10374a25da663')

    web3, pwd = connect()
    contract = web3.eth.contract(abi=abi, bytecode=bin, address=addr)

    p = 153098272504387072266936256155440771844922582242861823323292219309209807318109992190455717597749270325963123403359939192028947724926144342818770586136136126337375436706876614423863264051678326206739626203872223116203206738831155125839612432933059096643057013804321361170650382385182136069811475540151279147259
    g = 48095861804730928538428071688224004229592704416264787635743716356958582448226167154685924895443220005707859651277553435409220536317215422963672871914841517783042349761227906722244783116777179995820326154186287286353935949308174273056377987690394866714089833749644657555907806410435558837920979345110898160449
    k = 10022446701738583271276071804010446073913280425189472942303437612418862851223244723245226017322005926246813100742541609377103046893136104044015161562561526985453585647020566093167977121428923628169372925889701872928538625011078052920813557913682354018653924330859466163743103828247525446549945542160664745508


    h = pow(g, k, p)

    r = 62555713279948745690349351610356531327032351353192320967421937635293378693946211592624820108119998277825391232074589514501649650827908709815124457628347900961038658650480217718807650468597580969342931489490635246791126151937259525476850522897096329798193623331012272552762850181502944812071200771862243846107

    c_val = sha3(int_to_bytes(p) + int_to_bytes(g) + int_to_bytes(h))

    c = int.from_bytes(c_val, byteorder='big')

    hash_eq = contract.functions.hash_equal(int_to_bytes(c_val), count_bitlen(c))

    hash_eq.transact()

    #print("Equal or not ", c_neg)

    print("Hash Length Solidity", count_bitlen(int.from_bytes(c_sol, byteorder='big')))

    print("Hash Length Python", count_bitlen(c))

    print("Python c : ", c_val)
Esempio n. 21
0
def sign(hash, key):
    vrs = u.ecsign(hash, key)
    rsv = vrs[1:] + vrs[:1]
    vrs_bytes = [u.encode_int32(i) for i in rsv[:2]] + [u.int_to_bytes(rsv[2])]
    return b''.join(vrs_bytes)
Esempio n. 22
0
def get_deposit_hash(owner, token, value):
    return u.sha3(owner + token + b'\x00' * 31 + u.int_to_bytes(value))
Esempio n. 23
0
def get_deposit_hash(owner, token, value):
    assert value < 256, "Bad argument"  # rewrite function to allow passing larger value
    value_bytes = u.int_to_bytes(value) if value != 0 else b'\x00'
    return u.sha3(owner + token + b'\x00' * 31 + value_bytes)
Esempio n. 24
0
def get_sum_hash_of_tx(tx):
    offset = int_to_bytes(tx['contents']['offset']).rjust(8, b"\x00")
    tx_hash = sha3(json.dumps(tx))
    return b''.join([tx_hash, offset])
Esempio n. 25
0
    web3, pwd = connect()
    contract = web3.eth.contract(abi=abi, bytecode=bin, address=addr)

    for j in range(0, num_workers):
        web3.personal.unlockAccount(web3.personal.listAccounts[3 + j], pwd)
        print("Account ", j, ":", web3.eth.accounts[3 + j])
        web3.eth.defaultAccount = web3.eth.accounts[3 + j]
        i_array = [None] * 40
        c_1_array = [None] * 40
        c_2_array = [None] * 40
        for i in range(0, 40):
            random.seed(sha3(i * j))
            randi = random.getrandbits(256)
            c_1, c_2 = enc(int(ansvec[j][i]), randi)
            i_array[i] = i
            c_1_array[i] = int_to_bytes(c_1)
            c_2_array[i] = int_to_bytes(c_2)
        submit_answers = contract.functions.submit_answers(
            i_array, c_1_array, c_2_array)
        gas = submit_answers.estimateGas()
        print(submit_answers.buildTransaction())
        tx_hash = submit_answers.transact({'gas': gas, 'gasPrice': 1000000000})
        tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash, 600)

    for j in range(0, num_workers):
        web3.personal.unlockAccount(web3.personal.listAccounts[3 + j], pwd)
        print("Account ", j, ":", web3.eth.accounts[3 + j])
        web3.eth.defaultAccount = web3.eth.accounts[3 + j]
        i_array = [None] * 33
        c_1_array = [None] * 33
        c_2_array = [None] * 33
    for j in range(1,3):
        print("Solutions of Worker ", j)
        err_counter = 0
        for i in range(0, num_gold):
            print(ansvec[j][golden_standard[i]])
            if(ansvec[j][golden_standard[i]] != golden_answers[i]):     #performing different plaintext proof if workers solution does not match with golden standard
                c_1, c_2 = ciphervec[j][golden_standard[i]]

                # Sigma protocol

                r = int.from_bytes(get_random_bytes(16), byteorder='big')
                A = c_1
                a = pow(A, r, p)
                a_bitlen = count_bitlen(a)

                c = int.from_bytes(sha3(int_to_bytes(a) + int_to_bytes(g) + int_to_bytes(h)), byteorder='big')
                c_bitlen = count_bitlen(c)

                print("c bitlen: %d" % c_bitlen)

                z = r + (c * k)
                z_bitlen = count_bitlen(z)

                web3.personal.unlockAccount(web3.personal.listAccounts[0], pwd)
                web3.eth.defaultAccount = web3.eth.accounts[0]

                diff_plaintext_proof = contract.functions.different_plaintext_proof(int_to_bytes(c_1), count_bitlen(c_1), int_to_bytes(c_2), count_bitlen(c_2), golden_standard[i], web3.eth.accounts[3+j], int_to_bytes(a), a_bitlen, int_to_bytes(z), z_bitlen, c_bitlen)

                if(diff_plaintext_proof.call()):
                    print("Different Plaintext Proof Verified for Worker number ", j, " and question number ", golden_standard[i], "!")
                else:
Esempio n. 27
0
    rand_bytes = get_random_bytes(32)
    r = int.from_bytes(rand_bytes, byteorder='big')

    A = (ca1 * cb1) % p

    print("A: ", A)

    B = (ca2 * cb2) % p

    print("B: ", B)

    a = pow(A, r, p)

    print("a: ", a)

    c_val = sha3(int_to_bytes(a) + int_to_bytes(g) + int_to_bytes(h))

    c = int.from_bytes(c_val, byteorder='big')

    print("c: ", c)

    z = r + c * k

    print("z: ", z)

    lhs = (pow(g, c, p) * pow(A, z, p)) % p

    rhs = (a * pow(B, c, p)) % p

    print("lhs: ", lhs)
    print("rhs: ", rhs)
Esempio n. 28
0
    def acceptInputs(self, r, payL, payR, wdrawL, wdrawR, cmd=None):
        assert self.status == "OK"
        assert r == self.lastRound + 1
        # Assumption - don't call acceptInputs(r,...) multiple times

        depositsL = self.contract.deposits(0)
        depositsR = self.contract.deposits(1)

        _, (creditsL, creditsR, withdrawalsL, withdrawalsR, h, expiry,
            amount) = self.lastCommit

        # Code for handling conditional payments
        try:
            # Opening a new conditional payment
            if cmd[0] == 'open':
                _h, _expiry, _amount = cmd[1:]
                assert amount == 0  # No inflight payment
                assert _amount <= depositsL + creditsL  # No overpayment
                assert _expiry >= self.chain.block.number + 10
                h = _h
                expiry = _expiry
                amount = _amount
                creditsL -= _amount  # Reserve the amount for the conditional payment
        except TypeError as IndexError:
            pass
        if cmd == 'cancel':
            # Should only be invoked with permission from R
            assert amount > 0
            creditsL += amount
            amount = 0
        if cmd == 'complete':
            # Should only be invoked with permission from L
            assert amount > 0
            creditsR += amount
            amount = 0

        assert payL <= depositsL + creditsL
        assert payR <= depositsR + creditsR
        assert wdrawL <= depositsL + creditsL - payL
        assert wdrawR <= depositsR + creditsR - payR

        creditsL += payR - payL - wdrawL
        creditsR += payL - payR - wdrawR
        withdrawalsL += wdrawL
        withdrawalsR += wdrawR

        self.lastProposed = (creditsL, creditsR, withdrawalsL, withdrawalsR, h,
                             expiry, amount)

        # pdb.set_trace()
        a = zfill(utils.int_to_bytes(r))
        b = zfill(int_to_bytes(creditsL))
        c = zfill(int_to_bytes(creditsR))
        d = zfill(utils.int_to_bytes(withdrawalsL))
        e = zfill(utils.int_to_bytes(withdrawalsR))
        f = zfill(h)
        g = zfill(utils.int_to_bytes(expiry))
        h = zfill(utils.int_to_bytes(amount))
        self.h = utils.sha3(a + b + c + d + e + f + g + h)
        sig = sign(self.h, self.sk)
        #broadcast(self, r, self.h, sig)
        return sig
Esempio n. 29
0
    print('g_bitlen: ', count_bitlen(g))
    print('k: ', hex(k))
    print('k_bitlen: ', count_bitlen(k))
    print('h: ', hex(h))
    print('h_bitlen: ', count_bitlen(h))

    c_1, c_2 = enc_zero(r)
    print('c_1: ', hex(c_1))
    print('c_1_bitlen: ', count_bitlen(c_1))
    print('c_2: ', hex(c_2))
    print('c_2_bitlen: ', count_bitlen(c_2))
    print(is_zero(c_1, c_2, k))
    print(is_one(c_1, c_2, k))

    dispute_handling = contract.functions.dispute_handling(
        int_to_bytes(c_1), count_bitlen(c_1), int_to_bytes(c_2),
        count_bitlen(c_2), int_to_bytes(k), count_bitlen(k))
    gas = dispute_handling.estimateGas()
    tx_hash = dispute_handling.transact({'gas': gas})
    print(web3.toHex(tx_hash))
    tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
    print(tx_receipt)

    c_1, c_2 = enc_one(r)
    print('c_1: ', hex(c_1))
    print('c_1_bitlen: ', count_bitlen(c_1))
    print('c_2: ', hex(c_2))
    print('c_2_bitlen: ', count_bitlen(c_2))
    print(is_zero(c_1, c_2, k))
    print(is_one(c_1, c_2, k))