def test_javascript_signatures(w3, get_contract):
    a3 = w3.eth.accounts[2]
    # The zero address will cause `approve` to default to valid signatures
    zero_address = "0x0000000000000000000000000000000000000000"
    accounts = [
        "0x776ba14735ff84789320718cf0aa43e91f7a8ce1",
        "0x095ce4e4240fa66ff90282c26847456e3f3b5002"
    ]
    # The address that will receive the transaction
    recipient = "0x776Ba14735FF84789320718cf0aa43e91F7A8Ce1"
    # These are the matching sigs to the accounts
    raw_sigs = [
        "0x4a89507bf71749fb338ed13fba623a683d9ecab0fb9c389a4298525c043e38281a00ab65628bb18a382eb8c8b4fb4dae95ccc993cf49f617c60d8051180778601c",  # noqa: E501
        "0xc84fe5d2a600e033930e0cf73f26e78f4c65b134f9c9992f60f08ce0863abdbe0548a6e8aa2d952659f29c67106b59fdfcd64d67df03c1df620c70c85578ae701b"  # noqa: E501
    ]

    # Turns the raw sigs into sigs
    sigs = [
        (
            w3.toInt(x[64:]),  # v
            w3.toInt(x[:32]),  # r
            w3.toInt(x[32:64])  # s
        ) for x in map(lambda z: w3.toBytes(hexstr=z[2:]), raw_sigs)
    ]

    h = w3.keccak((0).to_bytes(32, "big") + b'\x00' * 12 +
                  w3.toBytes(hexstr=recipient[2:]) + (25).to_bytes(32, "big") +
                  b'')  # noqa: E501
    h2 = w3.keccak(b"\x19Ethereum Signed Message:\n32" + h)

    # Check to make sure the signatures are valid
    assert is_same_address(Account.recoverHash(h2, sigs[0]), accounts[0])
    assert is_same_address(Account.recoverHash(h2, sigs[1]), accounts[1])

    # Set the owners to zero addresses
    with open('examples/wallet/wallet.vy') as f:
        owners = [
            w3.toChecksumAddress(x)
            for x in accounts + [a3, zero_address, zero_address]
        ]
        x2 = get_contract(f.read(), *[owners, 2])

    w3.eth.sendTransaction({'to': x2.address, 'value': 10**17})

    # There's no need to pass in signatures because the owners are 0 addresses
    # causing them to default to valid signatures
    assert x2.approve(
        0,
        recipient,
        25,
        b"",
        sigs + [[0, 0, 0]] * 3,
        call={
            'to': x2.address,
            'value': 10**17
        },
    )

    print("Javascript signature tests passed")
Exemplo n.º 2
0
    def recover_message(
            cls,
            message: bytes,
            signature: str,
            is_deprecated_mode: bool = False) -> Tuple[Address, ...]:
        """
        Recover the addresses from the hash.

        :param message: the message we expect
        :param signature: the transaction signature
        :param is_deprecated_mode: if the deprecated signing was used
        :return: the recovered addresses
        """
        if is_deprecated_mode:
            enforce(
                len(message) == 32,
                "Message must be hashed to exactly 32 bytes.")
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                address = Account.recoverHash(  # pylint: disable=no-value-for-parameter
                    message_hash=message,
                    signature=signature)
        else:
            signable_message = encode_defunct(primitive=message)
            address = Account.recover_message(  # pylint: disable=no-value-for-parameter
                signable_message=signable_message,
                signature=signature)
        return (address, )
