예제 #1
0
 def do_execute(self, state):
     uid = state.certificate_json['assertion']['uid']
     signature = state.certificate_json['signature']
     if state.signing_key is None or uid is None or signature is None:
         return False
     message = BitcoinMessage(uid)
     return VerifyMessage(state.signing_key, message, signature)
예제 #2
0
def verify_signature(uid, signed_certificate_file_name, issuing_address):
    """
    Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use
    VerifyMessage to confirm that the signature in the certificate matches the issuing_address.

    Raises error is verification fails.

    :param uid:
    :param signed_certificate_file_name:
    :param issuing_address:
    :return:
    """

    # Throws an error if invalid
    logging.info('verifying signature for certificate with uid=%s:', uid)
    with open(signed_certificate_file_name) as in_file:
        signed_cert = in_file.read()
        signed_cert_json = json.loads(signed_cert)

        to_verify = signed_cert_json['assertion']['uid']
        signature = signed_cert_json['signature']
        message = BitcoinMessage(to_verify)
        verified = VerifyMessage(issuing_address, message, signature)
        if not verified:
            error_message = 'There was a problem with the signature for certificate uid={}'.format(
                signed_cert_json['assertion']['uid'])
            raise UnverifiedSignatureError(error_message)

        logging.info('verified signature')
def verify_message(address, message, signature):
    try:
        return VerifyMessage(address=address,
                             message=BitcoinMessage(message),
                             sig=signature)
    except Exception as ex:
        return False
def sign_and_verify(private_key, message, address):
    key = CBitcoinSecret(private_key)
    signature = SignMessage(key=key, message=BitcoinMessage(message))
    assert VerifyMessage(address=address,
                         message=BitcoinMessage(message),
                         sig=signature)
    return signature
예제 #5
0
 async def recover_missing_transaction(self, txn_id, exclude_ids=[]):
     return False
     if await self.config.mongo.async_db.failed_recoveries.find_one({'txn_id': txn_id}):
         return False
     self.app_log.warning("recovering missing transaction input: {}".format(txn_id))
     address = str(P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(self.public_key)))
     missing_txns = self.config.mongo.async_db.blocks.aggregate([
         {
             '$unwind': '$transactions'
         },
         {
             '$project': {
                 'transaction': '$transactions',
                 'index': '$index'
             }
         }
     ], allowDiskUse=True)
     async for missing_txn in missing_txns:
         self.app_log.warning('recovery searching block index: {}'.format(missing_txn['index']))
         try:
             result = verify_signature(base64.b64decode(txn_id), missing_txn['transaction']['hash'].encode(),
                                     bytes.fromhex(self.public_key))
             if result:
                 block_index = await self.find_unspent_missing_index(missing_txn['transaction']['hash'], exclude_ids)
                 if block_index:
                     await self.replace_missing_transaction_input(
                         block_index,
                         missing_txn['transaction']['hash'],
                         txn_id
                     )
                     return True
             else:
                 if len(base64.b64decode(txn_id)) != 65:
                     continue
                 result = VerifyMessage(
                     address,
                     BitcoinMessage(missing_txn['transaction']['hash'], magic=''),
                     txn_id
                 )
                 if result:
                     block_index = await self.find_unspent_missing_index(missing_txn['transaction']['hash'], exclude_ids)
                     if block_index:
                         await self.replace_missing_transaction_input(
                             block_index,
                             missing_txn['transaction']['hash'],
                             txn_id
                         )
                         return True
         except:
             continue
     await self.config.mongo.async_db.failed_recoveries.update_one({
         'txn_id': txn_id
     },
     {
         '$set': {
             'txn_id': txn_id
         }
     }, upsert=True)
     return False
예제 #6
0
    def test_verify_message_simple(self):
        address = "1F26pNMrywyZJdr22jErtKcjF8R3Ttt55G"
        message = address
        signature = "H85WKpqtNZDrajOnYDgUY+abh0KCAcOsAIOQwx2PftAbLEPRA7mzXA/CjXRxzz0MC225pR/hx02Vf2Ag2x33kU4="

        message = BitcoinMessage(message)

        self.assertTrue(VerifyMessage(address, message, signature))
