示例#1
0
    def create_wait_timer(cls, previous_certificate_id, local_mean):
        # Create some value from the cert ID.  We are just going to use
        # the seal key to sign the cert ID.  We will then use the low-order
        # 64 bits to change that to a number [0, 1]
        tag = \
            pybitcointools.base64.b64decode(
                pybitcointools.ecdsa_sign(
                    previous_certificate_id,
                    cls._seal_private_key))

        tagd = float(struct.unpack('L', tag[-8:])[0]) / (2**64 - 1)

        # Now compute the duration
        duration = cls.__MINIMUM_DURATTION - local_mean * math.log(tagd)

        # Create and sign the wait timer
        wait_timer = \
            EnclaveWaitTimer(
                duration=duration,
                previous_certificate_id=previous_certificate_id,
                local_mean=local_mean)
        wait_timer.signature = \
            pybitcointools.ecdsa_sign(
                wait_timer.serialize(),
                cls._poet_private_key)

        # Keep track of the active wait timer
        cls._active_wait_timer = wait_timer

        return wait_timer
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
示例#3
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
示例#4
0
def create_intkey_transaction(verb, name, value, private_key, public_key):
    payload = IntKeyPayload(
        verb=verb, name=name, value=value)

    # The prefix should eventually be looked up from the
    # validator's namespace registry.
    intkey_prefix = hashlib.sha512('intkey').hexdigest()[0:6]

    addr = intkey_prefix + hashlib.sha512(name).hexdigest()

    header = transaction_pb2.TransactionHeader(
        signer=public_key,
        family_name='intkey',
        family_version='1.0',
        inputs=[addr],
        outputs=[addr],
        dependencies=[],
        payload_encoding="application/cbor",
        payload_sha512=payload.sha512(),
        batcher=public_key)

    header_bytes = header.SerializeToString()

    signature = pybitcointools.ecdsa_sign(
        header_bytes,
        private_key)

    transaction = transaction_pb2.Transaction(
        header=header_bytes,
        payload=payload.to_cbor(),
        signature=signature)

    return transaction
    def test_deserialized_wait_timer(self):
        wait_timer = \
            EnclaveWaitTimer(
                duration=3.14159,
                previous_certificate_id='Bond.  James Bond.',
                local_mean=2.71828)

        serialized = wait_timer.serialize()
        signing_key = self._create_random_key()
        wait_timer.signature = \
            pybitcointools.ecdsa_sign(serialized, signing_key)

        copy_wait_timer = \
            EnclaveWaitTimer.wait_timer_from_serialized(
                serialized,
                wait_timer.signature)

        self.assertAlmostEquals(
            wait_timer.request_time,
            copy_wait_timer.request_time)
        self.assertAlmostEquals(
            wait_timer.duration,
            copy_wait_timer.duration)
        self.assertEqual(
            wait_timer.previous_certificate_id,
            copy_wait_timer.previous_certificate_id)
        self.assertAlmostEquals(
            wait_timer.local_mean,
            copy_wait_timer.local_mean)
        self.assertEqual(
            wait_timer.signature,
            copy_wait_timer.signature)

        self.assertEqual(serialized, copy_wait_timer.serialize())
    def test_deserialized_wait_timer(self):
        wait_timer = \
            EnclaveWaitTimer(
                duration=3.14159,
                previous_certificate_id='Bond.  James Bond.',
                local_mean=2.71828)

        serialized = wait_timer.serialize()
        signing_key = self._create_random_key()
        wait_timer.signature = \
            pybitcointools.ecdsa_sign(serialized, signing_key)

        copy_wait_timer = \
            EnclaveWaitTimer.wait_timer_from_serialized(
                serialized,
                wait_timer.signature)

        self.assertAlmostEquals(wait_timer.request_time,
                                copy_wait_timer.request_time)
        self.assertAlmostEquals(wait_timer.duration, copy_wait_timer.duration)
        self.assertEqual(wait_timer.previous_certificate_id,
                         copy_wait_timer.previous_certificate_id)
        self.assertAlmostEquals(wait_timer.local_mean,
                                copy_wait_timer.local_mean)
        self.assertEqual(wait_timer.signature, copy_wait_timer.signature)

        self.assertEqual(serialized, copy_wait_timer.serialize())
    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)
