コード例 #1
0
 def test_signature_recoverable(self):
     private_key = PrivateKey(PRIVATE_KEY_BYTES)
     assert (private_key.public_key.format() == PublicKey(
         recover(
             MESSAGE,
             deserialize_recoverable(
                 private_key.sign_recoverable(MESSAGE)))).format())
コード例 #2
0
    def signTx(self, key_bytes, tx_bytes, prevout_n, prevout_script,
               prevout_value):
        tx = self.loadTx(tx_bytes)
        sig_hash = SegwitV0SignatureHash(prevout_script, tx, prevout_n,
                                         SIGHASH_ALL, prevout_value)

        eck = PrivateKey(key_bytes)
        return eck.sign(sig_hash, hasher=None) + bytes((SIGHASH_ALL, ))
コード例 #3
0
ファイル: test_keys.py プロジェクト: kigawas/coincurve
    def test_signature_correct(self):
        private_key = PrivateKey()
        public_key = private_key.public_key

        message = urandom(200)
        signature = private_key.sign(message)

        assert verify_signature(signature, message, public_key.format(compressed=True))
        assert verify_signature(signature, message, public_key.format(compressed=False))
コード例 #4
0
    def check_and_fill_order(self, order):
        if not order or not order.fromToken or not order.toToken or not order.tx:
            return "error"

        if not self.order_exists(order):
            return "unknown"
        
        if not self.order_ready(order):
            return None

        gas_price = self.w3.eth.generateGasPrice()
        logger.debug("Loaded raw gas price {}".format(gas_price))
        gas_price = int(gas_price * float(self.gas_multiplier))

        nonce = self.pull_nonce()

        logger.debug("Using nonce {}, gasprice {}".format(nonce, gas_price))

        secret_pk = PrivateKey(order.secret)
        keccak_hash = keccak.new(digest_bits=256)
        keccak_hash.update(bytearray.fromhex(self.account.address.replace('0x', '')))
        witnesses = secret_pk.sign_recoverable(bytes(bytearray.fromhex(keccak_hash.hexdigest())), hasher=None)

        logger.debug("Signed order {} witnesses {}".format(order.tx, witnesses.hex()))

        calc_witness = Account.privateKeyToAccount(order.secret.hex().replace('0x', '')).address
        if calc_witness != order.witness:
            logger.warn("Witness missmatch order {} witness {} order witness {}".format(order.tx, calc_witness, order.witness))
            return "error"

        logger.debug("Sending tx for order {}".format(order.tx))
        transaction = self.uniswap_ex.functions.executeOrder(
            order.fromToken,
            order.toToken,
            order.minReturn,
            order.fee,
            order.owner,
            witnesses
        ).buildTransaction({
            'gasPrice': gas_price,
            'nonce': nonce,
            'from': self.account.address
        })

        if order.fromToken.lower() not in self.whitelisted_tokens and order.toToken.lower() not in self.whitelisted_tokens and transaction['gas'] * gas_price > order.fee:
            logger.debug("Order {} fee is not enought, cost {} vs {} -> {} * {}".format(order.tx, order.fee, transaction['gas'] * gas_price, transaction['gas'], gas_price))
            return None

        signed_txn = self.w3.eth.account.signTransaction(transaction, private_key=self.account.privateKey)
        logger.debug("Signed tx for order {}".format(order.tx))
        tx = Web3.toHex(self.w3.eth.sendRawTransaction(signed_txn.rawTransaction))
        logger.info("Relayed order {} tx {}".format(order.tx, tx))
        return tx
コード例 #5
0
    def test_sign(self):
        coin_settings = {'rpcport': 0, 'rpcauth': 'none', 'blocks_confirmed': 1, 'conf_target': 1}
        ci = BTCInterface(coin_settings, 'regtest')

        vk = i2b(ci.getNewSecretKey())
        pk = ci.getPubkey(vk)

        message = 'test signing message'
        message_hash = hashlib.sha256(bytes(message, 'utf-8')).digest()
        eck = PrivateKey(vk)
        sig = eck.sign(message.encode('utf-8'))

        ci.verifySig(pk, message_hash, sig)