예제 #7
0
    def verify(self):
        getcontext().prec = 8
        if int(self.version) != int(CHAIN.get_version_for_height(self.index)):
            raise Exception("Wrong version for block height", self.version, CHAIN.get_version_for_height(self.index))

        txns = self.get_transaction_hashes()
        verify_merkle_root = self.get_merkle_root(txns)
        if verify_merkle_root != self.merkle_root:
            raise Exception("Invalid block merkle root")

        header = self.generate_header()
        hashtest = self.generate_hash_from_header(self.index, header, str(self.nonce))
        # print("header", header, "nonce", self.nonce, "hashtest", hashtest)
        if self.hash != hashtest:
            getLogger("tornado.application").warning("Verify error hashtest {} header {} nonce {}".format(hashtest, header, self.nonce))
            raise Exception('Invalid block hash')

        address = P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(self.public_key))
        try:
            # print("address", address, "sig", self.signature, "pubkey", self.public_key)
            result = verify_signature(base64.b64decode(self.signature), self.hash.encode('utf-8'), bytes.fromhex(self.public_key))
            if not result:
                raise Exception("block signature1 is invalid")
        except:
            try:
                result = VerifyMessage(address, BitcoinMessage(self.hash.encode('utf-8'), magic=''), self.signature)
                if not result:
                    raise
            except:
                raise Exception("block signature2 is invalid")

        # verify reward
        coinbase_sum = 0
        for txn in self.transactions:
            if int(self.index) > CHAIN.CHECK_TIME_FROM and (int(txn.time) > int(self.time) + CHAIN.TIME_TOLERANCE):
                #yadacoin.core.config.CONFIG.mongo.db.miner_transactions.remove({'id': txn.transaction_signature}, multi=True)
                #raise Exception("Block embeds txn too far in the future")
                pass

            if txn.coinbase:
                for output in txn.outputs:
                    coinbase_sum += float(output.value)

        fee_sum = 0.0
        for txn in self.transactions:
            if not txn.coinbase:
                fee_sum += float(txn.fee)
        reward = CHAIN.get_block_reward(self.index)

        #if Decimal(str(fee_sum)[:10]) != Decimal(str(coinbase_sum)[:10]) - Decimal(str(reward)[:10]):
        """
        KO for block 13949
        0.02099999 50.021 50.0
        Integrate block error 1 ('Coinbase output total does not equal block reward + transaction fees', 0.020999999999999998, 0.021000000000000796)
        """
        if quantize_eight(fee_sum) != quantize_eight(coinbase_sum - reward):
            print(fee_sum, coinbase_sum, reward)
            raise Exception("Coinbase output total does not equal block reward + transaction fees", fee_sum, (coinbase_sum - reward))
예제 #8
0
파일: block.py 프로젝트: icook/yadacoin
    def verify(self):
        getcontext().prec = 8
        if int(self.version) != int(BU.get_version_for_height(self.index)):
            raise BaseException("Wrong version for block height", self.version,
                                BU.get_version_for_height(self.index))
        try:
            txns = self.get_transaction_hashes()
            self.set_merkle_root(txns)
            if self.verify_merkle_root != self.merkle_root:
                raise BaseException("Invalid block")
        except:
            raise

        try:
            header = BlockFactory.generate_header(self)
            hashtest = BlockFactory.generate_hash_from_header(
                header, str(self.nonce))
            if self.hash != hashtest:
                raise BaseException('Invalid block')
        except:
            raise

        address = P2PKHBitcoinAddress.from_pubkey(
            self.public_key.decode('hex'))
        try:
            result = verify_signature(base64.b64decode(self.signature),
                                      self.hash, self.public_key.decode('hex'))
            if not result:
                raise Exception("block signature is invalid")
        except:
            try:
                result = VerifyMessage(address,
                                       BitcoinMessage(self.hash, magic=''),
                                       self.signature)
                if not result:
                    raise
            except:
                raise BaseException("block signature is invalid")

        # verify reward
        coinbase_sum = 0
        for txn in self.transactions:
            if txn.coinbase:
                for output in txn.outputs:
                    coinbase_sum += float(output.value)

        fee_sum = 0.0
        for txn in self.transactions:
            if not txn.coinbase:
                fee_sum += float(txn.fee)
        reward = BU.get_block_reward(self.config, self.mongo, self)

        if Decimal(str(fee_sum)[:10]) != (Decimal(str(coinbase_sum)[:10]) -
                                          Decimal(str(reward)[:10])):
            raise BaseException(
                "Coinbase output total does not equal block reward + transaction fees",
                fee_sum, (coinbase_sum - reward))