示例#8
0
文件: gui.py 项目: Aeium/go-coin
def easy_add_transaction(tx_orig, sign_over, privkey):
    state=state_library.current_state()
    pubkey=pt.privtopub(privkey)
    if pubkey not in state or 'count' not in state[pubkey]:
        my_count=1
    else:
        my_count=state[pubkey]['count']
    txs=blockchain.load_transactions()
    my_txs=filter(lambda x: x['id']==pubkey, txs)
    tx=copy.deepcopy(tx_orig)
    tx['count']=len(my_txs)+my_count
    tx['signature']=pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey)
    print(blockchain.add_transaction(tx))
    if 'move_number' in tx:
        for i in range(10):
            tx['move_number']+=1
            tx['signature']=pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey)
            print(blockchain.add_transaction(tx))
    print('tx: ' +str(tx))
    blockchain.pushtx(tx, config.peers_list)
示例#9
0
def easy_add_transaction(tx_orig, sign_over, privkey):
    state = state_library.current_state()
    pubkey = pt.privtopub(privkey)
    if pubkey not in state or "count" not in state[pubkey]:
        my_count = 1
    else:
        my_count = state[pubkey]["count"]
    txs = blockchain.load_transactions()
    my_txs = filter(lambda x: x["id"] == pubkey, txs)
    tx = copy.deepcopy(tx_orig)
    tx["count"] = len(my_txs) + my_count
    tx["signature"] = pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey)
    print (blockchain.add_transaction(tx))
    if "move_number" in tx:
        for i in range(10):
            tx["move_number"] += 1
            tx["signature"] = pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey)
            print (blockchain.add_transaction(tx))
    print ("tx: " + str(tx))
    blockchain.pushtx(tx, quick_mine.peers_list)
示例#10
0
 def test_bulk_keymatch(self):
     """
     Tests key recovery over several keys
     """
     msg = 'foo'
     for _ in range(0, 20):
         priv = pbt.random_key()
         sig = pbt.ecdsa_sign(msg, priv)
         native_recovered = pbct_nativerecover.recover_pubkey(msg, sig)
         py_recovered = pbt.ecdsa_recover(msg, sig)
         self.assertEquals(native_recovered, py_recovered,
                           "Priv Key that failed: {}".format(priv))
    def create_wait_timer(cls, previous_certificate_id, local_mean):
        with cls._lock:
            # If we don't have a PoET private key, then the enclave has not
            # been properly initialized (either by calling create_signup_info
            # or unseal_signup_data)
            if cls._poet_private_key is None:
                raise \
                    WaitTimerError(
                        'Enclave must be initialized before attempting to '
                        'create a wait timer')

            # Create some value from the cert ID.  We are just going to use
            # the seal key to sign the cert ID.  We will then use the
            # low-order 64 bits to change that to a number [0, 1]
            tag = \
                pybitcointools.base64.b64decode(
                    pybitcointools.ecdsa_sign(
                        previous_certificate_id,
                        cls._seal_private_key))

            tagd = float(struct.unpack('L', tag[-8:])[0]) / (2**64 - 1)

            # Now compute the duration
            duration = cls.__MINIMUM_DURATTION - local_mean * math.log(tagd)

            # Create and sign the wait timer
            wait_timer = \
                EnclaveWaitTimer(
                    duration=duration,
                    previous_certificate_id=previous_certificate_id,
                    local_mean=local_mean)
            wait_timer.signature = \
                pybitcointools.ecdsa_sign(
                    wait_timer.serialize(),
                    cls._poet_private_key)

            # Keep track of the active wait timer
            cls._active_wait_timer = wait_timer

            return wait_timer
示例#12
0
 def test_bulk_keymatch(self):
     """
     Tests key recovery over several keys
     """
     msg = 'foo'
     self.longMessage = True
     for x in range(0, 20):
         priv = pbt.random_key()
         sig = pbt.ecdsa_sign(msg, priv)
         native_recovered = gossip.signed_object.get_verifying_key(msg, sig)
         py_recovered = pbt.ecdsa_recover(msg, sig)
         self.assertEquals(native_recovered, py_recovered,
                           "Priv Key that failed: {}".format(priv))
