コード例 #1
0
    def setup_cipher(self):
        # https://github.com/ethereum/cpp-ethereum/blob/develop/libp2p/RLPxFrameIO.cpp#L34
        assert self.responder_nonce
        assert self.initiator_nonce
        assert self.auth_init
        assert self.auth_ack
        assert self.remote_ephemeral_pubkey
        if not self.ecc.is_valid_key(self.remote_ephemeral_pubkey):
            raise InvalidKeyError('invalid remote ephemeral pubkey')

        # derive base secrets from ephemeral key agreement
        # ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk)
        ecdhe_shared_secret = self.ephemeral_ecc.get_ecdh_key(self.remote_ephemeral_pubkey)

        # shared-secret = sha3(ecdhe-shared-secret || sha3(nonce || initiator-nonce))
        shared_secret = sha3(
            ecdhe_shared_secret + sha3(self.responder_nonce + self.initiator_nonce))

        self.ecdhe_shared_secret = ecdhe_shared_secret  # FIXME DEBUG
        self.shared_secret = shared_secret   # FIXME DEBUG

        # token = sha3(shared-secret)
        self.token = sha3(shared_secret)
        self.token_by_pubkey[self.remote_pubkey] = self.token

        # aes-secret = sha3(ecdhe-shared-secret || shared-secret)
        self.aes_secret = sha3(ecdhe_shared_secret + shared_secret)

        # mac-secret = sha3(ecdhe-shared-secret || aes-secret)
        self.mac_secret = sha3(ecdhe_shared_secret + self.aes_secret)

        # setup sha3 instances for the MACs
        # egress-mac = sha3.update(mac-secret ^ recipient-nonce || auth-sent-init)
        mac1 = sha3_256(sxor(self.mac_secret, self.responder_nonce) + self.auth_init)
        # ingress-mac = sha3.update(mac-secret ^ initiator-nonce || auth-recvd-ack)
        mac2 = sha3_256(sxor(self.mac_secret, self.initiator_nonce) + self.auth_ack)

        if self.is_initiator:
            self.egress_mac, self.ingress_mac = mac1, mac2
        else:
            self.egress_mac, self.ingress_mac = mac2, mac1

        ciphername = 'aes-256-ctr'
        iv = "\x00" * 16
        assert len(iv) == 16
        self.aes_enc = pyelliptic.Cipher(self.aes_secret, iv, 1, ciphername=ciphername)
        self.aes_dec = pyelliptic.Cipher(self.aes_secret, iv, 0, ciphername=ciphername)
        self.mac_enc = AES.AESCipher(self.mac_secret, AES.MODE_ECB).encrypt

        self.is_ready = True
コード例 #2
0
def get_prefixes(fullname, funcs):
    names_to_sigs = {}
    for func in funcs:
        sig_start = func['name'].find('(')
        names_to_sigs[func['name'][:sig_start]] = func['name'][sig_start:]
    
    check_next_line = False
    prefixes = []
    for line in open(fullname):
        if line.startswith('def set'):
            name_start = line.find(' ') + 1
            name_end = line.find('(')
            name = line[name_start:name_end]
            sig = names_to_sigs[name]
        elif line.startswith('#whitelisted'):
            check_next_line = True
            continue
        elif check_next_line and line.startswith('def'):
            name_start = line.find(' ') + 1
            name_end = line.find('(')
            name = line[name_start:name_end]
            sig = names_to_sigs[name]
        else:
            continue
        prefix = sha3.sha3_256((name + sig).encode('ascii')).hexdigest()[:8]
        prefixes.append('0x' + prefix)

    prefixes.sort()
    prefix_init_code = []
    prefix_init_code.append('prefixes = array({})'.format(len(prefixes)))
    for i, prefix in enumerate(prefixes):
        item = 'prefixes[{i}] = {prefix}'.format(i=i, prefix=prefix)
        prefix_init_code.append(item)
    return '\n'.join(prefix_init_code)
def test_submitting_initial_answer(deploy_client, deploy_broker_contract,
                                   deployed_contracts, get_log_data,
                                   deploy_coinbase, contracts, denoms,
                                   StatusEnum):
    factory = deployed_contracts.BuildByteArrayFactory
    broker = deploy_broker_contract(factory._meta.address)

    expected = "\x01\x02\x03\x04\x05\x06\x07"

    request_txn_hash = broker.requestExecution("abcdefg", value=10 * denoms.ether)
    request_txn_receipt = deploy_client.wait_for_transaction(request_txn_hash)

    request_event_data = get_log_data(broker.Created, request_txn_hash)

    _id = request_event_data['id']

    assert broker.getRequest(_id)[5] == StatusEnum.Pending

    deposit_amount = broker.getRequiredDeposit("abcdefg")

    assert deposit_amount > 0

    answer_txn_hash = broker.answerRequest(_id, expected, value=deposit_amount)
    answer_txn_receipt = deploy_client.wait_for_transaction(answer_txn_hash)

    assert broker.getRequest(_id)[5] == StatusEnum.WaitingForResolution

    answer_data = broker.getInitialAnswer(_id)

    assert answer_data[0] == sha3.sha3_256(expected).digest()
    assert answer_data[1] == deploy_coinbase
    assert answer_data[2] == int(answer_txn_receipt['blockNumber'], 16)
    assert answer_data[3] is False
コード例 #4
0
def hash_string():
    string = input("Please Enter Your String: \n")

    # SHA-1 Hash
    hash_objectsha1 = hashlib.sha1(string.encode())
    String_SHA1 = hash_objectsha1.hexdigest()

    # SHA-256 Hash
    hash_objectsha2 = hashlib.sha256(string.encode())
    String_SHA256 = hash_objectsha2.hexdigest()

    # SHA-512 Hash
    hash_objectsha5 = hashlib.sha512(string.encode())
    String_SHA512 = hash_objectsha5.hexdigest()

    # SHA-3 256 Hash
    hash_objectsha3256 = sha3.sha3_256(string.encode())
    String_SHA3256 = hash_objectsha3256.hexdigest()

    # SHA-3 512 Hash
    hash_objectsha3512 = sha3.sha3_512(string.encode())
    String_SHA3512 = hash_objectsha3512.hexdigest()

    print("Your SHA-1 Hash is ", String_SHA1)
    print("\n")
    print("Your SHA-256 Hash is ", String_SHA256)
    print("\n")
    print("Your SHA-512 Hash is ", String_SHA512)
    print("\n")
    print("Your SHA-3 256 Hash is ", String_SHA3256)
    print("\n")
    print("Your SHA-3 512 Hash is ", String_SHA3512)
    print("\n")

    return
コード例 #5
0
ファイル: testrpc.py プロジェクト: 4gn3s/eth-testrpc
def web3_sha3(value, encoding='hex'):
    logger.info('web3_sha3')
    if encoding == 'hex':
        value = decode_hex(value)
    else:
        value = force_bytes(value)
    return encode_32bytes(sha3_256(value).digest())
コード例 #6
0
def get_prefixes(fullname, funcs):
    names_to_sigs = {}
    for func in funcs:
        sig_start = func["name"].find("(")
        names_to_sigs[func["name"][:sig_start]] = func["name"][sig_start:]

    check_next_line = False
    prefixes = []
    for line in open(fullname):
        if line.startswith("def set"):
            name_start = line.find(" ") + 1
            name_end = line.find("(")
            name = line[name_start:name_end]
            sig = names_to_sigs[name]
        elif line.startswith("#whitelisted"):
            check_next_line = True
            continue
        elif check_next_line and line.startswith("def"):
            name_start = line.find(" ") + 1
            name_end = line.find("(")
            name = line[name_start:name_end]
            sig = names_to_sigs[name]
        else:
            continue
        prefix = sha3.sha3_256((name + sig).encode("ascii")).hexdigest()[:8]
        prefixes.append("0x" + prefix)

    prefixes.sort()
    prefix_init_code = []
    prefix_init_code.append("prefixes = array({})".format(len(prefixes)))
    for i, prefix in enumerate(prefixes):
        item = "prefixes[{i}] = {prefix}".format(i=i, prefix=prefix)
        prefix_init_code.append(item)
    return "\n".join(prefix_init_code)
