Exemplo n.º 1
0
def verify_certificate():
    document = get_document(request)

    proof = request.json.get('proof')

    if proof is None:
        abort_by_missing_param('proof')

    spec = proof['spec']
    subtree = proof['subtree']

    # private key can be None as it is unused for viewing blockchain.
    eth = bbc_ethereum.BBcEthereum(spec['network'],
                                   private_key=None,
                                   contract_address=spec['contract_address'],
                                   project_dir=bbc1.__path__[0] +
                                   '/core/ethereum')

    digest = hashlib.sha256(document.file()).digest()

    block_no, root = eth.verify_and_get_root(digest, subtree)

    if block_no <= 0:
        abort_by_merkle_root_not_found()

    block = network.web3.eth.getBlock(block_no)

    return jsonify({
        'network': spec['network'],
        'contract_address': spec['contract_address'],
        'block': block_no,
        'root': binascii.b2a_hex(root).decode(),
        'time': block['timestamp']
    })
Exemplo n.º 2
0
def test_setup_deploy(default_config):

    setup.setup_deploy(default_config)

    prevdir = os.getcwd()
    dir = os.path.dirname(os.path.realpath(__file__))
    os.chdir(dir)
    os.chdir('../bbc1/core/' + bbc_config.DEFAULT_WORKING_DIR)

    f = open(TEST_CONFIG_FILE, 'r')
    config = json.load(f)
    f.close()

    address = config['ethereum']['contract_address']

    assert address[0:2] == '0x'
    assert len(address) == 42

    os.chdir('../ethereum')

    eth = bbc_ethereum.BBcEthereum(config['ethereum']['account'],
                                   config['ethereum']['passphrase'], address)

    eth.blockingSet(0x1234)

    assert eth.test(0x1230) == 0
    assert eth.test(0x1234) > 0

    eth.blockingSet(b'\x43\x21')

    assert eth.test(0x4321) > 0
    assert eth.test(b'\x43\x21') > 0

    os.chdir(prevdir)
    print("\n==> BBcAnchor is deployed and tested.")
Exemplo n.º 3
0
    def enable(self):
        """Enables communication with the underlying ledger.

        """

        if self.config['ledger_subsystem']['subsystem'] == 'ethereum':
            prevdir = os.getcwd()
            if not os.path.exists('ethereum/contracts/BBcAnchor.sol'):
                os.chdir(os.path.dirname(os.path.realpath(__file__)))
            os.chdir('ethereum')
            os.environ['WEB3_INFURA_PROJECT_ID'] = \
                    self.eth_config['web3_infura_project_id']
            try:
                self.eth = bbc_ethereum.BBcEthereum(
                    self.eth_config['network'], self.eth_config['private_key'],
                    self.eth_config['contract_address'])
            except:
                os.chdir(prevdir)
                raise
            os.chdir(prevdir)
        else:
            self.logger.error("Currently, Ethereum only is supported.")
            os.exit(1)
        self.timer = threading.Timer(self.interval, self.subsystem_timer)
        self.timer.start()
        self.enabled = True
        self.logger.debug("enabled")
    def enable(self):
        """
        Enables communication with the underlying ledger.

        :return:
        """
        if self.config['ledger_subsystem']['subsystem'] == 'ethereum':
            prevdir = os.getcwd()
            if not os.path.exists('ethereum/contracts/BBcAnchor.sol'):
                os.chdir(os.path.dirname(os.path.realpath(__file__)))
            os.chdir('ethereum')
            try:
                self.eth = bbc_ethereum.BBcEthereum(
                    self.eth_config['account'], self.eth_config['passphrase'],
                    self.eth_config['contract_address'])
            except:
                os.chdir(prevdir)
                raise
            os.chdir(prevdir)
        else:
            self.logger.error("Currently, Ethereum only is supported.")
            os.exit(1)
        self.timer = threading.Timer(self.interval, self.subsystem_timer)
        self.timer.start()
        self.enabled = True
        self.logger.debug("enabled")