示例#13
0
 def test_pbt_match(self):
     """
     Tests matching results between pybitcointools and native
     ECDSA key recovery
     """
     # This key has a small public key value which tests padding
     wifstr = '5JtMb6tmM9vT6QHyM7RR8pjMViqccukgMFNCPvG5xhLVf6CMoGx'
     priv = pbt.decode_privkey(wifstr, 'wif')
     msg = 'foo'
     sig = pbt.ecdsa_sign(msg, priv)
     native_recovered = gossip.signed_object.get_verifying_key(msg, sig)
     py_recovered = pbt.ecdsa_recover(msg, sig)
     self.assertEquals(native_recovered, py_recovered)
 def test_bulk_keymatch(self):
     """
     Tests key recovery over several keys
     """
     msg = 'foo'
     self.longMessage = True
     for x in range(0, 20):
         priv = pbt.random_key()
         sig = pbt.ecdsa_sign(msg, priv)
         native_recovered = gossip.signed_object.get_verifying_key(msg, sig)
         py_recovered = pbt.ecdsa_recover(msg, sig)
         self.assertEquals(native_recovered, py_recovered,
                           "Priv Key that failed: {}".format(priv))
 def test_pbt_match(self):
     """
     Tests matching results between pybitcointools and native
     ECDSA key recovery
     """
     # This key has a small public key value which tests padding
     wifstr = '5JtMb6tmM9vT6QHyM7RR8pjMViqccukgMFNCPvG5xhLVf6CMoGx'
     priv = pbt.decode_privkey(wifstr, 'wif')
     msg = 'foo'
     sig = pbt.ecdsa_sign(msg, priv)
     native_recovered = gossip.signed_object.get_verifying_key(msg, sig)
     py_recovered = pbt.ecdsa_recover(msg, sig)
     self.assertEquals(native_recovered, py_recovered)
示例#16
0
文件: gui.py 项目: SamPatt/CryptGo
def easy_add_transaction(tx_orig, sign_over, privkey, state):
    tx=copy.deepcopy(tx_orig)
    pubkey=pt.privtopub(privkey)
    if pubkey not in state or 'count' not in state[pubkey]:
        tx['count']=1
    else:
        tx['count']=state[pubkey]['count']
    txs=blockchain.load_transactions()
    my_txs=filter(lambda x: x['id']==pubkey, txs)
    tx['signature']=pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey)
    if blockchain.add_transaction(tx):
        blockchain.pushtx(tx, config.peers_list)
        return True
    if 'move_number' in tx:
        for i in range(10):
            tx['move_number']+=1
            tx['signature']=pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey)
            if blockchain.add_transaction(tx):
                blockchain.pushtx(tx, config.peers_list)
                return True
    print('SOMETHING IS BROKEN')
    return False
示例#17
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()
    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
示例#18
0
    def sign_object(self, signingkey):
        """Generates a string signature for the object using the signing
        key.

        Args:
            signingkey (str): hex encoded private key
        """

        self._originator_id = None
        serialized = self.serialize(signable=True)
        self.Signature = pybitcointools.ecdsa_sign(serialized, signingkey)

        self._recover_verifying_address()
        self._identifier = hashlib.sha256(self.Signature).hexdigest()
示例#19
0
    def sign_object(self, signingkey):
        """Generates a string signature for the object using the signing
        key.

        Args:
            signingkey (str): hex encoded private key
        """

        self._originator_id = None
        serialized = self.serialize(signable=True)
        self.Signature = pybitcointools.ecdsa_sign(serialized, signingkey)

        self._recover_verifying_address()
        self._identifier = hashlib.sha256(self.Signature).hexdigest()
示例#20
0
def create_jvm_sc_transaction(verb,
                              private_key,
                              public_key,
                              bytecode=None,
                              methods=None,
                              byte_addr=None,
                              method=None,
                              parameters=None,
                              addresses=None):

    payload = JVM_SC_Payload(verb=verb,
                             bytecode=bytecode,
                             methods=methods,
                             byte_addr=byte_addr,
                             method=method,
                             parameters=parameters)

    if addresses is None:
        addresses = []

    # The prefix should eventually be looked up from the
    # validator's namespace registry.
    if byte_addr is not None:
        addr = byte_addr
    elif bytecode is not None:
        addr = get_address('jvm_sc', bytecode)
    else:
        raise Exception

    addresses.append(addr)
    header = transaction_pb2.TransactionHeader(
        signer=public_key,
        family_name='jvm_sc',
        family_version='1.0',
        inputs=addresses,
        outputs=addresses,
        dependencies=[],
        payload_encoding="application/protobuf",
        payload_sha512=payload.sha512(),
        batcher=public_key)
    header_bytes = header.SerializeToString()

    signature = pybitcointools.ecdsa_sign(header_bytes, private_key)

    transaction = transaction_pb2.Transaction(header=header_bytes,
                                              payload=payload.payload_bytes,
                                              signature=signature)

    return transaction