def test_challenging_answer(deploy_client, deploy_broker_contract,
                            deployed_contracts, get_log_data,
                            deploy_coinbase, contracts, StatusEnum, denoms):
    factory = deployed_contracts.BuildByteArrayFactory
    broker = deploy_broker_contract(factory._meta.address)

    expected = "\x01\x02\x03\x04\x05\x06\x07"

    request_txn_hash = broker.requestExecution("abcdefg", value=10 * denoms.ether)
    request_txn_receipt = deploy_client.wait_for_transaction(request_txn_hash)

    request_event_data = get_log_data(broker.Created, request_txn_hash)

    _id = request_event_data['id']

    assert broker.getRequest(_id)[5] == StatusEnum.Pending

    deposit_amount = broker.getRequiredDeposit("abcdefg")

    assert deposit_amount > 0

    i_answer_txn_hash = broker.answerRequest(_id, "wrong", value=deposit_amount)
    i_answer_txn_receipt = deploy_client.wait_for_transaction(i_answer_txn_hash)

    assert broker.getRequest(_id)[5] == StatusEnum.WaitingForResolution

    i_answer_data = set(broker.getInitialAnswer(_id))

    assert deploy_coinbase in i_answer_data
    assert sha3.sha3_256("wrong").digest() in i_answer_data
    assert int(i_answer_txn_receipt['blockNumber'], 16) in i_answer_data
    assert broker.getInitialAnswerResult(_id) == "wrong"

    with pytest.raises(TransactionFailed):
        broker.challengeAnswer(_id, expected, value=deposit_amount - 1)
コード例 #8
0
ファイル: transaction.py プロジェクト: cgwyx/bigchaindb
    def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
        """Signs a Ed25519Fulfillment.

            Args:
                input_ (:class:`~bigchaindb.common.transaction.
                    Input`) The input to be signed.
                message (str): The message to be signed
                key_pairs (dict): The keys to sign the Transaction with.
        """
        # NOTE: To eliminate the dangers of accidentally signing a condition by
        #       reference, we remove the reference of input_ here
        #       intentionally. If the user of this class knows how to use it,
        #       this should never happen, but then again, never say never.
        input_ = deepcopy(input_)
        public_key = input_.owners_before[0]
        message = sha3_256(message.encode())
        if input_.fulfills:
            message.update('{}{}'.format(
                input_.fulfills.txid, input_.fulfills.output).encode())

        try:
            # cryptoconditions makes no assumptions of the encoding of the
            # message to sign or verify. It only accepts bytestrings
            input_.fulfillment.sign(
                message.digest(), base58.b58decode(key_pairs[public_key].encode()))
        except KeyError:
            raise KeypairMismatchException('Public key {} is not a pair to '
                                           'any of the private keys'
                                           .format(public_key))
        return input_
コード例 #9
0
 def calc_max(self):
     if self.max is None:
         r = []
         r.append(struct.pack("<i", self.nVersion))
         r.append(ser_uint256(self.hashPrevBlock))
         r.append(ser_uint256(self.hashMerkleRoot))
         r.append(struct.pack("<I", self.nTime))
         r.append(struct.pack("<I", self.nBits))
         r.append(struct.pack("<I", self.nNonce))
         self.max = uint256_from_str(sha3_256(''.join(r)).digest())
     return self.max
コード例 #10
0
ファイル: bruteforcer.py プロジェクト: ddworken/sha3Game
def findLowestHash(blockHash):
    start = random.randrange(0,999999999999999999999999999999999999999999999999999999999999999999999999999999999)       #big random range making it so multi-threading is easy. 
    lowest = (-1,999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999L)       #just a big number
    try:
        while True:
            hashInt = int(sha3.sha3_256(blockHash + str(start)).hexdigest(), 16)
            if hashInt < lowest[1]:
                lowest = (start, hashInt)
    except:
        print "anceled Search. Search results are: "
        return (str(lowest[0]), str(lowest[1]))
コード例 #11
0
ファイル: crypto.py プロジェクト: XertroV/web3.py
def sha3(value, encoding=None):
    from .formatting import (
        remove_0x_prefix,
    )
    from .string import (
        force_bytes,
    )

    if encoding:
        value = codecs.decode(remove_0x_prefix(value), encoding)

    return sha3_256(force_bytes(value)).hexdigest()
コード例 #12
0
ファイル: make_api.py プロジェクト: wintermooch/augur-core
def update_contract_events_api(contract_name, fullsig):
    api = {}
    for evt in fullsig:
        if evt["type"] == "event":
            split_name = evt["name"].split("(")
            api[split_name[0]] = {
                "inputs": evt["inputs"],
                "name": evt["name"],
                "signature": "0x" + sha3.sha3_256(evt["name"].encode("ascii")).hexdigest(),
                "contract": contract_name
            }
    return api
コード例 #13
0
def SHA3_256_hash_file(filename):
   # make a hash object
   h = sha3.sha3_256()
   # open file for reading in binary mode
   with open(filename,'rb') as file:
       # loop till the end of the file
       chunk = 0
       while chunk != b'':
           # read only 1024 bytes at a time
           chunk = file.read(1024)
           h.update(chunk)
   # return the hex representation of digest
   return h.hexdigest()
コード例 #14
0
ファイル: ethpow.py プロジェクト: Feretrius/pyethereum
def get_cache(block_number):
    while len(cache_seeds) <= block_number // EPOCH_LENGTH:
        cache_seeds.append(sha3.sha3_256(cache_seeds[-1]).digest())
    seed = cache_seeds[block_number // EPOCH_LENGTH]
    if seed in cache_by_seed:
        c = cache_by_seed.pop(seed)  # pop and append at end
        cache_by_seed[seed] = c
        return c
    c = mkcache(block_number)
    cache_by_seed[seed] = c
    if len(cache_by_seed) > cache_by_seed.max_items:
        cache_by_seed.pop(cache_by_seed.keys()[0])  # remove last recently accessed
    return c
コード例 #15
0
    def calculate_contract_address(self, tx=None, from_nonce_tuple=None):
        if tx:
            from_address = tx["from"]
            nonce = tx["nonce"]
        elif from_nonce_tuple:
            from_address = from_nonce_tuple[0]
            nonce = from_nonce_tuple[1]

        return "0x" + sha3.sha3_256(
            rlp.encode([
                binascii.unhexlify(from_address[2:]),
                nonce
            ])
        ).hexdigest()[-40:]
コード例 #16
0
def process_fullsig(fullsig):
    '''Transforms a signature to help with type checking

The full signature of a contract looks something like:
[{"type":"function",
  "name":"foo(int256)",
  ... ,
 }]

The Contract class uses the type information in the signature,
so that my_contract.foo(1) will work, but my_contract.foo('bar')
will not. After the transformation, the signature looks like this:

{"foo":[("4c970b2f",      # prefix
         ((int, long),),  # types
         "foo(int256)")]} # full name

A contract might have multiple functions with the same name, but
different input types, so the result dictionary maps a name to a list
of info for each function with that name.
'''
    names_to_info = {}
    for item in filter(lambda i: i['type']=='function', fullsig):
        sig_start = item['name'].find('(')
        if sig_start == -1:
            raise ValueError('Bad function name in fullsig: {}'.format(item['name']))

        name = item['name'][:sig_start]
        if name not in names_to_info:
            names_to_info[name] = []

        prefix = sha3.sha3_256(item['name'].encode('ascii')).hexdigest()[:8]
        if item['name'][sig_start + 1] == ')': #empty sig
            names_to_info[name].append((prefix, (), item['name']))
        else:
            sig = item['name'][sig_start + 1:-1].split(',')
            pysig = []
            for t in sig:
                if '[]' in t:
                    pysig.append(list)
                elif t.startswith('bytes') or t.startswith('string') or t=='address':
                    pysig.append(str)
                elif 'int' in t:
                    pysig.append(INT)
                else:
                    raise TypeError('unsupported type in fullsig: {}'.format(t))
            names_to_info[name].append((prefix, tuple(pysig), item['name']))
    return names_to_info
コード例 #17
0
ファイル: transaction.py プロジェクト: cgwyx/bigchaindb
    def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs):
        """Signs a ThresholdSha256.

            Args:
                input_ (:class:`~bigchaindb.common.transaction.
                    Input`) The Input to be signed.
                message (str): The message to be signed
                key_pairs (dict): The keys to sign the Transaction with.
        """
        input_ = deepcopy(input_)
        message = sha3_256(message.encode())
        if input_.fulfills:
            message.update('{}{}'.format(
                input_.fulfills.txid, input_.fulfills.output).encode())

        for owner_before in set(input_.owners_before):
            # TODO: CC should throw a KeypairMismatchException, instead of
            #       our manual mapping here

            # TODO FOR CC: Naming wise this is not so smart,
            #              `get_subcondition` in fact doesn't return a
            #              condition but a fulfillment

            # TODO FOR CC: `get_subcondition` is singular. One would not
            #              expect to get a list back.
            ccffill = input_.fulfillment
            subffills = ccffill.get_subcondition_from_vk(
                base58.b58decode(owner_before))
            if not subffills:
                raise KeypairMismatchException('Public key {} cannot be found '
                                               'in the fulfillment'
                                               .format(owner_before))
            try:
                private_key = key_pairs[owner_before]
            except KeyError:
                raise KeypairMismatchException('Public key {} is not a pair '
                                               'to any of the private keys'
                                               .format(owner_before))

            # cryptoconditions makes no assumptions of the encoding of the
            # message to sign or verify. It only accepts bytestrings
            for subffill in subffills:
                subffill.sign(
                    message.digest(), base58.b58decode(private_key.encode()))
        return input_