예제 #9
0
def verifyMessage():
    data = request.get_json()
    addr = data["addr"]
    msg = BitcoinMessage(data["msg"])
    sig = data["sig"]
    if VerifyMessage(addr, msg, sig):
        return "verified"
    else:
        return "unverified"
예제 #10
0
파일: ewcore.py 프로젝트: RCasatta/ew-core
    def sign(self, message):
        message = BitcoinMessage(message)
        signature = SignMessage(self.key, message).decode('ascii')
        print("Address: %s" % self.key)
        print("Message: %s" % message)
        print("Signature: %s" % signature)
        assert VerifyMessage(self.address, message, signature)

        return signature
예제 #11
0
def check_author(address, signed_json):
    uid = signed_json['assertion']['uid']
    message = BitcoinMessage(uid)
    if signed_json.get('signature', None):
        signature = signed_json['signature']
        logging.debug('Found signature for uid=%s; verifying message', uid)
        return VerifyMessage(address, message, signature)
    logging.warning('Missing signature for uid=%s', uid)
    return False
예제 #12
0
def do_verify_signature(address, signed_cert):
    signed_cert_json = json.loads(signed_cert)
    to_verify = signed_cert_json['assertion']['uid']
    message = BitcoinMessage(to_verify)
    signature = signed_cert_json['signature']
    verified = VerifyMessage(address, message, signature)
    if not verified:
        error_message = 'There was a problem with the signature for certificate uid={}'.format(
            signed_cert_json['assertion']['uid'])
        raise UnverifiedSignatureError(error_message)
예제 #13
0
def check_incoming_job_crypto(job):
    job_id = job['job'].pop('id')
    if job_id == sha256(json.dumps(job).encode('utf-8')).hexdigest():
        validity = job.pop('validity')
        if VerifyMessage(validity['signature_address'],
                         BitcoinMessage(json.dumps(job)),
                         validity['signature']):
            return True
    else:
        return False
예제 #14
0
파일: app.py 프로젝트: xeagu/PepeVote
def delegate_submit():
    if request.method == 'GET':
        return render_template('delegate_submit.html')

    message = ''
    signature = ''

    if 'message' in request.form: message = request.form['message']
    if 'signature' in request.form: signature = request.form['signature']

    if message == "" or signature == "":
        status = 'Message/Signature is missing'
        return render_template('delegate_submit.html', status=status)

    try:
        message_object = json.loads(message)
    except:
        print("errored.")
        status = 'message is not properly formatted JSON'
        return render_template('delegate_submit.html', status=status)

    try:
        source = message_object['source']
        delegate = message_object['delegate']

    except:

        if not 'source' in message_object:
            status = 'Source field is missing.'

        if not 'delegate' in message_object:
            status = 'Delegate field is missing.'

        return render_template('delegate_submit.html', status=status)

    data = BitcoinMessage(message)
    verified = VerifyMessage(source, data, signature)

    if not verified:
        status = 'Verification failed.'
        return render_template('delegate_submit.html', status=status)

    tuple = (source, delegate)
    conn = sqlite3.connect('pepevote.db')
    c = conn.cursor()

    c.execute("INSERT OR REPLACE INTO delegates(source, delegate) VALUES(?,?)",
              tuple)
    conn.commit()
    conn.close()

    print('Delegation processed successfully.')

    status = 'Delegation processed successfully.'
    return render_template('delegate_submit.html', status=status)