Exemplo n.º 3
0
def verify(req):
    vc_str = req.GET.get('vc')
    vc = json.loads(vc_str)
    sig_from_client = vc.get('sig')
    issuer_did = vc.get('issuer_did')
    applicant_did = vc.get('applicant_did')
    type = vc.get('type')
    color = vc.get('color')
    brand = vc.get('brand')
    battery_capacity = vc.get('battery_capacity')
    msg = {"issuer_did": issuer_did, 'applicant_did': applicant_did, "type": type, "color": color, "brand": brand,
           "battery_capacity": battery_capacity}
    msg = json.dumps(msg)
    # gen msg hash
    msghash = defunct_hash_message(text=msg)
    addr = Account.recoverHash(msghash, signature=sig_from_client)
    vc_id = vc.get('id')
    issuer_did = Credential.objects.filter(id=vc_id)[0].issuer_did
    cre_addr = issuer_did.split(":")[2].lower()
    if w3.toChecksumAddress(cre_addr) != w3.toChecksumAddress(addr):
        return JsonResponse({"status": False})

    from assets.verify_cred import check_cred
    status = check_cred(vc_id=vc_id, issuer_did=issuer_did)
    if status:
        return JsonResponse({"status": True})
    else:
        return JsonResponse({"status": False})
Exemplo n.º 4
0
def verifySignature(message):
    print("Verificando Firma")
    #get signature params
    v = int(message["v"])
    r = int(message["r"])
    s = int(message["s"])
    address = message["address"]
    ecrecoverargs = (v, r, s)
    print(ecrecoverargs)
    #Clean params to compute hash.
    message['v'] = ''
    message['r'] = ''
    message['s'] = ''
    #Compute hash
    messageNoSign = message
    messageNoSign = json.dumps(messageNoSign)
    hashedMessage = hashlib.sha256(messageNoSign.encode('utf-8')).hexdigest()
    #Get address that signed the transaction
    addressSignature = Account.recoverHash(hashedMessage, ecrecoverargs)
    #Verify that address has enough funds to pay for rules.
    customer = rulesContract.functions.customerList(addressSignature).call()
    customerFunds = customer[1]
    rulesPrice = rulesContract.functions.rulesPrice().call()
    if customerFunds >= rulesPrice:
        print("Enough Funds")
        return True
    else:
        print("Not Enough Funds")
        return False
Exemplo n.º 5
0
def test_signature_verification(signature_kwargs):
    account = Account.create()
    hashed_structured_msg = defunct_hash_message(
        **signature_kwargs,
        signature_version=b'\x01',
    )
    signed = Account.signHash(hashed_structured_msg, account.privateKey)
    new_addr = Account.recoverHash(hashed_structured_msg,
                                   signature=signed.signature)
    assert new_addr == account.address
Exemplo n.º 6
0
 def verifySignature(msg, sign):
     """Verify the message signature 
             This method signs the message for the user authentication mechanism
             Args:
             msg: original message
             sign : the signed hash obtained after signing the message with private key
             Returns:
             string: returns the ethereum address corresponding to the private key the message was signed with
             """
     k = sha3.keccak_256()
     encoded_message = (json.dumps(msg)).encode("utf-8")
     k.update(encoded_message)
     message_hash = k.hexdigest()
     return Account.recoverHash(message_hash, signature=sign)
Exemplo n.º 7
0
    def test_get_signed_api_url(self, client):
        """Test that we can sign api urls using a local private key"""

        # sign a sample API request
        signed_url = client.get_signed_api_url(
            '/v1/devisechain/0055baf8939b9956dcae9175cbf0f5365cfd7348/weights')
        msg = '/v1/devisechain/0055baf8939b9956dcae9175cbf0f5365cfd7348/weights?address=' + client.address

        # Verify the signature is correct
        signature = signed_url.split('&signature=')[1]
        sign_msg = ("\x19Ethereum Signed Message:\n%s%s" % (len(msg), msg.lower())).encode('utf8')
        message_hash = sha3.keccak_256(sign_msg).hexdigest()
        account = Account()
        address = account.recoverHash(message_hash, signature=signature)
        assert address.lower() == client.address.lower()
Exemplo n.º 8
0
    def recover_message(
        self, message: bytes, signature: str, is_deprecated_mode: bool = False
    ) -> Tuple[Address, ...]:
        """
        Recover the addresses from the hash.

        :param message: the message we expect
        :param signature: the transaction signature
        :param is_deprecated_mode: if the deprecated signing was used
        :return: the recovered addresses
        """
        if is_deprecated_mode:
            assert len(message) == 32, "Message must be hashed to exactly 32 bytes."
            address = Account.recoverHash(message_hash=message, signature=signature)
        else:
            signable_message = encode_defunct(primitive=message)
            address = Account.recover_message(
                signable_message=signable_message, signature=signature
            )
        return (address,)