コード例 #18
0
def address_to_pubkeyhash(addr):
    try:
        addr = b58decode(addr, 25)
    except:
        return None

    if addr is None:
        return None

    ver = addr[0]
    cksumA = addr[-4:]
    #TODO: We should clean this up so that it works with not Keccek implementations too.
    cksumB = sha3.sha3_256(addr[:-4]).digest()[:4]

    if cksumA != cksumB:
        return None

    return (ver, addr[1:-4])
コード例 #19
0
ファイル: transaction.py プロジェクト: cgwyx/bigchaindb
    def _input_valid(input_, operation, message, output_condition_uri=None):
        """Validates a single Input against a single Output.

            Note:
                In case of a `CREATE` or `GENESIS` Transaction, this method
                does not validate against `output_condition_uri`.

            Args:
                input_ (:class:`~bigchaindb.common.transaction.
                    Input`) The Input to be signed.
                operation (str): The type of Transaction.
                message (str): The fulfillment message.
                output_condition_uri (str, optional): An Output to check the
                    Input against.

            Returns:
                bool: If the Input is valid.
        """
        ccffill = input_.fulfillment
        try:
            parsed_ffill = Fulfillment.from_uri(ccffill.serialize_uri())
        except (TypeError, ValueError,
                ParsingError, ASN1DecodeError, ASN1EncodeError):
            return False

        if operation in (Transaction.CREATE, Transaction.GENESIS):
            # NOTE: In the case of a `CREATE` or `GENESIS` transaction, the
            #       output is always valid.
            output_valid = True
        else:
            output_valid = output_condition_uri == ccffill.condition_uri

        message = sha3_256(message.encode())
        if input_.fulfills:
            message.update('{}{}'.format(
                input_.fulfills.txid, input_.fulfills.output).encode())

        # NOTE: We pass a timestamp to `.validate`, as in case of a timeout
        #       condition we'll have to validate against it

        # cryptoconditions makes no assumptions of the encoding of the
        # message to sign or verify. It only accepts bytestrings
        ffill_valid = parsed_ffill.validate(message=message.digest())
        return output_valid and ffill_valid
コード例 #20
0
def test_compile_imports():
    make_tree(test_code)
    node = start_test_node()

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

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

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

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

    r1 = int(r1, 16)
    if r1 > 2**255:
        r1 -= 2**256
    r2 = bar(1 << 65)
    if r1 == r2:
        print 'TEST PASSED'
    else:
        print 'TEST FAILED: <r1 {}> <r2 {}>'.format(r1, r2)
    rm_tree(test_code)
    node.send_signal(signal.SIGINT)
    node.wait()
コード例 #21
0
def test_post_create_transaction_with_invalid_schema(mock_logger, client):
    from bigchaindb.models import Transaction
    user_priv, user_pub = crypto.generate_key_pair()
    tx = Transaction.create([user_pub], [([user_pub], 1)]).to_dict()
    del tx['version']
    ed25519 = Ed25519Sha256(public_key=base58.b58decode(user_pub))
    message = json.dumps(
        tx,
        sort_keys=True,
        separators=(',', ':'),
        ensure_ascii=False,
    ).encode()
    ed25519.sign(message, base58.b58decode(user_priv))
    tx['inputs'][0]['fulfillment'] = ed25519.serialize_uri()
    tx['id'] = sha3_256(
        json.dumps(
            tx,
            sort_keys=True,
            separators=(',', ':'),
            ensure_ascii=False,
        ).encode(),
    ).hexdigest()
    res = client.post(TX_ENDPOINT, data=json.dumps(tx))
    expected_status_code = 400
    expected_error_message = (
        "Invalid transaction schema: 'version' is a required property")
    assert res.status_code == expected_status_code
    assert res.json['message'] == expected_error_message
    assert mock_logger.error.called
    assert (
        'HTTP API error: %(status)s - %(method)s:%(path)s - %(message)s' in
        mock_logger.error.call_args[0]
    )
    assert (
        {
            'message': expected_error_message, 'status': expected_status_code,
            'method': 'POST', 'path': TX_ENDPOINT
        } in mock_logger.error.call_args[0]
    )
def test_creating_request_for_execution(deploy_client, deploy_broker_contract,
                                        deployed_contracts, get_log_data,
                                        deploy_coinbase, StatusEnum, denoms):
    broker = deploy_broker_contract(deployed_contracts.BuildByteArrayFactory._meta.address)

    request_txn_hash = broker.requestExecution("abcdefg", value=10 * denoms.ether)
    request_txn_receipt = deploy_client.wait_for_transaction(request_txn_hash)

    event_data = get_log_data(broker.Created, request_txn_hash)

    _id = event_data['id']

    req_data = broker.getRequest(_id)

    assert req_data[0] == sha3.sha3_256("abcdefg").digest()
    assert req_data[1] == "\x00" * 32
    assert req_data[2] == deploy_coinbase
    assert req_data[3] == "0x0000000000000000000000000000000000000000"
    assert req_data[4] == int(request_txn_receipt['blockNumber'], 16)
    assert req_data[5] == StatusEnum.Pending
    assert req_data[6] == 10 * denoms.ether
    assert req_data[7] == broker.getDefaultSoftResolutionBlocks()
コード例 #23
0
ファイル: util.py プロジェクト: AKIo0O/stratum-mining-keccak
def address_to_pubkeyhash(addr):
    try:
        addr = b58decode(addr, 25)
    except:
        return None

    if addr is None:
        return None

    ver = addr[0]
    cksumA = addr[-4:]
    if settings.COINDAEMON_ALGO != 'max':
        cksumB = doublesha(addr[:-4])[:4]
        #TODO: We should clean this up so that it works with not Keccek implementations too.
    else:
        cksumB = sha3_256(addr[:-4]).digest()[:4]
    

    if cksumA != cksumB:
        return None

    return (ver, addr[1:-4])
コード例 #24
0
def test_post_create_transaction_with_invalid_signature(mock_logger,
                                                        b,
                                                        client):
    from bigchaindb.common.exceptions import InvalidSignature
    from bigchaindb.models import Transaction
    user_priv, user_pub = crypto.generate_key_pair()

    tx = Transaction.create([user_pub], [([user_pub], 1)]).to_dict()
    tx['inputs'][0]['fulfillment'] = 64 * '0'
    tx['id'] = sha3_256(
        json.dumps(
            tx,
            sort_keys=True,
            separators=(',', ':'),
            ensure_ascii=False,
        ).encode(),
    ).hexdigest()

    res = client.post(TX_ENDPOINT, data=json.dumps(tx))
    expected_status_code = 400
    expected_error_message = (
        'Invalid transaction ({}): Fulfillment URI '
        'couldn\'t been parsed'
    ).format(InvalidSignature.__name__)
    assert res.status_code == expected_status_code
    assert res.json['message'] == expected_error_message
    assert mock_logger.error.called
    assert (
        'HTTP API error: %(status)s - %(method)s:%(path)s - %(message)s' in
        mock_logger.error.call_args[0]
    )
    assert (
        {
            'message': expected_error_message, 'status': expected_status_code,
            'method': 'POST', 'path': TX_ENDPOINT
        } in mock_logger.error.call_args[0]
    )
コード例 #25
0
#!/usr/bin/python3

###############################################################################
# Pulish by LibraOne, created by the NodePacific is the member of LibraOne
#
# Copyright 2019 The NodePacific Authors. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

from mnemonic import Mnemonic
from sha3 import sha3_256

