def create_signup_info(cls, originator_public_key_hash,
                           most_recent_wait_certificate_id):
        with cls._lock:
            # First we need to create a public/private key pair for the PoET
            # enclave to use.
            cls._poet_private_key = pybitcointools.random_key()
            cls._poet_public_key = \
                pybitcointools.privtopub(cls._poet_private_key)
            cls._active_wait_timer = None

            # We are going to fake out the sealing the signup data.
            signup_data = {
                'poet_public_key':
                pybitcointools.encode_pubkey(cls._poet_public_key, 'hex'),
                'poet_private_key':
                pybitcointools.encode_privkey(cls._poet_private_key, 'hex')
            }
            sealed_signup_data = \
                pybitcointools.base64.b64encode(dict2json(signup_data))

            # Create a fake report
            report_data = {
                'originator_public_key_hash':
                originator_public_key_hash.upper(),
                'poet_public_key':
                pybitcointools.encode_pubkey(cls._poet_public_key,
                                             'hex').upper()
            }
            report = {
                'report_data': pybitcointools.sha256(dict2json(report_data))
            }

            # Fake our "proof" data.
            verification_report = {
                'enclave_quote':
                pybitcointools.base64.b64encode(dict2json(report)),
                'pse_manifest_hash':
                pybitcointools.base64.b64encode(
                    pybitcointools.sha256('manifest destiny')),
                'nonce':
                most_recent_wait_certificate_id
            }

            proof_data = {
                'verification_report':
                dict2json(verification_report),
                'signature':
                pybitcointools.ecdsa_sign(dict2json(verification_report),
                                          cls._report_private_key)
            }
            proof_data_dict = dict2json(proof_data)

            return \
                EnclaveSignupInfo(
                    poet_public_key=signup_data['poet_public_key'],
                    proof_data=proof_data_dict,
                    anti_sybil_id=originator_public_key_hash,
                    sealed_signup_data=sealed_signup_data)
Exemplo n.º 2
0
def sign_message_with_transaction(transaction, key):
    """
    Signs a transaction message or transaction
    :param transaction dict:
    :param key str: A signing key
    returns message, txnid tuple: The first 16 characters
    of a sha256 hexdigest.
    """
    transaction['Nonce'] = time.time()
    pub = pybitcointools.encode_pubkey(pybitcointools.privkey_to_pubkey(key),
                                       "hex")
    transaction["public_key"] = pub
    sig = pybitcointools.ecdsa_sign(
        dict2cbor(transaction),
        key
    )
    transaction['Signature'] = sig

    txnid = hashlib.sha256(transaction['Signature']).hexdigest()[:16]
    message = {
        'Transaction': transaction,
        '__TYPE__': "/mktplace.transactions.MarketPlace/Transaction",
        '__NONCE__': time.time(),
    }
    cbor_serialized_mess = dict2cbor(message)
    signature = pybitcointools.ecdsa_sign(
        cbor_serialized_mess,
        key
    )
    message['__SIGNATURE__'] = signature
    return message, txnid
    def test_register_permissioned_validator_invalid(self):
        signing_key = signed_object.generate_signing_key()

        unpermissiond_private_key = signed_object.generate_signing_key()
        pub_key = pybitcointools.encode_pubkey(
            pybitcointools.privtopub(unpermissiond_private_key), 'hex')
        permissioned_public_keys = [pub_key]

        addr = signed_object.generate_identifier(unpermissiond_private_key)
        permissioned_addrs = [addr]

        update = {
            'whitelist_name': "hyperledger.sawtooth-core.genesis-whitelist",
            'verb': 'reg',
            'permissioned_public_keys': permissioned_public_keys,
            'permissioned_addrs': permissioned_addrs
        }
        minfo = {'Update': update}

        transaction = PermissionedValidatorRegistryTransaction(minfo)
        transaction.sign_object(signing_key)

        store = ObjectStore()
        with self.assertRaises(InvalidTransactionError):
            transaction.check_valid(store)
            self.fail("Failure: Verified an invalid transaction")
    def test_register_validator_key_mismatch(self):
        key = signed_object.generate_signing_key()
        public_key_hash = \
            hashlib.sha256(
                pybitcointools.encode_pubkey(
                    pybitcointools.privtopub(key),
                    'hex')).hexdigest()
        key2 = signed_object.generate_signing_key()
        validator_id = signed_object.generate_identifier(key)
        name = 'DasValidator'
        signup_info = \
            SignupInfo.create_signup_info(
                originator_public_key_hash=public_key_hash,
                most_recent_wait_certificate_id='0' * 16)

        store = ObjectStore()
        transaction = \
            ValidatorRegistryTransaction.register_validator(
                name,
                validator_id,
                signup_info)
        transaction.sign_object(key2)
        with self.assertRaises(InvalidTransactionError):
            transaction.check_valid(store)
            self.fail("Failure: Verified an invalid transaction")
