Beispiel #1
0
    def test_signature_with_wrong_message_returns_false(self):
        w = Wallet()

        message = 'howdy'
        signature = w.sign(message)

        self.assertFalse(verify(w.verifying_key, 'hello', signature))
Beispiel #2
0
    def test_signature_with_correct_message_returns_true(self):
        w = Wallet()

        message = 'howdy'
        signature = w.sign(message)

        self.assertTrue(verify(w.verifying_key, message, signature))
Beispiel #3
0
    def test_no_txs_merklizes_and_signs_input_hash(self):
        tx_batch_1 = {
            'transactions': [],
            'timestamp': time.time(),
            'input_hash': 'A' * 64
        }

        work = [tx_batch_1]

        w = Wallet()

        exe = execution.SerialExecutor(executor=self.client.executor)

        results = exe.execute_work(
            driver=self.client.raw_driver,
            work=work,
            previous_block_hash='B' * 64,
            wallet=w,
            stamp_cost=20_000
        )

        self.assertTrue(verify(w.verifying_key, results[0]['input_hash'], results[0]['merkle_tree']['signature']))

        h = hashlib.sha3_256()
        h.update(bytes.fromhex(results[0]['input_hash']))

        self.assertEqual(h.hexdigest(), results[0]['merkle_tree']['leaves'][0])
Beispiel #4
0
    def test_sign_works_properly(self):
        w = Wallet()

        tx = build_transaction(
            wallet=w,
            processor='b' * 64,
            stamps=123,
            nonce=0,
            contract='currency',
            function='transfer',
            kwargs={
                'amount': 123,
                'to': 'jeff'
            }
        )

        decoded = decode(tx)

        res = verify(
            w.verifying_key,
            encode(decoded['payload']),
            decoded['metadata']['signature']
        )

        self.assertTrue(res)
Beispiel #5
0
    def test_signature_with_wrong_vk_returns_false(self):
        w = Wallet()

        message = 'howdy'
        signature = w.sign(message)

        a = Wallet()

        self.assertFalse(verify(a.verifying_key, message, signature))
Beispiel #6
0
    async def process_message(self, msg):
        self.log.info(f'Received work from {msg["sender"][:8]}')
        # if msg['sender'] not in self.masters:
        #     self.log.error(f'TX Batch received from non-master {msg["sender"][:8]}')
        #     return

        shim = {
            'transactions': [],
            'timestamp': int(time.time()),
            'signature': '0' * 128,
            'input_hash': msg["sender"],
            'sender': msg["sender"]
        }

        if not verify(vk=msg['sender'],
                      msg=msg['input_hash'],
                      signature=msg['signature']):
            self.log.error(
                f'Invalidly signed TX Batch received from master {msg["sender"][:8]}'
            )
            return self.new_work[msg['sender']].append(shim)

        if int(time.time()) - msg['timestamp'] > self.expired_batch:
            self.log.error(
                f'Expired TX Batch received from master {msg["sender"][:8]}')
            return self.new_work[msg['sender']].append(shim)

        # Add padded!
        # Iterate and delete transactions from list that fail
        good_transactions = []
        for tx in msg['transactions']:
            try:
                transaction.transaction_is_valid_no_stale(
                    transaction=tx,
                    expected_processor=msg['sender'],
                    client=self.client,
                    nonces=self.nonces,
                    strict=False,
                    timeout=self.expired_batch + self.tx_timeout)
                good_transactions.append(tx)
            except transaction.TransactionException as e:
                self.log.error(f'TX in batch has error: {type(e)}')
                if isinstance(e,
                              transaction.TransactionTooManyPendingException):
                    self.log.error(f'Adding {tx} to good txs.')
                    good_transactions.append(tx)
                else:
                    good_transactions.append(InvalidTX(tx, e))

        # Replace transactions with ones that do not pass.
        msg['transactions'] = good_transactions

        self.new_work[msg['sender']].append(msg)
        self.log.info(
            f'{msg["sender"][:8]} has {len(self.new_work[msg["sender"]])} batches of work to do.'
        )
Beispiel #7
0
def check_tx_formatting(tx: dict, expected_processor: str):
    if not check_format(tx, rules.TRANSACTION_RULES):
        raise TransactionFormattingError

    if not wallet.verify(tx['payload']['sender'], encode(tx['payload']),
                         tx['metadata']['signature']):
        raise TransactionSignatureInvalid

    if tx['payload']['processor'] != expected_processor:
        raise TransactionProcessorInvalid
Beispiel #8
0
def verify_proof(proof, pepper):
    # Proofs expire after a minute
    if not primatives.check_format(proof, rules.PROOF_MESSAGE_RULES):
        return False

    if int(time.time()) - proof['timestamp'] > PROOF_EXPIRY:
        return False

    message = [pepper, proof['ip'], proof['timestamp']]
    message_bytes = encode(message).encode()

    h = hashlib.sha3_256()
    h.update(message_bytes)

    return verify(proof['vk'], h.digest().hex(), proof['signature'])
Beispiel #9
0
    def sbc_is_valid(self, sbc, sb_idx=0):
        if sbc['subblock'] != sb_idx:
            self.log.error(f'Subblock Contender[{sb_idx}] is out order.')
            return False

        # Make sure signer is in the delegates
        if len(sbc['transactions']) == 0:
            message = sbc['input_hash']
        else:
            message = sbc['merkle_tree']['leaves'][0]

        valid_sig = verify(vk=sbc['signer'],
                           msg=message,
                           signature=sbc['merkle_tree']['signature'])

        if not valid_sig:
            self.log.error(
                f'Subblock Contender[{sb_idx}] from {sbc["signer"][:8]} has an invalid signature.'
            )
            return False

        if len(sbc['merkle_tree']['leaves']) > 0:
            txs = [encode(tx).encode() for tx in sbc['transactions']]
            expected_tree = merklize(txs)

            # Missing leaves, etc
            if len(sbc['merkle_tree']['leaves']) != len(expected_tree) and len(
                    sbc['transactions']) > 0:
                self.log.error('Merkle Tree Len mismatch')
                return False

            for i in range(len(expected_tree)):
                if expected_tree[i] != sbc['merkle_tree']['leaves'][i]:
                    self.log.error(
                        f'Subblock Contender[{sbc["subblock"]}] from {sbc["signer"][:8]} has an Merkle tree proof.'
                    )
                    self.log.error(expected_tree[i])
                    self.log.error(txs[i])
                    return False

        self.log.info(
            f'Subblock[{sbc["subblock"]}] from {sbc["signer"][:8]} is valid.')

        return True
Beispiel #10
0
from lamden.crypto.wallet import Wallet, verify

privkey = "01c4763eadd4285cc31fdd60dedb4fa7c68f29e325775dc7f7f082bbab9b5fc9"

wallet = Wallet(privkey)

# Let's sign this message and receive a signature
message = "Some random string"
signature = wallet.sign(message)

print("signature", signature)

# Output
# ba32fcfa1b975f1572a1be21efa949d29f3a9e15e064d0e8d5f90eff596a204dd20ad8ca53161224ff62e97c147aba297f9ba8fd3a1eb8223c095cf6bcc85409

# Let's verify that the message was signed by my public address
signature = "ba32fcfa1b975f1572a1be21efa949d29f3a9e15e064d0e8d5f90eff596a204dd20ad8ca53161224ff62e97c147aba297f9ba8fd3a1eb8223c095cf6bcc85409"
was_it_me = verify(wallet.verifying_key, message, signature)

print("was_it_me", was_it_me)

# Output
# was_it_me True