MNEMONIC = Mnemonic("english")
words = MNEMONIC.generate(128)
shazer = sha3_256()
shazer.update(MNEMONIC.to_entropy(words))
print(shazer.digest().hex())
コード例 #26
0
ファイル: account.py プロジェクト: vdt/pylibra
 def __init__(self, private_key):
     self._signing_key = SigningKey(bytes.fromhex(private_key))
     self._verify_key = self._signing_key.verify_key
     shazer = sha3_256()
     shazer.update(self._verify_key.encode())
     self.address = shazer.digest().hex()
def make_4byte_signature(text_signature):
    return sha3_256(force_bytes(text_signature)).digest()[:4]
コード例 #28
0
def call(a_address, b_address, a_ai, b_ai, start_gas):
    a_fuel = start_gas / 2
    b_fuel = start_gas / 2

    # setup grid
    ncells = cols * rows
    a_grid = [0] * ncells
    b_grid = [0] * ncells

    # redistribution grid
    seed = id(a_address)  # prevhash
    seed = sha3.sha3_256(str(seed)).digest()
    redistribution_grid = mk_redistribution_grid(seed, ncells)

    # place a, b
    pos = ord(seed[0]) % (ncells / 2)
    a_grid[pos] = a_fuel
    b_grid[-pos - 1] = b_fuel

    def is_neighbour(a, b):
        return b in get_neighbours(a, cols, rows)

    def validate_move(grid, from_cell, to_cell, fuel):
        # check within grid
        if from_cell < ncells:
            if to_cell < ncells:
                # enough fuel there
                if fuel <= grid[from_cell]:
                    # check neighbour
                    if is_neighbour(from_cell, to_cell):
                        return True
        return False

    def total():
        return sum(a_grid + b_grid)

    sim_step_gas = 0
    sim_steps = 0
    total_gas_used = 0

    # end if one ran out of gas or half of start_gas is used
    while a_fuel > 0 and b_fuel > 0 and total() > start_gas / 2:
        if debug_callback:
            debug_callback(sim_steps, cols, rows, a_grid, b_grid,
                           redistribution_grid)

        total_at_start = total()
        redistribution = 0

        for ai, grid, other_grid, fuel in ((a_ai, a_grid, b_grid, a_fuel), (
                b_ai, b_grid, a_grid[:], b_fuel)):  # copy a_grid for 2nd call
            gas_used, move_from, move_to, move_amount = ai(
                seed, cols, rows, grid, other_grid)

            total_gas_used += gas_used
            if move_amount and not validate_move(grid, move_from, move_to,
                                                 move_amount):
                move_amount = 0

            # move
            if move_amount:
                grid[move_from] = grid[move_from] - move_amount
                grid[move_to] = grid[move_to] + move_amount

            # remove gas and redistribution
            for i in range(ncells):
                cell_fuel = grid[i]
                redistribution_allowance = cell_fuel / inv_redistribution_factor
                gas_allowance = (sim_step_gas / 2 +
                                 gas_used) * cell_fuel / fuel
                grid[i] = max(
                    0, cell_fuel - gas_allowance - redistribution_allowance)
                redistribution = redistribution + redistribution_allowance

        # handle collisions
        for i in range(ncells):
            if a_grid[i] and b_grid[i]:
                if a_grid[i] > b_grid[i]:
                    g, l = a_grid, b_grid
                else:
                    l, g = a_grid, b_grid
                d = g[i] - l[i]
                g[i] -= d
                l[i] = 0
                redistribution += d

        a_fuel = 0
        b_fuel = 0

        rnorm = sum(r for i, r in enumerate(redistribution_grid)
                    if a_grid[i] or b_grid[i])

        for i in range(ncells):
            add = redistribution * redistribution_grid[i] / rnorm
            if a_grid[i]:
                a_grid[i] += add
            if b_grid[i]:
                b_grid[i] += add
            a_fuel += a_grid[i]
            b_fuel += b_grid[i]

        assert total_at_start > total()

        sim_step_gas = 3000  # guess
        total_gas_used += sim_step_gas
        sim_steps += 1

    # end while loop
    winner = a_address if a_fuel > b_fuel else b_address
    return total_gas_used, winner
コード例 #29
0
ファイル: hash_chain.py プロジェクト: nanigasi-san/nanigasi
def calc_hash(value):
    return sha3.sha3_256(value.encode("utf-8")).hexdigest()
コード例 #30
0
 def get_account(self, counter):
     shazer = sha3_256()
     shazer.update(self.entropy)
     shazer.update(counter.to_bytes(32, "big"))
     return Account(shazer.digest().hex())
コード例 #31
0
    def start(startpoint, endpoint):
        for x in range(startpoint, endpoint, 10):
            command = eth_check.com(x)
            command2 = '{:064x}'.format(x + 1)
            command3 = eth_check.com(x + 2)
            command4 = eth_check.com(x + 4)
            command5 = eth_check.com(x + 5)
            command6 = eth_check.com(x + 6)
            command7 = eth_check.com(x + 7)
            command8 = eth_check.com(x + 8)
            command9 = eth_check.com(x + 9)
            command10 = eth_check.com(x + 10)
            private = binascii.unhexlify(command)
            private2 = binascii.unhexlify(command2)
            private3 = binascii.unhexlify(command3)
            private4 = binascii.unhexlify(command3)
            private5 = binascii.unhexlify(command3)
            private6 = binascii.unhexlify(command3)
            private7 = binascii.unhexlify(command3)
            private8 = binascii.unhexlify(command3)
            private9 = binascii.unhexlify(command3)
            private10 = binascii.unhexlify(command3)
            keccak = sha3.sha3_256()
            keccak2 = sha3.sha3_256()
            keccak3 = sha3.keccak_256()
            keccak4 = sha3.keccak_256()
            keccak5 = sha3.keccak_256()
            keccak6 = sha3.keccak_256()
            keccak7 = sha3.keccak_256()
            keccak8 = sha3.keccak_256()
            keccak9 = sha3.keccak_256()
            keccak10 = sha3.keccak_256()

            keccak.update(
                SigningKey.from_string(
                    private, curve=SECP256k1).get_verifying_key().to_string())
            keccak2.update(
                SigningKey.from_string(
                    private2, curve=SECP256k1).get_verifying_key().to_string())
            keccak3.update(
                SigningKey.from_string(
                    private3, curve=SECP256k1).get_verifying_key().to_string())
            keccak4.update(
                SigningKey.from_string(
                    private4, curve=SECP256k1).get_verifying_key().to_string())
            keccak5.update(
                SigningKey.from_string(
                    private5, curve=SECP256k1).get_verifying_key().to_string())
            keccak6.update(
                SigningKey.from_string(
                    private6, curve=SECP256k1).get_verifying_key().to_string())
            keccak7.update(
                SigningKey.from_string(
                    private7, curve=SECP256k1).get_verifying_key().to_string())
            keccak8.update(
                SigningKey.from_string(
                    private8, curve=SECP256k1).get_verifying_key().to_string())
            keccak9.update(
                SigningKey.from_string(
                    private9, curve=SECP256k1).get_verifying_key().to_string())
            keccak10.update(
                SigningKey.from_string(
                    private10,
                    curve=SECP256k1).get_verifying_key().to_string())

            address = "0x{0}".format(keccak.hexdigest()[24:])
            address2 = "0x{0}".format(keccak2.hexdigest()[24:])
            address3 = "0x{0}".format(keccak3.hexdigest()[24:])
            address4 = "0x{0}".format(keccak4.hexdigest()[24:])
            address5 = "0x{0}".format(keccak5.hexdigest()[24:])
            address6 = "0x{0}".format(keccak6.hexdigest()[24:])
            address7 = "0x{0}".format(keccak7.hexdigest()[24:])
            address8 = "0x{0}".format(keccak8.hexdigest()[24:])
            address9 = "0x{0}".format(keccak9.hexdigest()[24:])
            address10 = "0x{0}".format(keccak10.hexdigest()[24:])

            value = eth_check.get_balance(
                eth_check.build_url(address, address2, address3, address4,
                                    address5, address6, address7, address8,
                                    address9, address10))
            if float(value) == -1:
                x = x - 1
            if float(value) > 10000000000:
                eth_check.save_eth_address(x, command, address, value)
                eth_check.save_eth_address(x + 1, command2, address2, value)
                eth_check.save_eth_address(x + 2, command3, address2, value)
                eth_check.save_eth_address(x + 4, command4, address, value)
                eth_check.save_eth_address(x + 5, command5, address2, value)
                eth_check.save_eth_address(x + 6, command6, address2, value)
                eth_check.save_eth_address(x + 7, command7, address, value)
                eth_check.save_eth_address(x + 8, command8, address2, value)
                eth_check.save_eth_address(x + 9, command9, address2, value)
                eth_check.save_eth_address(x + 10, command10, address, value)
                print("==========================================")
                print("PV:", command)
                print("PV:", command2)
                print("PV:", command3)
                print("PV:", command4)
                print("PV:", command5)
                print("PV:", command6)
                print("PV:", command7)
                print("PV:", command8)
                print("PV:", command9)
                print("PV:", command10)
                print("CHECK THE VALL")
                print("==========================================")
            else:
                print(command, "CHECKED")
                print(command2, "CHECKED")
                print(command3, "CHECKED")
                print(command4, "CHECKED")
                print(command5, "CHECKED")
                print(command6, "CHECKED")
                print(command7, "CHECKED")
                print(command8, "CHECKED")
                print(command9, "CHECKED")
                print(command10, "CHECKED")