Exemplo n.º 5
0
 def setUpClass(cls):
     cls._originator_public_key = cls._create_random_public_key()
     cls._originator_public_key_hash = \
         hashlib.sha256(
             pybitcointools.encode_pubkey(
                 cls._originator_public_key,
                 'hex')).hexdigest()
    def test_register_validator_re_register(self):
        key = signed_object.generate_signing_key()
        public_key_hash = \
            hashlib.sha256(
                pybitcointools.encode_pubkey(
                    pybitcointools.privtopub(key),
                    'hex')).hexdigest()
        validator_id = signed_object.generate_identifier(key)
        name = 'DasValidator'
        signup_info = \
            SignupInfo.create_signup_info(
                originator_public_key_hash=public_key_hash,
                most_recent_wait_certificate_id='0' * 16)

        store = ObjectStore()
        transaction = \
            ValidatorRegistryTransaction.register_validator(
                name,
                validator_id,
                signup_info)
        transaction.sign_object(key)
        try:
            transaction.check_valid(store)
            transaction.apply(store)
        except InvalidTransactionError as e:
            self.fail('Failed valid transaction: {}'.format(e))
        try:  # check if valid to register again
            transaction.check_valid(store)
        except InvalidTransactionError as e:
            self.fail('Failure: Double registered validator: {}'.format(e))
Exemplo n.º 7
0
def fiat_shamir(fs_state: bytes,
                data: Union[List[Point], List[Scalar]],
                nret=2) -> Tuple[bytes, List[Scalar]]:
    """
    Generates nret integer chllange values from the currnet
    interaction (data) and the previous challenge values (self.fs_state),
    thus fulfilling the requirement of basing the challenge on the transcript of the
    prover-verifier communication up to this point
    """
    # Point type
    if isinstance(data[0], tuple):
        data_bs: bytes = reduce(lambda acc, x: acc + B.encode_pubkey(x, 'bin'),
                                data, b"")

    # Scalar type
    elif isinstance(data[0], int):
        data_bs: bytes = reduce(
            lambda acc, x: acc + B.encode_privkey(x, 'bin'), data, b"")

    else:
        raise Exception('Invalid `data` param type for fiat_shamir')

    xb: bytes = hashlib.sha256(fs_state + data_bs).digest()

    challenges: List[Scalar] = []

    for _ in range(nret):
        challenges.append(B.encode_privkey(xb, 'decimal'))
        xb = hashlib.sha256(xb).digest()

    return xb, challenges
    def test_register_permissioned_validator_invalid(self):
        signing_key = signed_object.generate_signing_key()

        unpermissiond_private_key = signed_object.generate_signing_key()
        pub_key = pybitcointools.encode_pubkey(
            pybitcointools.privtopub(unpermissiond_private_key), 'hex')
        permissioned_public_keys = [pub_key]

        addr = signed_object.generate_identifier(unpermissiond_private_key)
        permissioned_addrs = [addr]

        update = {
            'whitelist_name': "hyperledger.sawtooth-core.genesis-whitelist",
            'verb': 'reg',
            'permissioned_public_keys': permissioned_public_keys,
            'permissioned_addrs': permissioned_addrs
        }
        minfo = {'Update': update}

        transaction = PermissionedValidatorRegistryTransaction(minfo)
        transaction.sign_object(signing_key)

        store = ObjectStore()
        with self.assertRaises(InvalidTransactionError):
            transaction.check_valid(store)
            self.fail("Failure: Verified an invalid transaction")
Exemplo n.º 9
0
def _sign_message_with_transaction(transaction, message_type, key):
    """
    Signs a transaction message or transaction
    :param transaction (dict):
    :param key (str): A signing key
    returns message, txnid (tuple): The first 16 characters
    of a sha256 hexdigest.
    """
    transaction['Nonce'] = time.time()
    pub = pybitcointools.encode_pubkey(pybitcointools.privkey_to_pubkey(key),
                                       "hex")
    transaction["public_key"] = pub
    sig = pybitcointools.ecdsa_sign(_dict2cbor(transaction), key)
    transaction['Signature'] = sig

    txnid = hashlib.sha256(transaction['Signature']).hexdigest()[:16]
    message = {
        'Transaction': transaction,
        '__TYPE__': message_type,
        '__NONCE__': time.time(),
    }
    cbor_serialized_message = _dict2cbor(message)
    signature = pybitcointools.ecdsa_sign(cbor_serialized_message, key)
    message['__SIGNATURE__'] = signature
    return message, txnid
Exemplo n.º 10
0
def sender_payee_address_from_stealth(sender_prikey, receiver_pubkey):
    # sender - derive payee address
    ss1 = btc.multiply(receiver_pubkey, sender_prikey)
    ss2 = btc.sha256(btc.encode_pubkey((ss1), 'bin_compressed'))
    addr = btc.pubkey_to_address(btc.add_pubkeys(
        receiver_pubkey, btc.privtopub(ss2)))
    return addr
