예제 #1
0
def cert_issuer_main(args=None):
    from cert_issuer import config
    parsed_config = config.get_config()
    from cert_issuer import issue_certificates, trx_utils
    trx_utils.set_cost_constants(parsed_config.tx_fee,
                                 parsed_config.dust_threshold,
                                 parsed_config.satoshi_per_byte)
    issue_certificates.main(parsed_config)
예제 #2
0
def cert_issuer_main(args=None):

    from cert_issuer import config
    parsed_config = config.get_config()
    from cert_issuer import issue_certificates
    pr = cProfile.Profile()
    pr.enable()
    issue_certificates.main(parsed_config)
    pr.disable()
    # after your program ends
    pr.print_stats(sort="tottime")
    pr.dump_stats('profile.pstat')
예제 #3
0
def issue_certificates(export_path):
    try:
        parsed_config = config.get_config(os.path.abspath('../configuration/cert_issuer_conf.ini'))
        tx_id = isu.main(parsed_config)
        if tx_id:
            logging.info('Transaction id is %s', tx_id)
        else:
            logging.error('Certificate issuing failed')
            exit(1)

    except Exception as ex:
        logging.error(ex, exc_info=True)
        exit(1)
예제 #4
0
def check_internet_on():
    """If internet off and USB plugged in, returns true. Else, continues to wait..."""
    if config.get_config().skip_wifi_check:
        logging.warning(
            'app is configured to skip the wifi check when the USB is plugged in. Read the documentation to'
            ' ensure this is what you want, since this is less secure')
        return True
    while 1:
        if internet_on() is True and not os.path.exists(secrets_file_path):
            break
        else:
            print("Turn on your internet and unplug your USB to continue...")
            time.sleep(10)
    return True
예제 #5
0
    def setUp(self):
        config.get_config().skip_wifi_check = True
        mock = MagicMock()
        mock.uid = '34we3434'
        mock.name = 'Some Name'
        mock.pubkey = '123452'
        mock.unsigned_certificate_file_name = 'test/unsigned.json'
        mock.signed_certificate_file_name = 'test/signed.json'
        mock.certificate_hash_file_name = 'test/hashed.txt'
        mock.unsigned_tx_file_name = 'test/unsigned_tx.txt'
        mock.unsent_tx_file_name = 'test/unsent_tx.txt'
        mock.sent_tx_file_name = 'test/sent_tx.txt'

        self.mock_config = mock
예제 #6
0
import time
import shutil
import sys

import glob2
import requests
from cert_issuer import config

unhexlify = binascii.unhexlify
hexlify = binascii.hexlify
if sys.version > '3':
    unhexlify = lambda h: binascii.unhexlify(h.encode('utf8'))
    hexlify = lambda b: binascii.hexlify(b).decode('utf8')

secrets_file_path = os.path.join(
    config.get_config().usb_name, config.get_config().key_file)


def internet_off_for_scope(func):
    def func_wrapper(*args, **kwargs):
        check_internet_off()
        result = func(*args, **kwargs)
        check_internet_on()

    return func_wrapper


def import_key():
    with open(secrets_file_path) as key_file:
        key = key_file.read().strip()
    return key
            transaction_cost - balance, issuing_address)
        logging.error(error_message)
        raise InsufficientFundsError(error_message)

    # issue the certificates on the blockchain
    logging.info('Issuing the certificates on the blockchain')
    issuer.issue_on_blockchain(revocation_address=revocation_address)

    blockcerts_tmp_dir = os.path.join(work_dir,
                                      helpers.BLOCKCHAIN_CERTIFICATES_DIR)
    if not os.path.exists(blockcerts_dir):
        os.makedirs(blockcerts_dir)
    for item in os.listdir(blockcerts_tmp_dir):
        s = os.path.join(blockcerts_tmp_dir, item)
        d = os.path.join(blockcerts_dir, item)
        shutil.copy2(s, d)

    logging.info('Your Blockchain Certificates are in %s', blockcerts_dir)
    return blockcerts_dir


if __name__ == '__main__':
    from cert_issuer import config

    try:
        parsed_config = config.get_config()
        main(parsed_config)
    except Exception as ex:
        logging.error(ex, exc_info=True)
        exit(1)
예제 #8
0
from cert_issuer import helpers
from cert_issuer.errors import UnverifiedTransactionError
from cert_issuer.helpers import internet_off_for_scope
from cert_issuer.models import TransactionCosts


COIN = 100000000           # satoshis in 1 btc
BYTES_PER_INPUT = 148      # assuming compressed public key
BYTES_PER_OUTPUT = 34
FIXED_EXTRA_BYTES = 10
OP_RETURN_BYTE_COUNT = 43  # our op_return output values always have the same length because they are SHA-256 hashes
cost_constants = config.get_constants()
RECOMMENDED_FEE = cost_constants.recommended_fee_per_transaction * COIN
MIN_PER_OUTPUT = cost_constants.min_per_output * COIN
SATOSHI_PER_BYTE = cost_constants.satoshi_per_byte
ALLOWABLE_WIF_PREFIXES = wif_prefix_for_netcode(config.get_config().netcode)