예제 #15
0
    def test_sign_message_simple(self):
        key = CBitcoinSecret(
            "L4vB5fomsK8L95wQ7GFzvErYGht49JsCPJyJMHpB4xGM6xgi2jvG")
        address = "1F26pNMrywyZJdr22jErtKcjF8R3Ttt55G"
        message = address

        message = BitcoinMessage(message)
        signature = SignMessage(key, message)

        self.assertTrue(signature)
        self.assertTrue(VerifyMessage(address, message, signature))
예제 #16
0
def verify_message(address, message, signature):
    """
    Verify message was signed by the address
    :param address: signing address
    :param message: message to check
    :param signature: signature being tested
    :return:
    """
    bitcoin_message = BitcoinMessage(message)
    verified = VerifyMessage(address, bitcoin_message, signature)
    return verified
예제 #17
0
def print_verbose(signature, key, msg):
    secret = CBitcoinSecret(key)
    address = P2PKHBitcoinAddress.from_pubkey(secret.pub)
    message = BitcoinMessage(msg)
    print('Address: %s' % address)
    print('Message: %s' % msg)
    print('Signature: %s' % signature)
    print('Verified: %s' % VerifyMessage(address, message, signature))
    print('\nTo verify using bitcoin core:')
    print('\n`bitcoin-cli verifymessage %s \'%s\' \'%s\'`\n' %
          (address, signature.decode('ascii'), msg))
예제 #18
0
    def test_sign_message_vectors(self):
        for vector in load_test_vectors('signmessage.json'):
            key = CBitcoinSecret(vector['wif'])
            message = BitcoinMessage(vector['address'])

            signature = SignMessage(key, message)

            self.assertTrue(signature,
                            "Failed to sign for [%s]" % vector['address'])
            self.assertTrue(
                VerifyMessage(vector['address'], message, vector['signature']),
                "Failed to verify signature for [%s]" % vector['address'])
예제 #19
0
    def do_execute(self):

        if self.signing_key is None or self.content_to_verify is None or self.signature_value is None:
            return False
        message = BitcoinMessage(self.content_to_verify)
        try:
            lock.acquire()
            # obtain lock while modifying global state
            bitcoin.SelectParams(self.chain.name)
            return VerifyMessage(self.signing_key, message, self.signature_value)
        finally:
            lock.release()
    def verify(self):
        verify_hash = self.generate_hash()
        address = P2PKHBitcoinAddress.from_pubkey(
            self.public_key.decode('hex'))

        if verify_hash != self.hash:
            raise InvalidTransactionException("transaction is invalid")

        try:
            result = verify_signature(
                base64.b64decode(self.transaction_signature), self.hash,
                self.public_key.decode('hex'))
            if not result:
                raise
        except:
            try:
                result = VerifyMessage(address,
                                       BitcoinMessage(self.hash, magic=''),
                                       self.transaction_signature)
                if not result:
                    raise
            except:
                raise InvalidTransactionSignatureException(
                    "transaction signature did not verify")

        # verify spend
        total_input = 0
        for txn in self.inputs:
            txn_input = Transaction.from_dict(BU.get_transaction_by_id(txn.id))
            for output in txn_input.outputs:
                if str(output.to) == str(address):
                    total_input += float(output.value)

        if self.coinbase:
            return

        total_output = 0
        for txn in self.outputs:
            total_output += float(txn.value)
        total = float(total_output) + float(self.fee)
        if str(total_input) != str(total):
            raise BaseException(
                "inputs and outputs sum must match %s, %s, %s, %s" %
                (total_input, float(total_output), float(self.fee), total))
예제 #21
0
def verify(signed_json, options, chain_name='mainnet'):
    # options['expandContext': {'@vocab': 'https://fallback.org/'}]

    # compact to security context
    res = jsonld.compact(signed_json,
                         SECURITY_CONTEXT_URL,
                         options={'documentLoader': cached_document_loader})
    signature = res['signature']['signatureValue']
    del res['signature']
    normalized = normalize_jsonld(res)
    to_hash = _getDataToHash(normalized, options=options)

    message = BitcoinMessage(to_hash)

    signing_key = options.creator[len(PUBKEY_PREFIX):]

    # TODO: obtain lock while modifying global state
    bitcoin.SelectParams(chain_name)
    return VerifyMessage(signing_key, message, signature)