Exemplo n.º 11
0
    def setUpClass(cls):
        args = {"NodeName": "DasValidator"}
        poet_enclave.initialize(**args)
        SignupInfo.poet_enclave = poet_enclave

        cls._originator_public_key = cls._create_random_public_key()
        cls._originator_public_key_hash = \
            hashlib.sha256(
                pybitcointools.encode_pubkey(
                    cls._originator_public_key,
                    'hex')).hexdigest()

        cls._another_public_key = cls._create_random_public_key()
        cls._another_public_key_hash = \
            hashlib.sha256(
                pybitcointools.encode_pubkey(
                    cls._another_public_key,
                    'hex')).hexdigest()
Exemplo n.º 12
0
    def setUpClass(cls):
        # Reload the wait timer module to clear any changed global state
        reload(wait_timer)

        cls._originator_public_key = cls._create_random_public_key()
        cls._originator_public_key_hash = \
            hashlib.sha256(
                pybitcointools.encode_pubkey(
                    cls._originator_public_key,
                    'hex')).hexdigest()
Exemplo n.º 13
0
    def create_signup_info(cls, originator_public_key):
        # First we need to create a public/private key pair for the PoET
        # enclave to use.
        cls._poet_private_key = pybitcointools.random_key()
        cls._poet_public_key = pybitcointools.privtopub(cls._poet_private_key)
        cls._active_wait_timer = None

        # We are going to fake out the sealing the signup data.
        signup_data = {
            'poet_public_key':
            pybitcointools.encode_pubkey(cls._poet_public_key, 'hex'),
            'poet_private_key':
            pybitcointools.encode_privkey(cls._poet_private_key, 'hex')
        }
        sealed_signup_data = \
            pybitcointools.base64.b32encode(dict2json(signup_data))

        # Create a fake report
        report_data = {
            'originator_public_key_hash':
            pybitcointools.sha256(
                pybitcointools.encode_pubkey(originator_public_key, 'hex')),
            'poet_public_key':
            pybitcointools.encode_pubkey(cls._poet_public_key, 'hex')
        }
        report = {'report_data': pybitcointools.sha256(dict2json(report_data))}
        report = pybitcointools.base64.b32encode(dict2json(report))

        # Fake our "proof" data.
        proof_data = {
            'attestation_evidence_payload':
            pybitcointools.sha256(report),
            'attestation_verification_report':
            pybitcointools.sha256('Shave and a haircut...Two bits!')
        }

        return \
            EnclaveSignupInfo(
                anti_sybil_id='Sally Field',
                poet_public_key=signup_data['poet_public_key'],
                proof_data=proof_data,
                sealed_signup_data=sealed_signup_data)
Exemplo n.º 14
0
def getNUMS(index=0) -> Point:
    """
    Nothing Up My Sleeve

    Taking secp256k1's G as a seed,
    either in compressed or uncompressed form,
    append "index" as a byte, and append a second byte "counter"
    try to create a new NUMS base point from the sha256 of that
    bytestring. Loop counter and alternate compressed/uncompressed
    until finding a valid curve point. The first such point is
    considered as "the" NUMS base point alternative for this index value.
    The search process is of course deterministic/repeatable, so
    it's fine to just store a list of all the correct values for
    each index, but for transparency left in code for initialization
    by any user.
    """

    for G in [
            B.encode_pubkey(B.G, 'bin_compressed'),
            B.encode_pubkey(B.G, 'bin')
    ]:
        # Using latin-1 since its used in BTC
        seed = G + chr(index).encode('utf-8')
        for counter in range(256):
            seed_c = seed + chr(counter).encode('utf-8')
            hash_seed = hashlib.sha256(seed_c).digest()

            # Every x-coord on the curve has two y-values, encoded
            # in compressed form with 02/03 parity byte. We just
            # choose the former
            claimed_point: bytes = chr(2).encode('utf-8') + hash_seed

            try:
                # Check to see if its a valid public key
                C.PublicKey(claimed_point)
                return B.encode_pubkey(claimed_point, 'decimal')
            except:
                continue

    raise Exception('NUMS generation inconceivable')