示例#21
0
    def create_wait_certificate(cls, timer, block_digest):
        # TO DO - implement PoET 1 create certificate logic

        # First create a new enclave wait certificate using the data provided
        # and then sign the certificate with the PoET private key
        wait_certificate = \
            EnclaveWaitCertificate.wait_certificate_with_timer(
                timer=timer,
                block_digest=block_digest)
        wait_certificate.signature = \
            pybitcointools.ecdsa_sign(
                wait_certificate.serialize(),
                cls._poet_private_key)

        return wait_certificate
示例#22
0
def easy_add_transaction(tx_orig, sign_over, privkey, state):
    tx = copy.deepcopy(tx_orig)
    pubkey = pt.privtopub(privkey)
    if pubkey not in state or 'count' not in state[pubkey]:
        tx['count'] = 1
    else:
        tx['count'] = state[pubkey]['count']
    txs = blockchain.load_transactions()
    my_txs = filter(lambda x: x['id'] == pubkey, txs)
    tx['signature'] = pt.ecdsa_sign(go.message2signObject(tx, sign_over),
                                    privkey)
    if blockchain.add_transaction(tx):
        blockchain.pushtx(tx, config.peers_list)
        return True
    if 'move_number' in tx:
        for i in range(10):
            tx['move_number'] += 1
            tx['signature'] = pt.ecdsa_sign(
                go.message2signObject(tx, sign_over), privkey)
            if blockchain.add_transaction(tx):
                blockchain.pushtx(tx, config.peers_list)
                return True
    print('SOMETHING IS BROKEN')
    return False
示例#23
0
def create_batch(transactions, private_key, public_key):
    transaction_signatures = [t.signature for t in transactions]

    header = batch_pb2.BatchHeader(
        signer=public_key, transaction_signatures=transaction_signatures)

    header_bytes = header.SerializeToString()

    signature = pybitcointools.ecdsa_sign(header_bytes, private_key)

    batch = batch_pb2.Batch(header=header_bytes,
                            transactions=transactions,
                            signature=signature)

    return batch
示例#24
0
 def test_compressed_keys(self):
     """
     Tests compressed key
     """
     msg = 'foo'
     priv = pbt.encode_privkey(pbt.random_key(), 'hex_compressed')
     sig = pbt.ecdsa_sign(msg, priv)
     # Force old pybitcointools to behave
     v, r, s = pbt.decode_sig(sig)
     if v < 31:
         v += 4
     sig = pbt.encode_sig(v, r, s)
     pub = pbt.compress(pbt.privtopub(priv))
     native_recovered = pbct_nativerecover.recover_pubkey(msg, sig)
     self.assertEquals(native_recovered, pub,
                       "Priv Key that failed: {}".format(priv))
示例#25
0
 def test_compressed_keys(self):
     """
     Tests compressed key
     """
     msg = 'foo'
     self.longMessage = True
     priv = pbt.encode_privkey(pbt.random_key(), 'hex_compressed')
     sig = pbt.ecdsa_sign(msg, priv)
     # Force old pybitcointools to behave
     v, r, s = pbt.decode_sig(sig)
     if v < 31:
         v += 4
     sig = pbt.encode_sig(v, r, s)
     pub = pbt.compress(pbt.privtopub(priv))
     native_recovered = gossip.signed_object.get_verifying_key(msg, sig)
     self.assertEquals(native_recovered, pub,
                       "Priv Key that failed: {}".format(priv))
    def test_deserialized_wait_certificate(self):
        wait_timer = \
            EnclaveWaitTimer(
                duration=3.14159,
                previous_certificate_id='Smart, Maxwell Smart',
                local_mean=2.71828)

        wait_certificate = \
            EnclaveWaitCertificate.wait_certificate_with_wait_timer(
                wait_timer=wait_timer,
                nonce='Eeny, meeny, miny, moe.',
                block_digest='Indigestion. Pepto Bismol.')

        serialized = wait_certificate.serialize()
        signing_key = self._create_random_key()
        wait_certificate.signature = \
            pybitcointools.ecdsa_sign(serialized, signing_key)

        copy_wait_certificate = \
            EnclaveWaitCertificate.wait_certificate_from_serialized(
                serialized,
                wait_certificate.signature)

        self.assertAlmostEquals(
            wait_certificate.request_time,
            copy_wait_certificate.request_time)
        self.assertAlmostEquals(
            wait_certificate.duration,
            copy_wait_certificate.duration)
        self.assertEqual(
            wait_certificate.previous_certificate_id,
            copy_wait_certificate.previous_certificate_id)
        self.assertAlmostEquals(
            wait_certificate.local_mean,
            copy_wait_certificate.local_mean)
        self.assertEqual(
            wait_certificate.nonce,
            copy_wait_certificate.nonce)
        self.assertEqual(
            wait_certificate.block_digest,
            copy_wait_certificate.block_digest)
        self.assertEqual(
            wait_certificate.signature,
            copy_wait_certificate.signature)

        self.assertEqual(serialized, copy_wait_certificate.serialize())
 def test_compressed_keys(self):
     """
     Tests compressed key
     """
     msg = 'foo'
     self.longMessage = True
     priv = pbt.encode_privkey(pbt.random_key(), 'hex_compressed')
     sig = pbt.ecdsa_sign(msg, priv)
     # Force old pybitcointools to behave
     v, r, s = pbt.decode_sig(sig)
     if v < 31:
         v += 4
     sig = pbt.encode_sig(v, r, s)
     pub = pbt.compress(pbt.privtopub(priv))
     native_recovered = gossip.signed_object.get_verifying_key(msg, sig)
     self.assertEquals(native_recovered, pub,
                       "Priv Key that failed: {}".format(priv))