예제 #22
0
    def do_execute(self):

        if self.signing_key is None:
            logging.error(
                'EmbeddedSignatureChecker failed - signing key is none')
            return False
        if self.content_to_verify is None:
            logging.error(
                'EmbeddedSignatureChecker failed - content to verify is none')
            return False
        if self.signature_value is None:
            logging.error(
                'EmbeddedSignatureChecker failed - signature value is none')
            return False
        message = BitcoinMessage(self.content_to_verify)
        try:
            lock.acquire()
            # obtain lock while modifying global state
            bitcoin.SelectParams(chain_to_bitcoin_network(self.chain))
            return VerifyMessage(self.signing_key, message,
                                 self.signature_value)
        finally:
            lock.release()
예제 #23
0
def verify(address, message, signature):
    message = BitcoinMessage(message)
    return VerifyMessage(address, message, signature)
예제 #24
0
 def verifySignature(address, signature, m):
     message = BitcoinMessage(m)
     return VerifyMessage(address, message, signature)
예제 #25
0
    def verify(self):
        from fastgraph import FastGraph
        verify_hash = self.generate_hash()
        address = P2PKHBitcoinAddress.from_pubkey(
            self.public_key.decode('hex'))

        if verify_hash != self.hash:
            raise InvalidTransactionException("transaction is invalid")

        try:
            result = verify_signature(
                base64.b64decode(self.transaction_signature), self.hash,
                self.public_key.decode('hex'))
            if not result:
                raise Exception()
        except:
            try:
                result = VerifyMessage(address,
                                       BitcoinMessage(self.hash, magic=''),
                                       self.transaction_signature)
                if not result:
                    raise
            except:
                raise InvalidTransactionSignatureException(
                    "transaction signature did not verify")

        # verify spend
        total_input = 0
        for txn in self.inputs:
            input_txn = BU.get_transaction_by_id(self.config,
                                                 self.mongo,
                                                 txn.id,
                                                 include_fastgraph=isinstance(
                                                     self, FastGraph))
            if not input_txn:
                raise InvalidTransactionException(
                    "Input not found on blockchain.")
            txn_input = Transaction.from_dict(self.config, self.mongo,
                                              self.block_height, input_txn)

            found = False
            for output in txn_input.outputs:
                if hasattr(txn, 'public_key') and hasattr(txn, 'signature'):
                    ext_address = P2PKHBitcoinAddress.from_pubkey(
                        txn.public_key.decode('hex'))
                    if str(output.to) == str(ext_address):
                        found = True
                        try:
                            result = verify_signature(
                                base64.b64decode(txn.signature), txn.id,
                                txn.public_key.decode('hex'))
                            if not result:
                                raise Exception()
                        except:
                            try:
                                result = VerifyMessage(
                                    ext_address,
                                    BitcoinMessage(txn.id, magic=''),
                                    txn.signature)
                                if not result:
                                    raise
                            except:
                                raise InvalidTransactionSignatureException(
                                    "external input transaction signature did not verify"
                                )
                elif str(output.to) == str(address):
                    found = True
                    total_input += float(output.value)

            if not found:
                if hasattr(txn, 'public_key') and hasattr(txn, 'signature'):
                    raise InvalidTransactionException(
                        "external input signing information did not match any recipients of the input transaction"
                    )
                else:
                    raise InvalidTransactionException(
                        "using inputs from a transaction where you were not one of the recipients."
                    )

        if self.coinbase:
            return

        total_output = 0
        for txn in self.outputs:
            total_output += float(txn.value)
        total = float(total_output) + float(self.fee)
        if "{0:.8f}".format(total_input) != "{0:.8f}".format(total):
            raise BaseException(
                "inputs and outputs sum must match %s, %s, %s, %s" %
                (total_input, float(total_output), float(self.fee), total))