コード例 #6
0
ファイル: wallet.py プロジェクト: cleancoindev/marmopy-sdk
class Credentials:
    def __init__(self, private_key):
        if private_key.startswith("0x"):
            private_key = private_key[2:]

        self.private_key = PrivateKey(bytes(bytearray.fromhex(private_key)))

    @property
    def address(self):
        keccak_hash = keccak.new(digest_bits=256)
        keccak_hash.update(
            self.private_key.public_key.format(compressed=False, )[1:])
        return to_checksum_address(keccak_hash.digest()[-20:])

    def sign(self, message):
        msg_hash = bytes(bytearray.fromhex(remove_0x_prefix(message)))

        signature_bytes = self.private_key.sign_recoverable(msg_hash,
                                                            hasher=None)

        assert len(signature_bytes) == 65

        r = "0x" + format(big_endian_to_int(signature_bytes[0:32]), "x")
        s = "0x" + format(big_endian_to_int(signature_bytes[32:64]), "x")
        v = hex(ord(signature_bytes[64:65]) + 27)

        return {"r": r, "s": s, "v": v}
コード例 #7
0
ファイル: transactionutils.py プロジェクト: eskal/yadacoin
 def generate_signature(cls, message, private_key):
     x = ffi.new('long long *')
     x[0] = random.SystemRandom().randint(0, sys.maxsize)
     key = PrivateKey.from_hex(private_key)
     signature = key.sign(message.encode('utf-8'),
                          custom_nonce=(ffi.NULL, x))
     return base64.b64encode(signature).decode('utf-8')
コード例 #8
0
ファイル: transactionutils.py プロジェクト: eskal/yadacoin
 def generate_deterministic_signature(cls,
                                      config,
                                      message: str,
                                      private_key=None):
     if not private_key:
         private_key = config.private_key
     key = PrivateKey.from_hex(private_key)
     signature = key.sign(message.encode('utf-8'))
     return base64.b64encode(signature).decode('utf-8')
コード例 #9
0
ファイル: api.py プロジェクト: pdxwebdev/pycenteridentity
 def __init__(self, wif, username):
     self.wif = wif
     self.key = PrivateKey.from_hex(binascii.hexlify(
         base58.b58decode(wif)
     )[2:-10].decode())
     self.public_key = self.key.public_key
     self.username = username
     self.username_signature = self.generate_service_username_signature()
     self.cipher_key = PBKDF2(hashlib.sha256(
         self.wif.encode('utf-8')
     ).hexdigest(), 'salt', 400).read(32)
コード例 #10
0
ファイル: api.py プロジェクト: pdxwebdev/pycenteridentity
 def generate(cls, username):
     num = os.urandom(32).hex()
     wif = cls.to_wif(num)
     inst = cls(wif, username)
     inst.key = PrivateKey.from_hex(num)
     inst.public_key = inst.key.public_key
     inst.username = username
     inst.username_signature = base64.b64encode(
         inst.key.sign(inst.username.encode("utf-8"))
     ).decode("utf-8")
     return inst
コード例 #11
0
ファイル: network.py プロジェクト: cryptoguard/basicswap
    def send_handshake(self, peer):
        self._sc.log.debug('send_handshake %s', peer._address)
        peer._mx.acquire()
        try:
            # TODO: Drain peer._recv_messages
            if not peer._recv_messages.empty():
                self._sc.log.warning(
                    'send_handshake %s - Receive queue dumped.', peer._address)
                while not peer._recv_messages.empty():
                    peer._recv_messages.get(False)

            msg = MsgHandshake()

            msg._timestamp = int(time.time())
            key_r = rfc6979_hmac_sha256_generate(self._csprng, 32)
            k = PrivateKey(key_r)
            msg._ephem_pk = PublicKey.from_secret(key_r).format()
            self.check_handshake_ephem_key(peer, msg._timestamp, msg._ephem_pk)

            ss = k.ecdh(peer._pubkey)

            hashed = hashlib.sha512(
                ss + struct.pack('>Q', msg._timestamp)).digest()
            peer._ke = hashed[:32]
            peer._km = hashed[32:]

            nonce = peer._km[24:]

            payload = self._sc._version

            nk = PrivateKey(self._network_key)
            sig = nk.sign_recoverable(peer._km)
            payload += sig

            aad = msg.encode_aad()
            aad += nonce
            cipher = ChaCha20_Poly1305.new(key=peer._ke, nonce=nonce)
            cipher.update(aad)
            msg._ct, msg._mac = cipher.encrypt_and_digest(payload)

            peer._sent_nonce = hashlib.sha256(nonce + msg._mac).digest()
            peer._recv_nonce = hashlib.sha256(peer._km).digest()  # Init nonce

            peer._last_handshake_at = msg._timestamp
            peer._ready = False  # Wait for peer to complete handshake

            self.send_msg(peer, msg)
        finally:
            peer._mx.release()