Exemplo n.º 5
0
def test_setup_deploy(default_config):

    bbc_ethereum.setup_deploy(default_config)

    prevdir = os.getcwd()
    os.chdir(bbc1.__path__[0] + '/core/' + bbc_config.DEFAULT_WORKING_DIR)

    f = open(TEST_CONFIG_FILE, 'r')
    config = json.load(f)
    f.close()

    address = config['ethereum']['contract_address']

    assert address[0:2] == '0x'
    assert len(address) == 42

    os.chdir('../ethereum')

    eth = bbc_ethereum.BBcEthereum(config['ethereum']['account'],
                                   config['ethereum']['passphrase'], address)

    print("\ncontract has been deployed; setting a value.")
    eth.blockingSet(0x1234)

    assert eth.test(0x1230) == 0
    assert eth.test(0x1234) > 0

    print("value has been set; setting another value.")
    eth.blockingSet(b'\x43\x21')

    assert eth.test(0x4321) > 0
    assert eth.test(b'\x43\x21') > 0

    os.chdir(prevdir)
    print("==> BBcAnchor is deployed and tested.")
Exemplo n.º 6
0
    def enable(self):
        """
        Enables communication with the underlying ledger.

        :return:
        """
        if self.config['ledger_subsystem']['subsystem'] == 'ethereum':
            prevdir = os.getcwd()
            os.chdir('ethereum')
            self.eth = bbc_ethereum.BBcEthereum(
                self.config['ethereum']['account'],
                self.config['ethereum']['passphrase'],
                self.config['ethereum']['contract_address'])
            os.chdir(prevdir)
        else:
            self.logger.error("Currently, Ethereum only is supported.")
            os.exit(1)
        self.timer = threading.Timer(self.interval, self.subsystem_timer)
        self.timer.start()
        self.enabled = True
Exemplo n.º 7
0
def test_ledger_subsystem(default_config):

    setup.setup_run(default_config)

    prevdir = os.getcwd()
    dir = os.path.dirname(os.path.realpath(__file__))
    os.chdir(dir)
    os.chdir('../bbc1/core/ethereum')

    conf = default_config.get_config()
    eth = bbc_ethereum.BBcEthereum(conf['ethereum']['account'],
                                   conf['ethereum']['passphrase'],
                                   conf['ethereum']['contract_address'])

    os.chdir('..')

    ls = ledger_subsystem.LedgerSubsystem(default_config, enabled=True)

    for i in range(150):
        ls.register_transaction(None,
                                hashlib.sha256(i.to_bytes(4, 'big')).digest())
        time.sleep(0.1)

    time.sleep(30)

    i = 300
    j = ls.verify_transaction(None,
                              hashlib.sha256(i.to_bytes(4, 'big')).digest())

    assert j['result'] == False

    for i in range(150):
        digest = hashlib.sha256(i.to_bytes(4, 'big')).digest()
        j = ls.verify_transaction(None, digest)
        assert j['result'] == True
        assert eth.verify(digest, j['subtree']) > 0

    os.chdir(prevdir)

    setup.setup_stop(default_config)
    def _verify_by_subsystem(self, args, digest, spec, subtree):

        if spec[b'subsystem'] != b'ethereum':
            print("Failed: not stored in an Ethereum subsystem.")
            return 0

        bbcConfig = bbc_ethereum.setup_config(args.workingdir, args.config,
                                              args.networkid, args.gethport,
                                              args.log)
        config = bbcConfig.get_config()

        prevdir = os.getcwd()
        os.chdir(bbc1.__path__[0] + '/core/ethereum')

        eth = bbc_ethereum.BBcEthereum(
            config['ethereum']['account'],
            config['ethereum']['passphrase'],
            contract_address=spec[b'contract_address'])

        os.chdir(prevdir)

        return eth.verify(digest, subtree)
Exemplo n.º 9
0
    def _verify_by_subsystem(self, args, digest, spec, subtree):

        if spec[b'subsystem'] != b'ethereum':
            print("Failed: not stored in an Ethereum subsystem.")
            return 0

        bbcConfig = bbc_ethereum.setup_config(args.workingdir, args.config,
                                              args.network)
        config = bbcConfig.get_config()

        prevdir = os.getcwd()
        os.chdir(bbc1.__path__[0] + '/core/ethereum')
        os.environ['WEB3_INFURA_PROJECT_ID'] = \
                config['ethereum']['web3_infura_project_id']

        eth = bbc_ethereum.BBcEthereum(
            config['ethereum']['network'],
            config['ethereum']['private_key'],
            contract_address=spec[b'contract_address'].decode('utf-8'))

        os.chdir(prevdir)

        return eth.verify(digest, subtree)