コード例 #32
0
    'metadata': None,
    'outputs': (output, ),
    'inputs': (input_, ),
    'version': version,
    'id': None,
}

# JSON: serialize the transaction-without-id to a json formatted string
message = json.dumps(
    token_creation_tx,
    sort_keys=True,
    separators=(',', ':'),
    ensure_ascii=False,
)

message = sha3.sha3_256(message.encode())

# CRYPTO-CONDITIONS: sign the serialized transaction-without-id
ed25519.sign(message.digest(), base58.b58decode(producer.private_key))

# CRYPTO-CONDITIONS: generate the fulfillment uri
fulfillment_uri = ed25519.serialize_uri()

# add the fulfillment uri (signature)
token_creation_tx['inputs'][0]['fulfillment'] = fulfillment_uri

print("\nTransaction to be submitted")
print(json.dumps(token_creation_tx, indent=2))

# JSON: serialize the id-less transaction to a json formatted string
json_str_tx = json.dumps(
コード例 #33
0
    def submit_share(self, job_id, worker_name, session, extranonce1_bin, extranonce2, ntime, nonce,
                     difficulty):
        '''Check parameters and finalize block template. If it leads
           to valid block candidate, asynchronously submits the block
           back to the bitcoin network.

            - extranonce1_bin is binary. No checks performed, it should be from session data
            - job_id, extranonce2, ntime, nonce - in hex form sent by the client
            - difficulty - decimal number from session, again no checks performed
            - submitblock_callback - reference to method which receive result of submitblock()
        '''

        # Check if extranonce2 looks correctly. extranonce2 is in hex form...
        if len(extranonce2) != self.extranonce2_size * 2:
            raise SubmitException("Incorrect size of extranonce2. Expected %d chars" % (self.extranonce2_size*2))

        # Check for job
        job = self.get_job(job_id)
        if job == None:
            raise SubmitException("Job '%s' not found" % job_id)

        # Check if ntime looks correct
        if len(ntime) != 8:
            raise SubmitException("Incorrect size of ntime. Expected 8 chars")

        if not job.check_ntime(int(ntime, 16)):
            raise SubmitException("Ntime out of range")

        # Check nonce
        if len(nonce) != 8:
            raise SubmitException("Incorrect size of nonce. Expected 8 chars")

        # Check for duplicated submit
        if not job.register_submit(extranonce1_bin, extranonce2, ntime, nonce):
            log.info("Duplicate from %s, (%s %s %s %s)" % \
                    (worker_name, binascii.hexlify(extranonce1_bin), extranonce2, ntime, nonce))
            raise SubmitException("Duplicate share")

        # Now let's do the hard work!
        # ---------------------------

        # 0. Some sugar
        extranonce2_bin = binascii.unhexlify(extranonce2)
        ntime_bin = binascii.unhexlify(ntime)
        nonce_bin = binascii.unhexlify(nonce)

        # 1. Build coinbase
        coinbase_bin = job.serialize_coinbase(extranonce1_bin, extranonce2_bin)
        if settings.COINDAEMON_ALGO == 'max':
             coinbase_hash = sha256(coinbase_bin).digest()
        else:
             coinbase_hash = util.doublesha(coinbase_bin)

        # 2. Calculate merkle root
        merkle_root_bin = job.merkletree.withFirst(coinbase_hash)
        merkle_root_int = util.uint256_from_str(merkle_root_bin)

        # 3. Serialize header with given merkle, ntime and nonce
        header_bin = job.serialize_header(merkle_root_int, ntime_bin, nonce_bin)

        # 4. Reverse header and compare it with target of the user
        if settings.COINDAEMON_ALGO == 'scrypt':
            hash_bin = ltc_scrypt.getPoWHash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
        elif settings.COINDAEMON_ALGO  == 'scrypt-jane':
            hash_bin = yac_scrypt.getPoWHash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]), int(ntime, 16))
        elif settings.COINDAEMON_ALGO == 'quark':
            hash_bin = quark_hash.getPoWHash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
        elif settings.COINDAEMON_ALGO == 'max':
            hash_bin = sha3_256(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ])).digest()[0:33]
	elif settings.COINDAEMON_ALGO == 'skeinhash':
            hash_bin = skeinhash.skeinhash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
        elif settings.COINDAEMON_ALGO == 'keccak':
          s = sha3.sha3_256()
          ntime1 = str(int(ntime, 16))
          s.update(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]) + ntime1)
          hash_bin = s.hexdigest()
	else:
            hash_bin = util.doublesha(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))

        hash_int = util.uint256_from_str(hash_bin)
        scrypt_hash_hex = "%064x" % hash_int
        header_hex = binascii.hexlify(header_bin)
        if settings.COINDAEMON_ALGO == 'scrypt' or settings.COINDAEMON_ALGO == 'scrypt-jane':
            header_hex = header_hex+"000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"
        elif settings.COINDAEMON_ALGO == 'quark':
            header_hex = header_hex+"000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"
        #elif settings.COINDAEMON_ALGO == 'max':
            #header_hex = header_hex+"000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"
        else: pass

        target_user = self.diff_to_target(difficulty)
        if hash_int > target_user:
            raise SubmitException("Share is above target. Hash: %s",
                    scrypt_hash_hex)

        # Mostly for debugging purposes
        target_info = self.diff_to_target(100000)
        if hash_int <= target_info:
            log.info("Yay, share with diff above 100000")

        # Algebra tells us the diff_to_target is the same as hash_to_diff
        share_diff = int(self.diff_to_target(hash_int))

        # 5. Compare hash with target of the network
        if hash_int <= job.target:
            # Yay! It is block candidate!
            log.info("We found a block candidate! %s" % scrypt_hash_hex)

            # Reverse the header and get the potential block hash (for scrypt only)
            if settings.COINDAEMON_ALGO == 'max':
                block_hash_bin = sha3_256(''.join([ header_bin[i*4:i*4+4][::-1]
                    for i in range(0, 20) ]) + str(int(ntime, 16))).hexdigest()
            elif settings.COINDAEMON_ALGO == 'keccak':
                s = sha3.SHA3256()
                ntime1 = str(int(ntime, 16))
                s.update(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]) + ntime1)
	    else:
	        block_hash_bin = util.doublesha(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
            block_hash_hex = block_hash_bin[::-1].encode('hex_codec')
            if settings.COINDAEMON_ALGO != 'max':
            	block_hash_hex = hash_bin[::-1].encode('hex_codec')
            # 6. Finalize and serialize block object
            job.finalize(merkle_root_int, extranonce1_bin, extranonce2_bin, int(ntime, 16), int(nonce, 16))

            if not job.is_valid():
                # Should not happen
                log.exception("FINAL JOB VALIDATION FAILED!(Try enabling/disabling tx messages)")

            # 7. Submit block to the network
            serialized = binascii.hexlify(job.serialize())
            on_submit = self.bitcoin_rpc.submitblock(serialized, block_hash_hex, scrypt_hash_hex)
            if on_submit:
                self.update_block()

            if settings.SOLUTION_BLOCK_HASH:
                return (header_hex, block_hash_hex, share_diff, on_submit)
            else:
                return (header_hex, scrypt_hash_hex, share_diff, on_submit)

        if settings.SOLUTION_BLOCK_HASH:
        # Reverse the header and get the potential block hash (for scrypt only) only do this if we want to send in the block hash to the shares table
           if settings.COINDAEMON_ALGO == 'keccak':
               s = sha3.sha3_256()
               ntime1 = str(int(ntime, 16))
               s.update(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]) + ntime1)
               block_hash_bin = s.hexdigest()
           else:
           	block_hash_bin = util.doublesha(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
           block_hash_hex = block_hash_bin[::-1].encode('hex_codec')
           return (header_hex, block_hash_hex, share_diff, None)
        else:
            return (header_hex, scrypt_hash_hex, share_diff, None)
コード例 #34
0
def validate(secret=None):
    # already validated above
    print("Validating")
    json_string = json.loads(request.data)
    registrationReq = json_string["registration"]

    address = registrationReq["address"]
    print("Address: " + address)
    signature = json_string["signature"]

    if not signature:
        resp = app.make_response(jsonify(missingSignature))
        print("could not find signature from payload.")
        resp.status = "400"
        resp.content_type = "application/json"
        return resp

    verified_address = verify_address(registrationReq, signature)
    if verified_address != address:
        resp = app.make_response(jsonify(mismatchAddressSignature))
        print("signature doesn't match address.")
        resp.status = "400"
        resp.content_type = "application/json"
        return resp

    if not registrationReq or not registrationReq["token"]:
        resp = app.make_response(jsonify(invalidJsonInBody))
        resp.status = "401"
        resp.content_type = "application/json"
        return resp

    access_token = registrationReq["token"]
    print(access_token)

    if not access_token:
        resp = app.make_response(jsonify(authErrorNoToken))
        resp.status = "401"
        resp.content_type = "application/json"
        return resp

    token_header = jwt.get_unverified_header(access_token)
    x5c = None

    # Iterate JWK keys and extract matching x5c chain
    for key in jwk_keys['keys']:
        if key['kid'] == token_header['kid']:
            x5c = key['x5c']

    print("x5c is {0}".format(x5c[0]))

    if x5c[0] not in publicKeyMap.keys():
        cert = ''.join([
            '-----BEGIN CERTIFICATE-----\n',
            x5c[0],
            '\n-----END CERTIFICATE-----\n',
        ])
        public_key = load_pem_x509_certificate(cert.encode(),
                                               default_backend()).public_key()
        publicKeyMap[x5c[0]] = public_key
        print("public key constructed")
    else:
        public_key = publicKeyMap[x5c[0]]
        print("Cached public key is used")

    try:
        decoded_token = jwt.decode(
            access_token,
            public_key,
            verify=True if secret != 'test' else False,  # for debug
            algorithms=token_header['alg'],
            audience="79d908c3-6cc1-40c6-bbf1-9f7140e927fb")
    except jwt.exceptions.ExpiredSignatureError:
        print("expired signature")
        resp = app.make_response(jsonify(authErrorExpiredToken))
        resp.status = "401"
        resp.content_type = "application/json"
        return resp
    except:
        resp = app.make_response(jsonify(authErrorBadToken))
        print("bad token")
        resp.status = "401"
        resp.content_type = "application/json"
        return resp

    claimSet = registrationReq["options"]["claims"]
    # ignore the claimSet for now until we support more claim types
    if not claimSet or len(claimSet) != 1 or claimSet[0] != "tid":
        resp = app.make_response(jsonify(authErrorClaimNotSupport))
        print("claims in the claims to extract list are not supported")
        resp.status = "400"
        resp.content_type = "application/json"
        return resp

    tenantId = decoded_token["tid"]
    userObjectId = decoded_token["oid"]
    issuedAtTicks = decoded_token["iat"]

    print(decoded_token)
    print(tenantId)
    print(userObjectId)
    print(address)
    print(issuedAtTicks)
    userHash = sha3.sha3_256(
        (tenantId + "_" + userObjectId).encode('utf-8')).hexdigest()
    print("hash: " + userHash)

    # setTenant(contract, )

    resp = app.make_response("success")
    resp.status = "200"
    return resp
コード例 #35
0
ファイル: util.py プロジェクト: bubble501/ethash_learning
def sha3_256(x):
    return hash_words(lambda v: sha3.sha3_256(v).digest(), 32, x)
コード例 #36
0
def sha3(s, encoding=None):
    if isinstance(s, six.text_type):
        s = s.encode('utf8')
    if encoding:
        s = codecs.decode(strip_0x_prefix(s), encoding)
    return sha3_256(s).hexdigest()
コード例 #37
0
def hash_transaction(transaction):
    return sha3_256(serialize_transaction(transaction).encode()).hexdigest()
コード例 #38
0
ファイル: iroha.py プロジェクト: phillipgibb/blockchain
def sha3_256(message):
    return sha3.sha3_256(message).digest()
コード例 #39
0
 def blake2b256_keccak256(data):
     b = blake2b(digest_size=32)
     b.update(data)
     return sha3_256(b.digest()).digest()
コード例 #40
0
 def hash_data(data):
     return sha3.sha3_256(data.encode()).hexdigest()
コード例 #41
0
def hash_data(data):
    """Hash the provided data using SHA3-256"""
    return sha3.sha3_256(data.encode()).hexdigest()
コード例 #42
0
ファイル: utils.py プロジェクト: zebbra2014/pyethereum
def sha3(seed):
    return sha3_256(to_string(seed)).digest()
コード例 #43
0
ファイル: pearlbase.py プロジェクト: andreysobol/pearl
 def get_hash(self):
     return sha3.sha3_256(self.pearl.get_color_bytes() + self.owner).digest()
コード例 #44
0
ファイル: utils.py プロジェクト: ryanwwest/indy-plenum
 def sha3_256(x):
     return _sha3.sha3_256(x).digest()
コード例 #45
0
ファイル: utils.py プロジェクト: fedaykinofdune/pyethereum
def sha3(seed):
    return sha3_256(seed).digest()
コード例 #46
0
ファイル: ethash_utils.py プロジェクト: yourhrh/Request
try:
    from Crypto.Hash import keccak

    sha3_256 = lambda x: keccak.new(digest_bits=256, data=x).digest()
    sha3_512 = lambda x: keccak.new(digest_bits=512, data=x)
except:
    import sha3 as _sha3

    sha3_256 = lambda x: _sha3.sha3_256(x).digest()
    sha3_512 = lambda x: _sha3.sha3_512(x).digest()
from rlp.utils import decode_hex, encode_hex
import sys

WORD_BYTES = 4  # bytes in word
DATASET_BYTES_INIT = 2 ** 30  # bytes in dataset at genesis
DATASET_BYTES_GROWTH = 2 ** 23  # growth per epoch (~7 GB per year)
CACHE_BYTES_INIT = 2 ** 24  # Size of the dataset relative to the cache
CACHE_BYTES_GROWTH = 2 ** 17  # Size of the dataset relative to the cache
EPOCH_LENGTH = 30000  # blocks per epoch
MIX_BYTES = 128  # width of mix
HASH_BYTES = 64  # hash length in bytes
DATASET_PARENTS = 256  # number of parents of each dataset element
CACHE_ROUNDS = 3  # number of rounds in cache production
ACCESSES = 64  # number of accesses in hashimoto loop


FNV_PRIME = 0x01000193


def fnv(v1, v2):
    return (v1 * FNV_PRIME ^ v2) % 2 ** 32
コード例 #47
0
 def get_hash(self):
     sha3.sha3_256(self.get_color_bytes()).digest()
コード例 #48
0
    def sha3_256(x): return _sha3.sha3_256(x).digest()

address = Binary.fixed_length(20, allow_empty=True)
コード例 #49
0
def sha3(value):
    return sha3_256(value).digest()
def test_challenging_answer(
    deploy_client,
    deploy_broker_contract,
    deployed_contracts,
    get_log_data,
    deploy_coinbase,
    contracts,
    StatusEnum,
    denoms,
):
    factory = deployed_contracts.BuildByteArrayFactory
    broker = deploy_broker_contract(factory._meta.address)

    expected = "\x01\x02\x03\x04\x05\x06\x07"

    request_txn_hash = broker.requestExecution("abcdefg", value=10 * denoms.ether)
    request_txn_receipt = deploy_client.wait_for_transaction(request_txn_hash)

    request_event_data = get_log_data(broker.Created, request_txn_hash)

    _id = request_event_data["id"]

    assert broker.getRequest(_id)[5] == StatusEnum.Pending

    deposit_amount = broker.getRequiredDeposit("abcdefg")

    assert deposit_amount > 0

    i_answer_txn_hash = broker.answerRequest(_id, "wrong", value=deposit_amount)
    i_answer_txn_receipt = deploy_client.wait_for_transaction(i_answer_txn_hash)

    assert broker.getRequest(_id)[5] == StatusEnum.WaitingForResolution

    i_answer_data = set(broker.getInitialAnswer(_id))

    assert deploy_coinbase in i_answer_data
    assert sha3.sha3_256("wrong").digest() in i_answer_data
    assert int(i_answer_txn_receipt["blockNumber"], 16) in i_answer_data
    assert broker.getInitialAnswerResult(_id) == "wrong"

    c_answer_txn_hash = broker.challengeAnswer(_id, expected, value=deposit_amount)
    c_answer_txn_receipt = deploy_client.wait_for_transaction(c_answer_txn_hash)

    assert broker.getRequest(_id)[5] == StatusEnum.NeedsResolution

    c_answer_data = set(broker.getChallengeAnswer(_id))

    assert deploy_coinbase in c_answer_data
    assert sha3.sha3_256(expected).digest() in c_answer_data
    assert int(c_answer_txn_receipt["blockNumber"], 16) in c_answer_data
    assert broker.getChallengeAnswerResult(_id) == expected

    assert broker.getRequest(_id)[3] == "0x0000000000000000000000000000000000000000"
    assert broker.getRequest(_id)[5] == StatusEnum.NeedsResolution

    i_dispute_txn_hash = broker.initializeDispute(_id)
    i_dispute_txn_receipt = deploy_client.wait_for_transaction(i_dispute_txn_hash)

    assert broker.getRequest(_id)[5] == StatusEnum.Resolving

    i_dispute_log_data = get_log_data(factory.Constructed, i_dispute_txn_hash)

    assert i_dispute_log_data["addr"] in broker.getRequest(_id)[3]
コード例 #51
0
ファイル: algo_interface.py プロジェクト: iSC-Labs/TidePool
def make_header_hash_max(header):
    #return max_hash.getPoWHash(header)
    return sha3_256(header).digest()
コード例 #52
0
 def digest(self):
     return sha3.sha3_256(self._data).digest()
コード例 #53
0
    def submit_share(self, job_id, worker_name, session, extranonce1_bin, extranonce2, ntime, nonce,
                     difficulty):
        '''Check parameters and finalize block template. If it leads
           to valid block candidate, asynchronously submits the block
           back to the bitcoin network.
        
            - extranonce1_bin is binary. No checks performed, it should be from session data
            - job_id, extranonce2, ntime, nonce - in hex form sent by the client
            - difficulty - decimal number from session, again no checks performed
            - submitblock_callback - reference to method which receive result of submitblock()
        '''
        
        # Check if extranonce2 looks correctly. extranonce2 is in hex form...
        if len(extranonce2) != self.extranonce2_size * 2:
            raise SubmitException("Incorrect size of extranonce2. Expected %d chars" % (self.extranonce2_size*2))
        
        # Check for job
        job = self.get_job(job_id)
        if job == None:
            raise SubmitException("Job '%s' not found" % job_id)
                
        # Check if ntime looks correct
        if len(ntime) != 8:
            raise SubmitException("Incorrect size of ntime. Expected 8 chars")

        if not job.check_ntime(int(ntime, 16)):
            raise SubmitException("Ntime out of range")
        
        # Check nonce        
        if len(nonce) != 8:
            raise SubmitException("Incorrect size of nonce. Expected 8 chars")
        
        # Check for duplicated submit
        if not job.register_submit(extranonce1_bin, extranonce2, ntime, nonce):
            log.info("Duplicate from %s, (%s %s %s %s)" % \
                    (worker_name, binascii.hexlify(extranonce1_bin), extranonce2, ntime, nonce))
            raise SubmitException("Duplicate share")
        
        # Now let's do the hard work!
        # ---------------------------
        
        # 0. Some sugar
        extranonce2_bin = binascii.unhexlify(extranonce2)
        ntime_bin = binascii.unhexlify(ntime)
        nonce_bin = binascii.unhexlify(nonce)
                
        # 1. Build coinbase
        coinbase_bin = job.serialize_coinbase(extranonce1_bin, extranonce2_bin)
        if settings.COINDAEMON_ALGO == 'max' or settings.COINDAEMON_ALGO == 'blake':
             coinbase_hash = sha256(coinbase_bin).digest()
        else:
             coinbase_hash = util.doublesha(coinbase_bin)
        
        # 2. Calculate merkle root
        merkle_root_bin = job.merkletree.withFirst(coinbase_hash)
        merkle_root_int = util.uint256_from_str(merkle_root_bin)
                
        # 3. Serialize header with given merkle, ntime and nonce
        header_bin = job.serialize_header(merkle_root_int, ntime_bin, nonce_bin)
    
        # 4. Reverse header and compare it with target of the user
        if settings.COINDAEMON_ALGO == 'scrypt':
            hash_bin = ltc_scrypt.getPoWHash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
        elif settings.COINDAEMON_ALGO  == 'scrypt-jane':
            hash_bin = yac_scrypt.getPoWHash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]), int(ntime, 16))
        elif settings.COINDAEMON_ALGO == 'quark':
            hash_bin = quark_hash.getPoWHash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
        elif settings.COINDAEMON_ALGO == 'max':
            hash_bin = max_hash.getPoWHash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
            hash_bin = sha3_256(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ])).digest()[0:33]
        elif settings.COINDAEMON_ALGO == 'blake':
             hash_bin = blake_hash.getPoWHash80(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))#.digest()[0:33]
	elif settings.COINDAEMON_ALGO == 'skeinhash':
            hash_bin = skeinhash.skeinhash(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
        elif settings.COINDAEMON_ALGO == 'keccak':
          s = sha3.sha3_256()
          ntime1 = str(int(ntime, 16))
          s.update(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]) + ntime1)
          hash_bin = s.hexdigest()
	else:
            hash_bin = util.doublesha(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))

        hash_int = util.uint256_from_str(hash_bin)
        scrypt_hash_hex = "%064x" % hash_int
        header_hex = binascii.hexlify(header_bin)
        if settings.COINDAEMON_ALGO == 'scrypt' or settings.COINDAEMON_ALGO == 'scrypt-jane':
            header_hex = header_hex+"000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"
        elif settings.COINDAEMON_ALGO == 'quark':
            header_hex = header_hex+"000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"
        #elif settings.COINDAEMON_ALGO == 'max':
            #header_hex = header_hex+"000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"
        else: pass
                 
        #target_user = self.diff_to_target(difficulty)

        target_user = self.diff_to_target(difficulty)
        #print(self.diff_to_target(target_user))

        if hash_int > target_user:
            raise SubmitException("Share is above target. Hash: %s", scrypt_hash_hex)

        # Mostly for debugging purposes
        target_info = self.diff_to_target(100000)
        if hash_int <= target_info:
            log.info("Yay, share with diff above 100000")

        # Algebra tells us the diff_to_target is the same as hash_to_diff
        share_diff = int(self.diff_to_target(hash_int))

        # 5. Compare hash with target of the network
        if hash_int <= job.target:
            # Yay! It is block candidate! 
            log.info("We found a block candidate! %s" % scrypt_hash_hex)

            # Reverse the header and get the potential block hash (for scrypt only) 
            if settings.COINDAEMON_ALGO == 'max':
                block_hash_bin =                 sha3_256(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ])).digest()[0:33]
                block_hash_bin = sha3_256(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]) + str(int(ntime, 16))).hexdigest()
            elif settings.COINDAEMON_ALGO == 'blake':
            	 block_hash_bin = blake_hash.getPoWHash80(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ])) #.digest()[0:33] #''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]) + str(int(ntime, 16))).hexdigest()
            elif settings.COINDAEMON_ALGO == 'keccak':
                s = sha3.SHA3256()
                ntime1 = str(int(ntime, 16))
                s.update(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]) + ntime1)
	    else:
	        block_hash_bin = util.doublesha(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))

            block_hash_hex = block_hash_bin[::-1].encode('hex_codec')
            if settings.COINDAEMON_ALGO != 'max':
            	block_hash_hex = hash_bin[::-1].encode('hex_codec')

            # 6. Finalize and serialize block object 
            job.finalize(merkle_root_int, extranonce1_bin, extranonce2_bin, int(ntime, 16), int(nonce, 16))
            
            if not job.is_valid():
                # Should not happen
                log.exception("FINAL JOB VALIDATION FAILED!(Try enabling/disabling tx messages)")
                            
            # 7. Submit block to the network
            serialized = binascii.hexlify(job.serialize())
            on_submit = self.bitcoin_rpc.submitblock(serialized, block_hash_hex, scrypt_hash_hex)
            if on_submit:
                self.update_block()

            if settings.SOLUTION_BLOCK_HASH:
                return (header_hex, block_hash_hex, share_diff, on_submit)
            else:
                return (header_hex, scrypt_hash_hex, share_diff, on_submit)
        
        if settings.SOLUTION_BLOCK_HASH:
        # Reverse the header and get the potential block hash (for scrypt only) only do this if we want to send in the block hash to the shares table
           if settings.COINDAEMON_ALGO == 'keccak':
               s = sha3.sha3_256()
               ntime1 = str(int(ntime, 16))
               s.update(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]) + ntime1)
               block_hash_bin = s.hexdigest()
           else: 
           	block_hash_bin = util.doublesha(''.join([ header_bin[i*4:i*4+4][::-1] for i in range(0, 20) ]))
           block_hash_hex = block_hash_bin[::-1].encode('hex_codec')
           return (header_hex, block_hash_hex, share_diff, None)
        else:
            return (header_hex, scrypt_hash_hex, share_diff, None)