예제 #26
0
    async def verify(self):
        verify_hash = await self.generate_hash()
        address = P2PKHBitcoinAddress.from_pubkey(
            bytes.fromhex(self.public_key))

        if verify_hash != self.hash:
            raise InvalidTransactionException("transaction is invalid")

        try:
            result = verify_signature(
                base64.b64decode(self.transaction_signature),
                self.hash.encode('utf-8'), bytes.fromhex(self.public_key))
            if not result:
                print("t verify1")
                raise Exception()
        except:
            try:
                result = VerifyMessage(address,
                                       BitcoinMessage(self.hash, magic=''),
                                       self.transaction_signature)
                if not result:
                    print("t verify2")
                    raise
            except:
                print("t verify3")
                raise InvalidTransactionSignatureException(
                    "transaction signature did not verify")

        if len(self.relationship) > 20480:
            raise MaxRelationshipSizeExceeded(
                'Relationship field cannot be greater than 2048 bytes')

        # verify spend
        total_input = 0
        exclude_recovered_ids = []
        async for txn in self.get_inputs(self.inputs):
            input_txn = self.config.BU.get_transaction_by_id(txn.id)
            if input_txn:
                txn_input = Transaction.from_dict(input_txn)
            if not input_txn:
                if self.extra_blocks:
                    txn_input = await self.find_in_extra_blocks(txn)
                if not txn_input:
                    result = await self.recover_missing_transaction(
                        txn.id, exclude_recovered_ids)
                    exclude_recovered_ids.append(exclude_recovered_ids)
                    raise MissingInputTransactionException(
                        "Input not found on blockchain: {}".format(txn.id))

            found = False
            for output in txn_input.outputs:
                if isinstance(txn, ExternalInput):
                    ext_address = P2PKHBitcoinAddress.from_pubkey(
                        bytes.fromhex(txn_input.public_key))
                    int_address = P2PKHBitcoinAddress.from_pubkey(
                        bytes.fromhex(txn.public_key))
                    if str(output.to) == str(ext_address) and str(
                            int_address) == str(txn.address):
                        try:
                            result = verify_signature(
                                base64.b64decode(txn.signature),
                                txn.id.encode('utf-8'),
                                bytes.fromhex(txn_input.public_key))
                            if not result:
                                print("t verify4")
                                raise Exception()
                        except:
                            try:
                                result = VerifyMessage(
                                    ext_address,
                                    BitcoinMessage(txn.id, magic=''),
                                    txn.signature)
                                if not result:
                                    print("t verify5")
                                    raise
                            except:
                                raise InvalidTransactionSignatureException(
                                    "external input transaction signature did not verify"
                                )

                        found = True
                        total_input += float(output.value)
                elif str(output.to) == str(address):
                    found = True
                    total_input += float(output.value)

            if not found:
                if isinstance(txn, ExternalInput):
                    raise InvalidTransactionException(
                        "external input signing information did not match any recipients of the input transaction"
                    )
                else:
                    raise InvalidTransactionException(
                        "using inputs from a transaction where you were not one of the recipients."
                    )

        if self.coinbase:
            return

        total_output = 0
        for txn in self.outputs:
            total_output += float(txn.value)
        total = float(total_output) + float(self.fee)
        if fix_float1(total_input) != fix_float1(total) and fix_float2(
                total_input) != fix_float2(total):
            raise TotalValueMismatchException(
                "inputs and outputs sum must match %s, %s, %s, %s" %
                (total_input, float(total_output), float(self.fee), total))