Exemplo n.º 10
0
Arquivo: setup.py Projeto: y-sira/bbc1
def setup_deploy(bbcConfig):
    """
    Deploys BBcAnchor contract to Ethereum ledger subsystem.

    :param bbcConfig: configuration object
    :return:
    """
    prevdir = os.getcwd()
    dirpath = os.path.dirname(os.path.realpath(__file__))
    os.chdir(dirpath)

    config = bbcConfig.get_config()
    bbcEthereum = bbc_ethereum.BBcEthereum(config['ethereum']['account'],
                                           config['ethereum']['passphrase'])

    contract_address = config['ethereum']['contract_address']
    if contract_address != '':
        config['ethereum']['previous_contract_address'] = contract_address

    config['ethereum']['contract_address'] = bbcEthereum.get_contract_address()
    os.chdir('..')
    bbcConfig.update_config()

    os.chdir(prevdir)
Exemplo n.º 11
0
def test_ledger_subsystem(default_config):

    setup.setup_run(default_config)

    prevdir = os.getcwd()
    dir = os.path.dirname(os.path.realpath(__file__))
    os.chdir(dir)
    os.chdir('../bbc1/core/ethereum')

    conf = default_config.get_config()
    print(conf)
    eth = bbc_ethereum.BBcEthereum(conf['ethereum']['account'],
                                   conf['ethereum']['passphrase'],
                                   conf['ethereum']['contract_address'])

    os.chdir('..')

    networking = bbc_network.BBcNetwork(core=DummyCore(),
                                        config=conf,
                                        p2p_port=6641)
    networking.create_domain(domain_id=domain_id1)

    ls = ledger_subsystem.LedgerSubsystem(conf,
                                          networking=networking,
                                          domain_id=domain_id1,
                                          enabled=True)

    for i in range(150):
        ls.register_transaction(hashlib.sha256(i.to_bytes(4, 'big')).digest())

        time.sleep(0.1)

    time.sleep(30)

    i = 300
    j = ls.verify_transaction(hashlib.sha256(i.to_bytes(4, 'big')).digest())

    assert not j['result']

    for i in range(150):
        digest = hashlib.sha256(i.to_bytes(4, 'big')).digest()
        j = ls.verify_transaction(digest)
        assert j['result']
        assert eth.verify(digest, j['subtree']) > 0

    # -- test in another domain
    networking.create_domain(domain_id=domain_id2)
    ls = ledger_subsystem.LedgerSubsystem(conf,
                                          networking=networking,
                                          domain_id=domain_id2,
                                          enabled=True)

    i = 100
    j = ls.verify_transaction(hashlib.sha256(i.to_bytes(4, 'big')).digest())

    assert not j['result']

    i = 99
    digest = hashlib.sha256(i.to_bytes(4, 'big')).digest()
    ls.register_transaction(digest)

    time.sleep(31)

    j = ls.verify_transaction(digest)
    assert j['result']
    assert eth.verify(digest, j['subtree']) > 0

    setup.setup_stop(default_config)
Exemplo n.º 12
0
def test_ledger_subsystem(default_config):

    bbc_ethereum.setup_run(default_config)

    prevdir = os.getcwd()
    os.chdir(bbc1.__path__[0] + '/core/ethereum')

    conf = default_config.get_config()
    eth = bbc_ethereum.BBcEthereum(conf['ethereum']['account'],
                                   conf['ethereum']['passphrase'],
                                   conf['ethereum']['contract_address'])

    os.chdir('..')

    networking = bbc_network.BBcNetwork(core=DummyCore(),
                                        config=default_config,
                                        p2p_port=6641)
    networking.create_domain(domain_id=domain_id1)

    ls = ledger_subsystem.LedgerSubsystem(default_config,
                                          networking=networking,
                                          domain_id=domain_id1,
                                          enabled=True)

    for i in range(150):
        ls.register_transaction(hashlib.sha256(i.to_bytes(4, 'big')).digest())

    print("\n30-second interval for trigger Merkle tree creation.")
    for i in range(6, 0, -1):
        print("continuing to sleep. countdown", i)
        time.sleep(5)

    i = 300
    j = ls.verify_transaction(hashlib.sha256(i.to_bytes(4, 'big')).digest())

    assert not j['result']

    for i in range(150):
        digest = hashlib.sha256(i.to_bytes(4, 'big')).digest()
        j = ls.verify_transaction(digest)
        assert j['result']
        assert eth.verify(digest, j['subtree']) > 0

    # -- test in another domain
    networking.create_domain(domain_id=domain_id2)
    ls = ledger_subsystem.LedgerSubsystem(default_config,
                                          networking=networking,
                                          domain_id=domain_id2,
                                          enabled=True)

    i = 100
    j = ls.verify_transaction(hashlib.sha256(i.to_bytes(4, 'big')).digest())

    assert not j['result']

    i = 99
    digest = hashlib.sha256(i.to_bytes(4, 'big')).digest()
    ls.register_transaction(digest)

    print("31-second interval for trigger Merkle tree creation.")
    time.sleep(1)
    for i in range(6, 0, -1):
        print("continuing to sleep. countdown", i)
        time.sleep(5)

    j = ls.verify_transaction(digest)
    assert j['result']
    assert eth.verify(digest, j['subtree']) > 0

    os.chdir(prevdir)
    bbc_ethereum.setup_stop(default_config)