コード例 #54
0
)

from vyper.exceptions import (
    InvalidLiteralException,
    VariableDeclarationException,
)
from vyper.opcodes import (
    OPCODES,
)

try:
    from Crypto.Hash import keccak
    keccak256 = lambda x: keccak.new(digest_bits=256, data=x).digest()  # noqa: E731
except ImportError:
    import sha3 as _sha3
    keccak256 = lambda x: _sha3.sha3_256(x).digest()  # noqa: E731


# Converts four bytes to an integer
def fourbytes_to_int(inp):
    return (inp[0] << 24) + (inp[1] << 16) + (inp[2] << 8) + inp[3]


# Converts string to bytes
def string_to_bytes(str):
    bytez = b''
    for c in str:
        if ord(c) >= 256:
            raise InvalidLiteralException(f"Cannot insert special character {c} into byte array")
        bytez += bytes([ord(c)])
    bytez_length = len(bytez)
コード例 #55
0
ファイル: simulator.py プロジェクト: heikoheiko/fuelbattles
def call(a_address, b_address, a_ai, b_ai, start_gas):
    a_fuel = start_gas / 2
    b_fuel = start_gas / 2

    # setup grid
    ncells = cols * rows
    a_grid = [0] * ncells
    b_grid = [0] * ncells

    # redistribution grid
    seed = id(a_address) # prevhash
    seed = sha3.sha3_256(str(seed)).digest()
    redistribution_grid = mk_redistribution_grid(seed, ncells)

    # place a, b
    pos = ord(seed[0]) % (ncells/2)
    a_grid[pos] = a_fuel
    b_grid[-pos-1] = b_fuel


    def is_neighbour(a, b):
        return b in get_neighbours(a, cols, rows)

    def validate_move(grid, from_cell, to_cell, fuel):
        # check within grid
        if from_cell < ncells:
            if to_cell < ncells:
                # enough fuel there
                if fuel <= grid[from_cell]:
                    # check neighbour
                    if is_neighbour(from_cell, to_cell):
                        return True
        return False

    def total():
        return sum(a_grid + b_grid)

    sim_step_gas = 0
    sim_steps = 0
    total_gas_used = 0

    # end if one ran out of gas or half of start_gas is used
    while a_fuel > 0 and b_fuel > 0 and total() > start_gas / 2:
        if debug_callback:
            debug_callback(sim_steps, cols, rows, a_grid, b_grid, redistribution_grid)

        total_at_start = total()
        redistribution = 0

        for ai, grid, other_grid, fuel in ((a_ai, a_grid, b_grid, a_fuel), (b_ai, b_grid, a_grid[:], b_fuel)): # copy a_grid for 2nd call
            gas_used, move_from, move_to, move_amount = ai(seed, cols, rows, grid, other_grid)

            total_gas_used += gas_used
            if move_amount and not validate_move(grid, move_from, move_to, move_amount):
                move_amount = 0

            # move
            if move_amount:
                grid[move_from] = grid[move_from] - move_amount
                grid[move_to] = grid[move_to] + move_amount

            # remove gas and redistribution
            for i in range(ncells):
                cell_fuel = grid[i]
                redistribution_allowance = cell_fuel / inv_redistribution_factor
                gas_allowance = (sim_step_gas / 2 + gas_used) * cell_fuel / fuel
                grid[i] = max(0, cell_fuel - gas_allowance - redistribution_allowance)
                redistribution = redistribution + redistribution_allowance


        # handle collisions
        for i in range(ncells):
            if a_grid[i] and b_grid[i]:
                if a_grid[i] > b_grid[i]:
                    g, l = a_grid, b_grid
                else:
                    l, g = a_grid, b_grid
                d = g[i] - l[i]
                g[i] -= d
                l[i] = 0
                redistribution += d

        a_fuel = 0
        b_fuel = 0

        rnorm = sum(r for i, r in enumerate(redistribution_grid) if a_grid[i] or b_grid[i])

        for i in range(ncells):
            add = redistribution * redistribution_grid[i] / rnorm
            if a_grid[i]:
                a_grid[i] += add
            if b_grid[i]:
                b_grid[i] += add
            a_fuel += a_grid[i]
            b_fuel += b_grid[i]

        assert total_at_start > total()

        sim_step_gas = 3000 # guess
        total_gas_used += sim_step_gas
        sim_steps += 1

    # end while loop
    winner = a_address if a_fuel > b_fuel else b_address
    return total_gas_used, winner