Exemplo n.º 15
0
def recover_pubkey(message, signature):
    v, r, s = pybitcointools.decode_sig(signature)
    msghash = pybitcointools.electrum_sig_hash(message)
    q = pybitcointools.ecdsa_raw_recover(msghash, (v, r, s))

    # A prior implementation set the behavior that this
    # method should return an encoded recovered pubkey or
    # an empty string if there is a recovery error. This
    # differs from the pybitcointools implementation of
    # ecdsa_recover, which returns the recovered pubkey
    # or False, if a recovery error occurs.
    if not q:
        return ""

    compress = True if v >= 31 else False

    if compress:
        pubkey = pybitcointools.encode_pubkey(q, 'hex_compressed')
    else:
        pubkey = pybitcointools.encode_pubkey(q, 'hex')

    return pubkey
    def test_register_permissioned_validator_valid(self):
        signing_key = signed_object.generate_signing_key()

        try:
            priv_key1 = pybitcointools.decode_privkey(
                open('./tests/unit/keys/pv1.wif', "r")
                .read().strip(), 'wif')
            priv_key2 = pybitcointools.decode_privkey(
                open('./tests/unit/keys/pv2.wif', "r")
                .read().strip(), 'wif')
        except IOError as ex:
            raise Exception('IOError: {}'.format(str(ex)))

        pub_key1 = pybitcointools.encode_pubkey(
            pybitcointools.privtopub(priv_key1), 'hex')
        pub_key2 = pybitcointools.encode_pubkey(
            pybitcointools.privtopub(priv_key2), 'hex')
        permissioned_public_keys = [pub_key1, pub_key2]

        addr1 = signed_object.generate_identifier(priv_key1)
        addr2 = signed_object.generate_identifier(priv_key2)
        permissioned_addrs = [addr1, addr2]

        update = {
            'whitelist_name': "hyperledger.sawtooth-core.genesis-whitelist",
            'verb': 'reg',
            'permissioned_public_keys': permissioned_public_keys,
            'permissioned_addrs': permissioned_addrs
        }
        minfo = {'Update': update}
        transaction = PermissionedValidatorRegistryTransaction(minfo)
        transaction.sign_object(signing_key)

        store = ObjectStore()
        try:
            transaction.check_valid(store)
            transaction.apply(store)
        except InvalidTransactionError as e:
            self.fail('Failed valid transaction: {}'.format(e))
    def test_register_permissioned_validator_valid(self):
        signing_key = signed_object.generate_signing_key()

        try:
            priv_key1 = pybitcointools.decode_privkey(
                open('./tests/unit/keys/pv1.wif', "r").read().strip(), 'wif')
            priv_key2 = pybitcointools.decode_privkey(
                open('./tests/unit/keys/pv2.wif', "r").read().strip(), 'wif')
        except IOError as ex:
            raise Exception('IOError: {}'.format(str(ex)))

        pub_key1 = pybitcointools.encode_pubkey(
            pybitcointools.privtopub(priv_key1), 'hex')
        pub_key2 = pybitcointools.encode_pubkey(
            pybitcointools.privtopub(priv_key2), 'hex')
        permissioned_public_keys = [pub_key1, pub_key2]

        addr1 = signed_object.generate_identifier(priv_key1)
        addr2 = signed_object.generate_identifier(priv_key2)
        permissioned_addrs = [addr1, addr2]

        update = {
            'whitelist_name': "hyperledger.sawtooth-core.genesis-whitelist",
            'verb': 'reg',
            'permissioned_public_keys': permissioned_public_keys,
            'permissioned_addrs': permissioned_addrs
        }
        minfo = {'Update': update}
        transaction = PermissionedValidatorRegistryTransaction(minfo)
        transaction.sign_object(signing_key)

        store = ObjectStore()
        try:
            transaction.check_valid(store)
            transaction.apply(store)
        except InvalidTransactionError as e:
            self.fail('Failed valid transaction: {}'.format(e))
Exemplo n.º 18
0
def do_generate(args):
    private_key = pybitcointools.random_key()
    public_key = pybitcointools.encode_pubkey(
        pybitcointools.privkey_to_pubkey(private_key), "hex")

    words = generate_word_list(args.pool_size)

    batches = []
    start = time.time()
    total_txn_count = 0
    for i in xrange(0, args.count):
        txns = []
        for _ in xrange(0, random.randint(1, args.batch_max_size)):
            txn = create_intkey_transaction(
                verb=random.choice(['set', 'inc', 'dec']),
                name=random.choice(words),
                value=random.randint(0, 100000),
                private_key=private_key,
                public_key=public_key)
            total_txn_count += 1
            txns.append(txn)

        batch = create_batch(
            transactions=txns,
            private_key=private_key,
            public_key=public_key)

        batches.append(batch)

        if i % 100 == 0 and i != 0:
            stop = time.time()

            txn_count = 0
            for batch in batches[-100:]:
                txn_count += len(batch.transactions)

            fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}'
            print fmt.format(
                str(i),
                100 / (stop - start),
                str(total_txn_count),
                txn_count / (stop - start))
            start = stop

    batch_list = batch_pb2.BatchList(batches=batches)

    print "Writing to {}...".format(args.output)
    with open(args.output, "w") as fd:
        fd.write(batch_list.SerializeToString())