예제 #27
0
파일: app.py 프로젝트: xeagu/PepeVote
def submit_message():
    message = ''
    signature = ''

    if 'message' in request.form: message = request.form['message']
    if 'signature' in request.form: signature = request.form['signature']

    if message == "" or signature == "":
        registration_error = 'Message/Signature is missing'
        return render_template('create_submission.html',
                               registration_error=registration_error)

    else:
        # TODO: Change 'image hash' to 'hash' for terseness
        # TODO: Change status to error for readability?

        # First, check if all relevant fields have been provided to the signed message.
        # If you don't do this, things die with malformed input.

        try:
            message_object = json.loads(message)
        except:
            print("errored.")
            registration_error = 'message is not properly formatted JSON'
            return render_template('create_submission.html',
                                   registration_error=registration_error)

        try:
            address = message_object['address']
            asset = message_object['asset']
            hash = message_object['image_hash']
            block = message_object['block']

        except:

            if not 'address' in message_object:
                registration_error = 'Address field is missing.'

            if not 'asset' in message_object:
                registration_error = 'Asset field is missing.'

            if not 'image_hash' in message_object:
                registration_error = 'Hash field is missing.'
                return render_template('create_submission.html',
                                       registration_error=registration_error,
                                       message=message)

            if not 'block' in message_object:
                registration_error = 'Block field is missing.'

            return render_template('create_submission.html',
                                   registration_error=registration_error,
                                   hash=hash,
                                   message=message)

        data = BitcoinMessage(message)
        verified = VerifyMessage(address, data, signature)

        if not verified:
            registration_error = 'Verification failed.'
            return render_template('create_submission.html',
                                   registration_error=registration_error,
                                   message=message,
                                   hash=hash)

        else:
            conn = sqlite3.connect('pepevote.db')
            c = conn.cursor()

            # Check if this is a duplicate entry
            c.execute(
                'SELECT * FROM verified_messages WHERE hash=? OR asset=?',
                (hash, asset))
            entry = c.fetchone()
            conn.close()

            if entry:
                registration_error = 'This asset or image has already been submitted this week.'
                return render_template('create_submission.html',
                                       registration_error=registration_error,
                                       hash=hash,
                                       message=message)

            else:  # Entry is not a duplicate

                # Check if address actually owns the asset in question
                if not owns_asset(address, asset):
                    registration_error = 'The provided address does not have the provided asset.'
                    return render_template(
                        'create_submission.html',
                        registration_error=registration_error,
                        hash=hash,
                        message=message)

                # Check if the burn fee is paid
                paid = False

                candidates = get_candidates(512000, 520000)

                for candidate in candidates:
                    if hash == candidate:
                        paid = True

                        # TODO: Check if anyone has ever used this hash before

                if not paid:
                    registration_error = 'Burn fee has not been paid.'
                    return render_template(
                        'create_submission.html',
                        registration_error=registration_error,
                        message=message,
                        hash=hash)

                # TODO: Check if the asset is a duplicate of an existing one

                # Check if hash matches an uploaded image
                match = False

                dir = 'uploads'
                submissions = os.listdir(dir)

                candidates = []
                for submission in submissions:
                    if not submission == "temp":
                        candidates.append(os.path.join(dir, submission))

                for candidate in candidates:
                    candidate_hash = sha256_checksum(candidate)

                    print(candidate)
                    print(candidate_hash)

                    if hash == candidate_hash:
                        match = True
                        submission_path = candidate

                if not match:
                    registration_error = 'No uploaded image has the provided hash.'
                    return render_template(
                        'create_submission.html',
                        registration_error=registration_error,
                        hash=hash,
                        message=message)

                location = os.path.join('static', 'submitted',
                                        submission_path[8:])
                os.rename(submission_path, location)

                conn = sqlite3.connect('pepevote.db')
                c = conn.cursor()

                tuple = (address, asset, hash, block, signature, location)
                c.execute(
                    "INSERT INTO verified_messages(address, asset, hash, block, signature, image) VALUES(?, ?, ?, ?, ?, ?)",
                    tuple)
                conn.commit()
                conn.close()

                success = 'Verification succeeded, your art has been registered.'

    try:
        return render_template('create_submission.html',
                               success=success,
                               hash=hash,
                               message=message)
    except:
        return render_template('create_submission.html')