Exemplo n.º 13
0
    def verify(self, certificate):

        print("certificate id: {0}".format(certificate.id))

        if self.is_verbose:
            print("xml: {0}".format(
                ET.tostring(certificate.document.root,
                            encoding='utf-8').decode('utf-8')))

        try:
            dic = self.get_verification_dict(certificate)

        except ValueError as error:
            print("Failed: {0}".format(str(error)))
            return

        except KeyError as error:
            print("Failed: algorithm {0} not supported".format(str(error)))
            return

        if dic is None:
            print("Failed: not registered.")
            return

        if dic == {}:
            print("Failed: ledger subsystem is not enabled.")
            return

        if dic[b'result'] == False:
            print("Failed: document digest is not found.")
            return

        spec = dic[b'spec']
        if spec[b'subsystem'] != b'ethereum':
            print("Failed: not stored in an Ethereum subsystem.")
            return

        if self.is_test:
            return

        subtree = dic[b'subtree']

        bbcConfig = bbc_config.BBcConfig(
            self.workingdir,
            os.path.join(self.workingdir, bbc_config.DEFAULT_CONFIG_FILE))
        config = bbcConfig.get_config()

        prevdir = os.getcwd()
        os.chdir(bbc1.__path__[0] + '/core/ethereum')

        eth = bbc_ethereum.BBcEthereum(
            config['ethereum']['network'],
            config['ethereum']['private_key'],
            contract_address=spec[b'contract_address'].decode('utf-8'))

        os.chdir(prevdir)

        digest = self.registry.get_document_digest(
            certificate.document.document_id)

        block_no = eth.verify(digest, subtree)

        if block_no <= 0:
            print("Failed: document digest is not found.")

        else:
            block = network.web3.eth.getBlock(block_no)
            print("Verified at: block {0}".format(block_no))
            print("Date-Time: {0}".format(
                datetime.datetime.fromtimestamp(block['timestamp'])))
Exemplo n.º 14
0
def certify(cert_xml, subtree_string):

    if cert_xml is None or subtree_string is None:
        return failure_template('no-query')

    try:
        root = ET.fromstring(cert_xml)

    except ET.ParseError:
        return failure_template('xml-syntax')

    try:
        data = registry_lib.file(root)

    except ValueError as error:
        s = str(error)
        if s.startswith('pubkey'):
            return failure_template('no-pubkey', root=root)
        elif s.startswith('sig'):
            return failure_template('bad-sig', root=root)

    except KeyError as error:
        return failure_template('sig-algo', root=root)

    digest = hashlib.sha256(data).digest()

    subtree = []
    nodes = subtree_string.split(':')

    for node in nodes:
        s = node.split('-')
        if len(s) != 2 or not all(c in string.hexdigits for c in s[1]):
            return failure_template('subtree-syntax', root=root)
        dic = {}
        dic['position'] = 'right' if s[0] == 'r' else 'left'
        dic['digest'] = s[1]
        subtree.append(dic)

    eth = bbc_ethereum.BBcEthereum(S_NETWORK,
                                   private_key=None,
                                   contract_address=S_CONTRACT_ADDRESS,
                                   project_dir=bbc1.__path__[0] +
                                   '/core/ethereum')

    block_no, digest0 = eth.verify_and_get_root(digest, subtree)

    if block_no <= 0:
        return failure_template('digest-mismatch', root=root)

    block = network.web3.eth.getBlock(block_no)

    realtime = datetime.datetime.fromtimestamp(block['timestamp'])

    return render_template('cert/success.html',
                           title='Certificate Vefirication - Success',
                           root=root,
                           network=S_NETWORK,
                           contract=S_CONTRACT_ADDRESS,
                           block_no=block_no,
                           realtime=realtime,
                           get_date_string=get_date_string,
                           merkle_root=binascii.b2a_hex(digest0).decode())