Exemplo n.º 19
0
 def parse(self, data):
     if re.match('^[0-9a-fA-F]*$', data):
         data = data.decode('hex')
     o = rlp.decode(data)
     self.nonce = o[0]
     self.to = o[1]
     self.value = o[2]
     self.fee = o[3]
     self.data = o[4]
     self.v = o[5]
     self.r = o[6]
     self.s = o[7]
     rawhash = sha256(
         rlp.encode([self.nonce, self.to, self.value, self.fee, self.data]))
     pub = encode_pubkey(
         ecdsa_raw_recover(rawhash, (self.v, self.r, self.s)), 'bin')
     self.sender = bin_sha256(pub[1:])[-20:]
     return self
    def test_is_valid_pub_key(self):
        pubkey = pybitcointools.privkey_to_pubkey("5KQ4iQQGgbQX9MmfiPUwwHBL1R"
                                                  "GPa86NwFbqrWoodjuzruqFVDd")
        pub = pybitcointools.encode_pubkey(pubkey, "hex")
        minfo = {'Nonce': 100, 'public_key': pub,
                 'TransactionType': '/Transaction', 'Dependencies': []}
        sig = pybitcointools.ecdsa_sign(
            signed_object.dict2cbor(minfo),
            "5KQ4iQQGgbQX9MmfiPUwwHBL1RGPa86NwFbqrWoodjuzruqFVDd"
        )
        # Create valid transaction
        minfo["Signature"] = sig
        temp = Transaction(minfo)
        self.assertTrue(temp.is_valid("unused"))

        # Change transaction after it was signed
        minfo["Nonce"] = time.time()
        temp = Transaction(minfo)
        self.assertFalse(temp.is_valid("unused"))
Exemplo n.º 21
0
    def check_valid(self, store, txn):
        """Determines if the update is valid.
            Check policy on each element of validator_name, validator_id,
            and signup_info

        Args:
            store (Store): Transaction store.
            txn (Transaction): Transaction encompassing this update.
        """
        LOGGER.debug('check update %s from %s', str(self), self.validator_id)

        # Check name
        if not self.is_valid_name():
            raise InvalidTransactionError('Illegal validator name {}'.format(
                self.validator_name[:64]))

        # Check registering validator matches transaction signer.
        if self.validator_id != txn.OriginatorID:
            raise InvalidTransactionError(
                'Signature mismatch on validator registration with validator'
                ' {} signed by {}'.format(self.validator_id, txn.OriginatorID))

        # Nothing to check for anti_sybil_id
        # Apply will invalidate any previous entries for this anti_sybil_id
        # and create a new entry.

        try:
            public_key_hash = \
                hashlib.sha256(
                    pybitcointools.encode_pubkey(
                        txn.originator_public_key,
                        'hex')).hexdigest()

            self.signup_info.check_valid(
                originator_public_key_hash=public_key_hash,
                most_recent_wait_certificate_id='0' * 16)
        except SignupInfoError as error:
            raise InvalidTransactionError(
                'Invalid Signup Info: {0}, Reason: {1}'.format(
                    self.signup_info, error))

        return True
Exemplo n.º 22
0
    def test_is_valid_pub_key(self):
        pubkey = pybitcointools.privkey_to_pubkey("5KQ4iQQGgbQX9MmfiPUwwHBL1R"
                                                  "GPa86NwFbqrWoodjuzruqFVDd")
        pub = pybitcointools.encode_pubkey(pubkey, "hex")
        minfo = {
            'Nonce': 100,
            'public_key': pub,
            'TransactionType': '/Transaction',
            'Dependencies': []
        }
        sig = pybitcointools.ecdsa_sign(
            signed_object.dict2cbor(minfo),
            "5KQ4iQQGgbQX9MmfiPUwwHBL1RGPa86NwFbqrWoodjuzruqFVDd")
        # Create valid transaction
        minfo["Signature"] = sig
        temp = Transaction(minfo)
        self.assertTrue(temp.is_valid("unused"))

        # Change transaction after it was signed
        minfo["Nonce"] = time.time()
        temp = Transaction(minfo)
        self.assertFalse(temp.is_valid("unused"))
Exemplo n.º 23
0
def encode_pubkey(pubkey, encoding_format):
    return pybitcointools.encode_pubkey(pubkey, encoding_format)
Exemplo n.º 24
0
def pubkey_to_ethaddress(pubkey):
    pub = encode_pubkey(pubkey, 'bin')
    address = sha3_256(pub[1:])[12:]
    return '0x' + address.encode('hex')