예제 #28
0
파일: app.py 프로젝트: xeagu/PepeVote
def submit_vote():
    if request.method == 'GET':
        return render_template('submit_vote.html')

    else:
        signature = ''
        vote_string = ''

        if 'signature' in request.form: signature = request.form['signature']
        if 'vote_string' in request.form:
            vote_string = request.form['vote_string']

        if vote_string == "" or signature == "":
            status = 'Signature is missing.'
            return render_template('submit_vote.html',
                                   vote_string=vote_string,
                                   status=status)

        else:
            # TODO: Change 'image hash' to 'hash' for terseness
            # TODO: Change status to error for readability?

            # First, check if all relevant fields have been provided to the signed message.
            # If you don't do this, things die with malformed input.

            try:
                message_object = json.loads(vote_string)
            except:
                print("errored.")
                status = 'message is not properly formatted JSON'
                return render_template('submit_vote.html',
                                       vote_string=vote_string,
                                       status=status)

            try:
                address = message_object['address']
                block = message_object['block']
                votes = message_object['votes']

            except:

                if not 'address' in message_object:
                    status = 'Address field is missing.'

                if not 'votes' in message_object:
                    status = 'Votes field is missing.'

                if not 'block' in message_object:
                    status = 'Block field is missing.'

                return render_template('submit_vote.html',
                                       vote_string=vote_string,
                                       status=status)

            data = BitcoinMessage(vote_string)
            try:
                verified = VerifyMessage(address, data, signature)

            except:
                status = 'Verification failed - signature is malformed.'
                return render_template('submit_vote.html',
                                       status=status,
                                       vote_string=vote_string)

            if not verified:
                status = 'Verification failed.'
                return render_template('submit_vote.html',
                                       status=status,
                                       vote_string=vote_string)

            else:
                conn = sqlite3.connect('pepevote.db')
                c = conn.cursor()

                # Check if this is a duplicate entry
                c.execute('SELECT * FROM votes WHERE address=?', (address, ))
                entry = c.fetchone()
                conn.close()
                #             (address text PRIMARY KEY, block text, votes text, signature text)''')

                if entry is not None:
                    # Check block height to see if message is reused
                    (_, old_block, _, _) = entry

                    if block <= old_block:
                        print("Reusing old message")
                        status = 'Error: reused old vote'
                        return render_template('submit_vote.html',
                                               status=status,
                                               vote_string=vote_string)

                conn = sqlite3.connect('pepevote.db')
                c = conn.cursor()

                tuple = (address, block, str(votes), signature)
                c.execute(
                    "INSERT OR REPLACE INTO votes(address, block, votes, signature) VALUES(?, ?, ?, ?)",
                    tuple)
                conn.commit()
                conn.close()

                print('Vote submitted successfully')

                status = 'Vote submitted successfully.'
                return render_template('submit_vote.html',
                                       vote_string=vote_string,
                                       status=status)
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-bitcoinlib, including this file, may be copied, modified,
# propagated, or distributed except according to the terms contained in the
# LICENSE file.

from __future__ import absolute_import, division, print_function, unicode_literals

from bitcoin.wallet import CBitcoinSecret, P2PKHBitcoinAddress
from bitcoin.signmessage import BitcoinMessage, VerifyMessage, SignMessage

key = CBitcoinSecret("L4vB5fomsK8L95wQ7GFzvErYGht49JsCPJyJMHpB4xGM6xgi2jvG")
address = P2PKHBitcoinAddress.from_pubkey(
    key.pub)  # "1F26pNMrywyZJdr22jErtKcjF8R3Ttt55G"
message = "Hey I just met you, and this is crazy, but I'll verify my address, maybe ..."

message = BitcoinMessage(message)

signature = SignMessage(key, message)

print(key, address)
print("Address: %s" % address)
print("Message: %s", message)
print("\nSignature: %s" % signature)
print("\nVerified: %s" % VerifyMessage(address, message, signature))

print("\nTo verify using bitcoin core;")
print("`bitcoin-cli verifymessage %s \"%s\" \"%s\"`" %
      (address, signature.decode('ascii'), message))
예제 #30
0
 def verifySignature(address, signature, message):
     msg = BitcoinMessage(message)
     return VerifyMessage(address, msg, signature)