示例#28
0
def create_jvm_sc_transaction(verb, private_key, public_key,
                              bytecode=None, methods=None, byte_addr=None,
                              method=None, parameters=None, addresses=None):

    payload = JVM_SC_Payload(verb=verb, bytecode=bytecode,
                             methods=methods, byte_addr=byte_addr,
                             method=method, parameters=parameters)

    if addresses is None:
        addresses = []

    # The prefix should eventually be looked up from the
    # validator's namespace registry.
    if byte_addr is not None:
        addr = byte_addr
    elif bytecode is not None:
        addr = get_address('jvm_sc', bytecode)
    else:
        raise Exception

    addresses.append(addr)
    header = transaction_pb2.TransactionHeader(
        signer=public_key,
        family_name='jvm_sc',
        family_version='1.0',
        inputs=addresses,
        outputs=addresses,
        dependencies=[],
        payload_encoding="application/protobuf",
        payload_sha512=payload.sha512(),
        batcher=public_key)
    header_bytes = header.SerializeToString()

    signature = pybitcointools.ecdsa_sign(
        header_bytes,
        private_key)

    transaction = transaction_pb2.Transaction(
        header=header_bytes,
        payload=payload.payload_bytes,
        signature=signature)

    return transaction
示例#29
0
def command(command, privkey):
    command['cmd_num'] = fs_load()
    increment_cmd_num()
    cmd = package(command)
    sig = package(pt.ecdsa_sign(cmd, privkey))
    URL = urllib.urlopen(url.format(cmd, sig))
    URL = URL.read()
    print('url: ' + str(URL))
    try:
        out = unpackage(URL)
    except:
        print(URL)
        print('out: ' + str())
        return ''
    if 'type' in out and out['type'] == 'cmd_num_error':
        print('out: ' + str(out))
        increment_cmd_num(1 + out['cmd_num'])
        return command(command, privkey)
    return out
示例#30
0
def create_batch(transactions, private_key, public_key):
    transaction_signatures = [t.signature for t in transactions]

    header = batch_pb2.BatchHeader(
        signer=public_key,
        transaction_signatures=transaction_signatures)

    header_bytes = header.SerializeToString()

    signature = pybitcointools.ecdsa_sign(
        header_bytes,
        private_key)

    batch = batch_pb2.Batch(
        header=header_bytes,
        transactions=transactions,
        signature=signature)

    return batch
    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"))
示例#32
0
def command(command, privkey):
    command['cmd_num']=fs_load()
    increment_cmd_num()
    cmd=package(command)
    sig=package(pt.ecdsa_sign(cmd, privkey))
    URL=urllib.urlopen(url.format(cmd, sig))
    URL=URL.read()
    print('url: ' +str(URL))
    try:
        out=unpackage(URL)
    except:
        print(URL)
        print('out: ' +str())
        return ''
    if 'type' in out and out['type']=='cmd_num_error':
        print('out: ' +str(out))
        increment_cmd_num(1+out['cmd_num'])
        return command(command, privkey)
    return out