コード例 #56
0
import binascii
import re

from collections import OrderedDict
from vyper.exceptions import InvalidLiteralException
from vyper.opcodes import opcodes

try:
    from Crypto.Hash import keccak
    sha3 = lambda x: keccak.new(digest_bits=256, data=x).digest()
except ImportError:
    import sha3 as _sha3
    sha3 = lambda x: _sha3.sha3_256(x).digest()


# Converts four bytes to an integer
def fourbytes_to_int(inp):
    return (inp[0] << 24) + (inp[1] << 16) + (inp[2] << 8) + inp[3]


# Converts string to bytes
def string_to_bytes(str):
    bytez = b''
    for c in str:
        if ord(c) >= 256:
            raise InvalidLiteralException(
                "Cannot insert special character %r into byte array" % c)
        bytez += bytes([ord(c)])
    bytez_length = len(bytez)
    return bytez, bytez_length
コード例 #57
0
ファイル: utils.py プロジェクト: 1600/hydrachain
def sha3(seed):
    return sha3_256(bytes(seed)).digest()
コード例 #58
0
ファイル: utils.py プロジェクト: elkingtowa/azove
def sha3(seed):
    return sha3_256(seed).digest()
コード例 #59
0
def test_tx_serialization_hash_function(signed_create_tx):
    tx = signed_create_tx.to_dict()
    tx['id'] = None
    payload = json.dumps(tx, skipkeys=False, sort_keys=True,
                         separators=(',', ':'))
    assert sha3.sha3_256(payload.encode()).hexdigest() == signed_create_tx.id