コード例 #12
0
    def test_add_update(self):
        private_key = PrivateKey(b'\x01')
        new_private_key = private_key.add(b'\x09', update=True)

        assert new_private_key.to_int() == 10
        assert private_key is new_private_key
コード例 #13
0
 def test_add(self):
     assert PrivateKey(b'\x01').add(b'\x09').to_int() == 10
コード例 #14
0
    def test_ecdh(self):
        a = PrivateKey()
        b = PrivateKey()

        assert a.ecdh(b.public_key.format()) == b.ecdh(a.public_key.format())
コード例 #15
0
 def test_from_der(self):
     assert PrivateKey.from_der(PRIVATE_KEY_DER).secret == PRIVATE_KEY_BYTES
コード例 #16
0
 def test_from_pem(self):
     assert PrivateKey.from_pem(PRIVATE_KEY_PEM).secret == PRIVATE_KEY_BYTES
コード例 #17
0
 def test_from_int(self):
     assert PrivateKey.from_int(PRIVATE_KEY_NUM).secret == PRIVATE_KEY_BYTES
コード例 #18
0
 def test_signature_deterministic(self):
     assert PrivateKey(PRIVATE_KEY_BYTES).sign(MESSAGE) == SIGNATURE
コード例 #19
0
 def test_to_der(self):
     assert PrivateKey(PRIVATE_KEY_BYTES).to_der() == PRIVATE_KEY_DER
コード例 #20
0
 def generate_signature_with_private_key(cls, private_key, message):
     x = ffi.new('long *')
     x[0] = random.SystemRandom().randint(0, sys.maxint)
     key = PrivateKey.from_hex(private_key)
     signature = key.sign(message, custom_nonce=(ffi.NULL, x))
     return base64.b64encode(signature)
コード例 #21
0
 def test_multiply(self):
     assert PrivateKey(b'\x05').multiply(b'\x05').to_int() == 25
コード例 #22
0
    def test_multiply_update(self):
        private_key = PrivateKey(b'\x05')
        new_private_key = private_key.multiply(b'\x05', update=True)

        assert new_private_key.to_int() == 25
        assert private_key is new_private_key
コード例 #23
0
 def test_signature_invalid_hasher(self):
     with pytest.raises(ValueError):
         PrivateKey().sign(MESSAGE, lambda x: sha512(x).digest())
コード例 #24
0
 def test_from_hex(self):
     assert PrivateKey.from_hex(PRIVATE_KEY_HEX).secret == PRIVATE_KEY_BYTES
コード例 #25
0
 def test_to_hex(self):
     assert PrivateKey(PRIVATE_KEY_BYTES).to_hex() == PRIVATE_KEY_HEX
コード例 #26
0
 def test_public_key(self):
     assert PrivateKey(
         PRIVATE_KEY_BYTES).public_key.format() == PUBLIC_KEY_COMPRESSED
コード例 #27
0
    def signCompact(self, k, message):
        message_hash = hashlib.sha256(bytes(message, 'utf-8')).digest()

        privkey = PrivateKey(k)
        return privkey.sign_recoverable(message_hash, hasher=None)[:64]
コード例 #28
0
 def test_to_int(self):
     assert PrivateKey(PRIVATE_KEY_BYTES).to_int() == PRIVATE_KEY_NUM
コード例 #29
0
 def proveDLEAG(self, key):
     privkey = PrivateKey(key)
     return dleag_prove(privkey)
コード例 #30
0
 def test_to_pem(self):
     assert PrivateKey(PRIVATE_KEY_BYTES).to_pem() == PRIVATE_KEY_PEM