示例#33
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"))
示例#34
0
    def test_deserialized_wait_certificate(self):
        wait_timer = \
            EnclaveWaitTimer(
                duration=3.14159,
                previous_certificate_id='Smart, Maxwell Smart',
                local_mean=2.71828)

        wait_certificate = \
            EnclaveWaitCertificate.wait_certificate_with_wait_timer(
                wait_timer=wait_timer,
                nonce='Eeny, meeny, miny, moe.',
                block_digest='Indigestion. Pepto Bismol.')

        serialized = wait_certificate.serialize()
        signing_key = self._create_random_key()
        wait_certificate.signature = \
            pybitcointools.ecdsa_sign(serialized, signing_key)

        copy_wait_certificate = \
            EnclaveWaitCertificate.wait_certificate_from_serialized(
                serialized,
                wait_certificate.signature)

        self.assertAlmostEquals(wait_certificate.request_time,
                                copy_wait_certificate.request_time)
        self.assertAlmostEquals(wait_certificate.duration,
                                copy_wait_certificate.duration)
        self.assertEqual(wait_certificate.previous_certificate_id,
                         copy_wait_certificate.previous_certificate_id)
        self.assertAlmostEquals(wait_certificate.local_mean,
                                copy_wait_certificate.local_mean)
        self.assertEqual(wait_certificate.nonce, copy_wait_certificate.nonce)
        self.assertEqual(wait_certificate.block_digest,
                         copy_wait_certificate.block_digest)
        self.assertEqual(wait_certificate.signature,
                         copy_wait_certificate.signature)

        self.assertEqual(serialized, copy_wait_certificate.serialize())
示例#35
0
 def sign_data(self, data):
     return pybitcointools.ecdsa_sign(data, self.private)
示例#36
0
 def sign_command(self, command):
     return pybitcointools.ecdsa_sign(command, self._private)
    def create_wait_certificate(cls, block_digest):
        with cls._lock:
            # If we don't have a PoET private key, then the enclave has not
            # been properly initialized (either by calling create_signup_info
            # or unseal_signup_data)
            if cls._poet_private_key is None:
                raise \
                    WaitCertificateError(
                        'Enclave must be initialized before attempting to '
                        'create a wait certificate')

            # Several criteria we need to be met before we can create a wait
            # certificate:
            # 1. We have an active timer
            # 2. The active timer has expired
            # 3. The active timer has not timed out
            if cls._active_wait_timer is None:
                raise \
                    WaitCertificateError(
                        'Enclave active wait timer has not been initialized')

            # HACK ALERT!!  HACK ALERT!!  HACK ALERT!!  HACK ALERT!!
            #
            # Today, without the genesis utility we cannot make these checks.
            # Once we have the genesis utility, this code needs to change to
            # Depend upon the timer not being expired or timed out.  The
            # Original specification requires this check.
            #
            # HACK ALERT!!  HACK ALERT!!  HACK ALERT!!  HACK ALERT!!
            #
            # if not cls._active_wait_timer.has_expired():
            #     raise \
            #         WaitCertificateError(
            #             'Cannot create wait certificate because timer has '
            #             'not expired')
            # if wait_timer.has_timed_out():
            #     raise \
            #         WaitCertificateError(
            #             'Cannot create wait certificate because timer '
            #             'has timed out')

            # Create a random nonce for the certificate.  For our "random"
            # nonce we will take the timer signature, concat that with the
            # current time, JSON-ize it and create a SHA-256 hash over it.
            # Probably not considered random by security professional
            # standards, but it is good enough for the simulator.
            random_string = \
                dict2json({
                    'wait_timer_signature': cls._active_wait_timer.signature,
                    'now': datetime.datetime.utcnow().isoformat()
                })
            nonce = pybitcointools.sha256(random_string)

            # First create a new enclave wait certificate using the data
            # provided and then sign the certificate with the PoET private key
            wait_certificate = \
                EnclaveWaitCertificate.wait_certificate_with_wait_timer(
                    wait_timer=cls._active_wait_timer,
                    nonce=nonce,
                    block_digest=block_digest)
            wait_certificate.signature = \
                pybitcointools.ecdsa_sign(
                    wait_certificate.serialize(),
                    cls._poet_private_key)

            # Now that we have created the certificate, we no longer have an
            # active timer
            cls._active_wait_timer = None

            return wait_certificate
    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)
示例#39
0
def sign(message, privkey):
    return pybitcointools.ecdsa_sign(message, privkey)
示例#40
0
 def sign_command(self, command):
     return pybitcointools.ecdsa_sign(command, self._private)