Exemplo n.º 9
0
    def verify_message(self,
                       message,
                       signed_message=None,
                       address=None,
                       use_tron: bool = True):
        """ Get the address of the account that signed the message with the given hash.
        You must specify exactly one of: vrs or signature

        Args:
            message (str): The message in the format "hex"
            signed_message (AttributeDict): Signature
            address (str): is Address
            use_tron (bool): is Tron header

        """
        if address is None:
            address = self.tron.default_address.base58

        if not is_hex(message):
            raise TronError('Expected hex message input')

        # Determine which header to attach to the message
        # before encrypting or decrypting
        header = TRX_MESSAGE_HEADER if use_tron else ETH_MESSAGE_HEADER

        message_hash = self.tron.sha3(text=header + message)
        recovered = Account.recoverHash(message_hash,
                                        signature=signed_message.signature)

        tron_address = '41' + recovered[2:]
        base58address = self.tron.address.from_hex(tron_address).decode()

        if base58address == address:
            return True

        raise ValueError('Signature does not match')
Exemplo n.º 10
0
def verifySignature(message):
    print("Verificando Firma")
    sourceID = int(message["id"])
    print(sourceID)
    #get signature params
    v = int(message.pop("v", None))
    r = int(message.pop("r", None))
    s = int(message.pop("s", None))
    info = message["info"]
    address = message["address"]
    print(message)
    ecrecoverargs = (v, r, s)
    print(ecrecoverargs)
    #Compute hash
    hashedMessage = hashlib.sha256(info.encode('utf-8')).hexdigest()
    #Verify Signature
    addressSignature = Account.recoverHash(hashedMessage, ecrecoverargs)
    print(addressSignature)
    print(address)
    if (addressSignature == address):  #Signature is correct
        print("Firma Correcta")
        sendInformation(sourceID, info, v, r, s)
    else:
        print("Firma Incorrecta")
Exemplo n.º 11
0
    def recover_hash(message_hash, signature):
        if not is_hex(message_hash):
            raise ValueError('Invalid message_hash provided')

        return ETHAccount.recoverHash(message_hash, signature=signature)
Exemplo n.º 12
0
def signature_address(nonce, signature):
    nonce_hash = keccak(keccak(text=nonce))
    address = Account.recoverHash(nonce_hash, signature=decode_hex(signature))
    return address
Exemplo n.º 13
0
 def recover_executive_address(self, proposal: Proposal) -> str:
     signing_account = Account.recoverHash(message_hash=proposal.digest,
                                           signature=self.serialize())
     return signing_account
Exemplo n.º 14
0
def test_ecrecover_simple_message_success(alice, message, msg_hash, signature,
                                          vrs):
    for kwargs in [{"signature": signature.signature}, {"vrs": vrs}]:
        recovered = Account.recoverHash(msg_hash, **kwargs)
        assert recovered == alice.address
Exemplo n.º 15
0
 def recover_address(self):
     msg_hash = self.message_hash()
     return Account.recoverHash(msg_hash, vrs=self.sig)
Exemplo n.º 16
0
from eth_account import Account
from eth_account.messages import encode_defunct

message = 'https://www.aztecprotocol.com/ignition/participant/0xb51da5f6a840098a2b78a381a2a9716ff1f112c1/?timestamp=1578775929139'
hash = '0x09b6524742eab624e8aff260bf168b17d546429a7471ca43f860f7a1a59899d8'
signature = '0x316c44c5db370af3cadde8101c298b6ff3bffb64147295d76446f12d2a623c9f59eec8834fd45c4bb2be950af2b5ea9db2813d1af35036866d3d035a086c844c1b'

success = Account.recover_message(encode_defunct(text=message),
                                  signature=signature) == Account.recoverHash(
                                      hash, signature=signature)

if success:
    print("Success! Verified Attestation!")
else:
    print("WARNING! Could not verify Attestation!")