コード例 #60
0
import sys
import hashlib
import struct
import base64

# Python 3.6+, the SHA3 is available in hashlib natively. Else this requires
# the pysha3 package (pip install pysha3).
if sys.version_info < (3, 6):
    import sha3

# Test vector to make sure the right sha3 version will be used. pysha3 < 1.0
# used the old Keccak implementation. During the finalization of SHA3, NIST
# changed the delimiter suffix from 0x01 to 0x06. The Keccak sponge function
# stayed the same. pysha3 1.0 provides the previous Keccak hash, too.
TEST_VALUE = "e167f68d6563d75bb25f3aa49c29ef612d41352dc00606de7cbd630bb2665f51"
if TEST_VALUE != sha3.sha3_256(b"Hello World").hexdigest():
    print("pysha3 version is < 1.0. Please install from:")
    print("https://github.com/tiran/pysha3https://github.com/tiran/pysha3")
    sys.exit(1)

# Checksum is built like so:
#   CHECKSUM = SHA3(".onion checksum" || PUBKEY || VERSION)
PREFIX = ".onion checksum".encode()
# 32 bytes ed25519 pubkey from first test vector of
# https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-02#section-6
PUBKEY = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a".decode(
    'hex')
# Version 3 is proposal224
VERSION = 3

data = struct.pack('15s32sb', PREFIX, PUBKEY, VERSION)