Exemplo n.º 25
0
    def initialization_complete(self, journal):
        """Processes all invocations that arrived while the ledger was
        being initialized.
        """
        # Before we allow the base journal to do anything that might result
        # in a wait timer or wait certificate being created, we have to ensure
        # the PoET enclave has been initialized.  This can be done in one of
        # two ways:
        # 1. If we have sealed signup data (meaning that we have previously
        #    created signup info), we can request that the enclave unseal it,
        #    in the process restoring the enclave to its previous state.
        # 2. Create new signup information.
        signup_info = None
        sealed_signup_data = journal.local_store.get('sealed_signup_data')

        if sealed_signup_data is not None:
            self.poet_public_key = SignupInfo.unseal_signup_data(
                sealed_signup_data=sealed_signup_data)
        else:
            wait_certificate_id = journal.most_recent_committed_block_id
            public_key_hash = \
                hashlib.sha256(
                    pybitcointools.encode_pubkey(
                        journal.local_node.public_key(),
                        'hex')).hexdigest()

            signup_info = \
                SignupInfo.create_signup_info(
                    originator_public_key_hash=public_key_hash,
                    most_recent_wait_certificate_id=wait_certificate_id)

            # Save off the sealed signup data
            journal.local_store.set('sealed_signup_data',
                                    signup_info.sealed_signup_data)
            journal.local_store.sync()

            self.poet_public_key = signup_info.poet_public_key

        # propagate the maximum blocks to keep
        journal.maximum_blocks_to_keep = max(
            journal.maximum_blocks_to_keep,
            WaitTimer.certificate_sample_length)

        # initialize stats specifically for the block chain journal
        journal.JournalStats.add_metric(stats.Value('LocalMeanTime', 0))
        journal.JournalStats.add_metric(stats.Value('AggregateLocalMean', 0))
        journal.JournalStats.add_metric(stats.Value('PopulationEstimate', 0))
        journal.JournalStats.add_metric(
            stats.Value('ExpectedExpirationTime', 0))
        journal.JournalStats.add_metric(stats.Value('Duration', 0))

        # initialize the block handlers
        poet_transaction_block.register_message_handlers(journal)

        # If we created signup information, then advertise self to network
        if signup_info is not None:
            # Create a validator register transaction and sign it.  Wrap
            # the transaction in a message.  Broadcast it to out.
            transaction = \
                val_reg.ValidatorRegistryTransaction.register_validator(
                    journal.local_node.Name,
                    journal.local_node.Identifier,
                    signup_info)
            transaction.sign_from_node(journal.local_node)

            message = \
                val_reg.ValidatorRegistryTransactionMessage()
            message.Transaction = transaction

            LOGGER.info('Advertise PoET 1 validator with name %s',
                        journal.local_node.Name)

            journal.gossip.broadcast_message(message)
Exemplo n.º 26
0
def do_generate(args):
    private_key = pybitcointools.random_key()
    public_key = pybitcointools.encode_pubkey(
        pybitcointools.privkey_to_pubkey(private_key), "hex")

    words = generate_word_list(args.pool_size)

    txns = []
    batches = []
    bytecode = ""
    with open(args.contract, "rb") as fd:
        byte = fd.readline()
        while byte != "":
            bytecode += byte
            byte = fd.readline()

    byte_addr = get_address("jvm_sc", bytecode)

    txn = create_jvm_sc_transaction(
        verb='store',
        private_key=private_key,
        public_key=public_key,
        bytecode=bytecode,
        methods=["set", "inc", "dec"])
    txns.append(txn)

    keys = []
    addresses = []
    for i in range(20):
        if len(txns) < 10:
            key = random.choice(words)
            keys.append(key)
            value = str(random.randint(0, 1000))
            key_addr = get_address("intkey", key)
            addresses.append(key_addr)
            txn = create_jvm_sc_transaction(
                verb='run',
                private_key=private_key,
                public_key=public_key,
                byte_addr=byte_addr,
                method="set",
                parameters=["key," + key, "value," + value,
                            "&check," + key_addr],
                addresses=addresses)
            txns.append(txn)
            addresses = []
        else:
            batch = create_batch(txns, private_key, public_key)
            batches.append(batch)
            txns = []

    for i in range(20):
        if len(txns) < 10:
            key = random.choice(keys)
            key_addr = get_address("intkey", key)
            addresses.append(key_addr)
            txn = create_jvm_sc_transaction(
                verb='run',
                private_key=private_key,
                public_key=public_key,
                byte_addr=byte_addr,
                method=random.choice(["inc", "dec"]),
                parameters=["key," + key, "&value," + key_addr, "diff,2"],
                addresses=addresses)
            txns.append(txn)
            addresses = []
        else:
            batch = create_batch(txns, private_key, public_key)
            batches.append(batch)
            txns = []

    batch_list = batch_pb2.BatchList(batches=batches)
    print "Writing to {}...".format(args.output)
    with open(args.output, "w") as fd:
        fd.write(batch_list.SerializeToString())
Exemplo n.º 27
0
compressed_private_key = private_key + '01'
print("Private Key Compressed (hex) is: ", compressed_private_key)

# Generate a WIF format from the compressed private key (WIF-compressed)
wif_compressed_private_key = pybitcointools.encode_privkey(
    pybitcointools.decode_privkey(compressed_private_key, 'hex'),
    'wif_compressed')
print("Private Key (WIF-Compressed) is: ", wif_compressed_private_key)

# Multiply the EC generator point G with the private key to get a public key point
public_key = pybitcointools.fast_multiply(pybitcointools.G,
                                          decoded_private_key)
print("Public Key (x,y) coordinates is:", public_key)

# Encode as hex, prefix 04
hex_encoded_public_key = pybitcointools.encode_pubkey(public_key, 'hex')
print("Public Key (hex) is:", hex_encoded_public_key)