def create_trx(op_return_val, issuing_transaction_cost,
               issuing_address, tx_outs, tx_input):
    """

    :param op_return_val:
    :param issuing_transaction_cost:
    :param issuing_address:
    :param tx_outs:
    :param tx_input:
    :return:
    """
    cert_out = CMutableTxOut(0, CScript([OP_RETURN, op_return_val]))
    tx_ins = [CTxIn(COutPoint(tx_input.tx_hash, tx_input.tx_out_index))]
                          app_config.signed_certs_file_part,
                          batch_id)

    logging.info('Archiving sent transactions.')
    helpers.archive_files(app_config.sent_txs_file_pattern,
                          app_config.archive_path,
                          app_config.txs_file_part,
                          batch_id)

    logging.info('Archiving receipts.')
    helpers.archive_files(app_config.receipts_file_pattern,
                          app_config.archive_path,
                          app_config.receipts_file_part,
                          batch_id)

    logging.info('Archiving blockchain certificates.')
    helpers.archive_files(app_config.blockchain_certificates_file_pattern,
                          app_config.archive_path,
                          app_config.blockchain_certificates_file_part,
                          batch_id)

    archive_folder = os.path.join(app_config.archive_path, batch_id)
    logging.info('Your Blockchain Certificates are in %s', archive_folder)


if __name__ == '__main__':
    from cert_issuer import config

    parsed_config = config.get_config()
    main(parsed_config)
예제 #10
0
from pycoin.tx import Spendable

from cert_issuer import config
from cert_issuer.errors import ConnectorError
from cert_issuer.helpers import hexlify
from cert_issuer.helpers import unhexlify

try:
    from urllib2 import urlopen, HTTPError
    from urllib import urlencode
except ImportError:
    from urllib.request import urlopen, HTTPError
    from urllib.parse import urlencode


CONFIG_NETCODE = config.get_config().netcode

def try_get(url):
    """throw error if call fails"""
    response = requests.get(url)
    if int(response.status_code) != 200:
        error_message = 'Error! status_code={}, error={}'.format(
            response.status_code, response.json()['error'])
        logging.error(error_message)
        raise ConnectorError(error_message)
    return response


def to_hex(transaction):
    s = io.BytesIO()
    transaction.stream(s)
예제 #11
0
def cert_issuer_main(args=None):
    from cert_issuer import config
    parsed_config = config.get_config()
    from cert_issuer import issue_certificates
    issue_certificates.main(parsed_config)
예제 #12
0
from pycoin.services.providers import service_provider_methods
from pycoin.tx import Spendable

from cert_issuer import config
from cert_issuer.errors import ConnectorError
from cert_issuer.helpers import hexlify
from cert_issuer.helpers import unhexlify

try:
    from urllib2 import urlopen, HTTPError
    from urllib import urlencode
except ImportError:
    from urllib.request import urlopen, HTTPError
    from urllib.parse import urlencode

CONFIG_NETCODE = config.get_config().netcode


def try_get(url):
    """throw error if call fails"""
    response = requests.get(url)
    if int(response.status_code) != 200:
        error_message = 'Error! status_code={}, error={}'.format(
            response.status_code,
            response.json()['error'])
        logging.error(error_message)
        raise ConnectorError(error_message)
    return response


def to_hex(transaction):
예제 #13
0
def issue_certificates(pubkey):
    config_logger()

    print()
    logging.info('Trying to acquire file lock ...')

    bypass = False

    file = open(get_latest_transaction_file_dir(), 'r+')
    fcntl.flock(file.fileno(), fcntl.LOCK_EX)
    logging.info('Lock acquired ...')

    tx_id = ''
    successful = False
    latest_transaction = file.readline()
    chain_latest = ''

    count = 0

    if latest_transaction == '':
        bypass = True

    if bypass:
        logging.info('The latest transaction check is bypassed ...')
    else:
        logging.info('Waiting the latest transaction to be confirmed ...')
        while get_confirmation(latest_transaction, TOKEN) == 0:
            logging.info('No confirmation yet. Will retry ...')
            count += 1
            if count >= 1000:  # timeout
                file.close()
                raise Exception('Waiting timeout.')
            request_sleep(TOKEN)
        count = 0
        while True:
            count += 1
            chain_latest = get_latest_transaction(pubkey, TOKEN)
            if chain_latest != 'retry':
                break
            if count >= 1000:
                file.close()
                raise Exception('Waiting timeout.')
            request_sleep(TOKEN)
        logging.info('Passed')

    if chain_latest in latest_transaction or bypass:
        if not bypass:
            logging.info('Latest transaction authenticity check passed ...')
        try:
            parsed_config = config.get_config(get_issuer_conf_dir(TOKEN))
            tx_id = isu.main(parsed_config)
            if tx_id:
                logging.info('Transaction id is %s', tx_id)
                file.seek(0)
                file.write(tx_id)
                successful = True
            else:
                logging.error('Certificate issuing failed')
                file.close()
        except Exception as ex:
            logging.error(ex, exc_info=True)
            file.close()
            return [tx_id, successful]
    else:
        logging.error(
            'Latest transaction authenticity check failed ... The public key is possibly stolen by someone else, please change a public key.'
        )
        file.close()

    return [tx_id, successful, file]
예제 #14
0
import shutil
import sys
import time

import glob2
import requests

from cert_issuer import config, models

unhexlify = binascii.unhexlify
hexlify = binascii.hexlify
if sys.version > '3':
    unhexlify = lambda h: binascii.unhexlify(h.encode('utf8'))
    hexlify = lambda b: binascii.hexlify(b).decode('utf8')

secrets_file_path = os.path.join(config.get_config().usb_name,
                                 config.get_config().key_file)


def internet_off_for_scope(func):
    """
    Wraps func with check that internet is off, then on after the call to func
    :param func:
    :return:
    """
    def func_wrapper(*args, **kwargs):
        check_internet_off()
        result = func(*args, **kwargs)
        check_internet_on()
        return result