# Compress public key, adjust prefix depending on whether y is even or odd
(public_key_x, public_key_y) = public_key
compressed_prefix = '02' if (public_key_y % 2) == 0 else '03'
hex_compressed_public_key = compressed_prefix + (pybitcointools.encode(
    public_key_x, 16).zfill(64))
print("Compressed Public Key (hex) is:", hex_compressed_public_key)

# Generate pybitcointools address from public key
print("pybitcointools Address (b58check) is:",
      pybitcointools.pubkey_to_address(public_key))

# Generate compressed pybitcointools address from compressed public key
print("Compressed pybitcointools Address (b58check) is:",
Exemplo n.º 28
0
def multiply_pubkeys(p1, p2, n):
    f1, f2 = get_pubkey_format(p1), get_pubkey_format(p2)
    mp = fast_multiply(decode_pubkey(p2, f2), n)
    return encode_pubkey(fast_add(decode_pubkey(p1, f1), mp), f1)
Exemplo n.º 29
0
def create_stealth_address(spend_pubkey, magic_byte=42):
    # magic_byte = 42 for mainnet, 43 for testnet.
    hex_spendkey = btc.encode_pubkey(spend_pubkey, 'hex_compressed')
    hex_data = '00{0:066x}'.format(int(hex_spendkey, 16))
    addr = btc.hex_to_b58check(hex_data, magic_byte)
    return addr
Exemplo n.º 30
0
import pybitcointools

pub = pybitcointools.decode_pubkey(
    "03d299230be2bf10cad8f0b6f25c905c67e6a5896956c59adc8774c7e601946acf")
print hex(pub[1])
pybitcointools.encode_pubkey(pub, "bin_compressed")
pub1 = pybitcointools.decode_pubkey(
    "02a4e436bede8e4ed5f6193d64619b7dddbd42a3c26dcc057de79e8f0911342647")
print hex(pub1[1])
pybitcointools.encode_pubkey(pub1, "bin_compressed")

pub = pybitcointools.decode_pubkey(
    "0335644013e62b3576612253e1a9860e2b0c71c9033a711522606832bbcc733a44")
print hex(pub[1])
pybitcointools.encode_pubkey(pub, "bin_compressed")
Exemplo n.º 31
0
    def create_signup_info(cls,
                           originator_public_key,
                           validator_network_basename,
                           most_recent_wait_certificate_id):
        with cls._lock:
            # First we need to create a public/private key pair for the PoET
            # enclave to use.
            cls._poet_private_key = pybitcointools.random_key()
            cls._poet_public_key = \
                pybitcointools.privtopub(cls._poet_private_key)
            cls._active_wait_timer = None

            # We are going to fake out the sealing the signup data.
            signup_data = {
                'poet_public_key':
                    pybitcointools.encode_pubkey(cls._poet_public_key, 'hex'),
                'poet_private_key':
                    pybitcointools.encode_privkey(
                        cls._poet_private_key,
                        'hex')
            }
            sealed_signup_data = \
                pybitcointools.base64.b32encode(dict2json(signup_data))

            # Create a fake report
            report_data = {
                'originator_public_key_hash':
                    pybitcointools.sha256(
                        pybitcointools.encode_pubkey(
                            originator_public_key,
                            'hex')),
                'poet_public_key':
                    pybitcointools.encode_pubkey(cls._poet_public_key, 'hex')
            }
            report = {
                'report_data': pybitcointools.sha256(dict2json(report_data)),
                'validator_network_basename': validator_network_basename
            }

            # Fake our "proof" data.
            attestation_evidence_payload = {
                'enclave_quote':
                    pybitcointools.base64.b64encode(dict2json(report)),
                'pse_manifest':
                    pybitcointools.base64.b64encode(
                        pybitcointools.sha256(
                            'manifest destiny')),
                'nonce': most_recent_wait_certificate_id
            }

            attestation_verification_report = {
                'attestation_evidence_payload': attestation_evidence_payload,
                'anti_sybil_id': cls._anti_sybil_id
            }

            proof_data = {
                'attestation_verification_report':
                    attestation_verification_report,
                'signature':
                    pybitcointools.ecdsa_sign(
                        dict2json(attestation_verification_report),
                        cls._report_private_key)
            }

            return \
                EnclaveSignupInfo(
                    poet_public_key=signup_data['poet_public_key'],
                    proof_data=proof_data,
                    sealed_signup_data=sealed_signup_data)
Exemplo n.º 32
0
    def verify_signup_info(cls,
                           signup_info,
                           originator_public_key,
                           validator_network_basename,
                           most_recent_wait_certificate_id):
        # Verify the attestation verification report signature
        attestation_verification_report = \
            signup_info.proof_data.get('attestation_verification_report')
        if attestation_verification_report is None:
            raise \
                SignupInfoError(
                    'Attestation verification report is missing from proof '
                    'data')

        if not pybitcointools.ecdsa_verify(
                dict2json(attestation_verification_report),
                signup_info.proof_data.get('signature'),
                cls._report_public_key):
            raise \
                SignupInfoError(
                    'Attestation verification report signature is invalid')

        # Verify the presence of the anti-Sybil ID
        anti_sybil_id = attestation_verification_report.get('anti_sybil_id')
        if anti_sybil_id is None:
            raise \
                SignupInfoError(
                    'Attestation verification report does not contain an '
                    'anti-Sybil ID')

        # Verify that the report data field in the report contains the SHA256
        # digest of the originator's public key SHA 256 digest and the PoET
        # public key.
        attestation_evidence_payload = \
            attestation_verification_report.get(
                'attestation_evidence_payload')
        if attestation_evidence_payload is None:
            raise \
                SignupInfoError(
                    'Attestation verification report does not contain '
                    'attestation evidence payload')

        enclave_quote = attestation_evidence_payload.get('enclave_quote')
        if enclave_quote is None:
            raise \
                SignupInfoError(
                    'Attestation evidence payload does not contain an '
                    'enclave quote')

        report = json2dict(pybitcointools.base64.b64decode(enclave_quote))
        report_data = report.get('report_data')
        if report_data is None:
            raise \
                SignupInfoError('Enclave quote does not contain report data')

        target_report_data = {
            'originator_public_key_hash':
                pybitcointools.sha256(
                    pybitcointools.encode_pubkey(
                        originator_public_key,
                        'hex')),
            'poet_public_key': signup_info.poet_public_key
        }
        target_report_data_digest = \
            pybitcointools.sha256(dict2json(target_report_data))

        if report_data != target_report_data_digest:
            raise SignupInfoError('Enclave quote report data is invalid')

        # Verify that the validator base name in the enclave quote report
        # matches the provided validator network basename
        validator_net_basename = report.get('validator_network_basename')
        if validator_net_basename is None:
            raise \
                SignupInfoError(
                    'Enclave quote report does not have a validator network '
                    'basename')

        if validator_net_basename != validator_network_basename:
            raise \
                SignupInfoError(
                    'Enclave quote report validator network basename [{0}] '
                    'does not match [{1}]'.format(
                        validator_net_basename,
                        validator_network_basename))
Exemplo n.º 33
0
def do_generate(args):
    private_key = pybitcointools.random_key()
    public_key = pybitcointools.encode_pubkey(
        pybitcointools.privkey_to_pubkey(private_key), "hex")

    words = generate_word_list(args.pool_size)

    txns = []
    batches = []
    bytecode = ""
    with open(args.contract, "rb") as fd:
        byte = fd.readline()
        while byte != "":
            bytecode += byte
            byte = fd.readline()

    byte_addr = get_address("jvm_sc", bytecode)

    txn = create_jvm_sc_transaction(verb='store',
                                    private_key=private_key,
                                    public_key=public_key,
                                    bytecode=bytecode,
                                    methods=["set", "inc", "dec"])
    txns.append(txn)

    keys = []
    addresses = []
    for i in range(20):
        if len(txns) < 10:
            key = random.choice(words)
            keys.append(key)
            value = str(random.randint(0, 1000))
            key_addr = get_address("intkey", key)
            addresses.append(key_addr)
            txn = create_jvm_sc_transaction(verb='run',
                                            private_key=private_key,
                                            public_key=public_key,
                                            byte_addr=byte_addr,
                                            method="set",
                                            parameters=[
                                                "key," + key, "value," + value,
                                                "&check," + key_addr
                                            ],
                                            addresses=addresses)
            txns.append(txn)
            addresses = []
        else:
            batch = create_batch(txns, private_key, public_key)
            batches.append(batch)
            txns = []

    for i in range(20):
        if len(txns) < 10:
            key = random.choice(keys)
            key_addr = get_address("intkey", key)
            addresses.append(key_addr)
            txn = create_jvm_sc_transaction(
                verb='run',
                private_key=private_key,
                public_key=public_key,
                byte_addr=byte_addr,
                method=random.choice(["inc", "dec"]),
                parameters=["key," + key, "&value," + key_addr, "diff,2"],
                addresses=addresses)
            txns.append(txn)
            addresses = []
        else:
            batch = create_batch(txns, private_key, public_key)
            batches.append(batch)
            txns = []

    batch_list = batch_pb2.BatchList(batches=batches)
    print "Writing to {}...".format(args.output)
    with open(args.output, "w") as fd:
        fd.write(batch_list.SerializeToString())
Exemplo n.º 34
0
def receiver_payee_privkey_from_stealth(receiver_prikey, sender_pubkey):
    # sender - derive payee address
    ss1 = btc.multiply(sender_pubkey, receiver_prikey)
    ss2 = btc.sha256(btc.encode_pubkey((ss1), 'bin_compressed'))
    key = btc.add_privkeys(receiver_prikey, ss2)
    return key