示例#1
0
 def __init__(self,
              api_net=MAIN_NET,
              fees=0.0015,
              private_key=None,
              fee_token_name=None,
              discount=0.5):
     """
     Create new Switcheo exchange with url, fee rate and private key
     :param api_net:
     :param fees:
     :param private_key:
     """
     self.url = Switcheo._API_URL[api_net]
     self.tokens = []
     self.pairs = []
     self.contracts = []
     self.fees = fees
     self.fee_token_name = fee_token_name
     self.fee_token = None
     self.key_pair = None
     self.discount = discount
     self.client = AuthenticatedClient(api_url=self.url)
     if private_key:
         try:
             self.key_pair = KeyPair(bytes.fromhex(private_key))
         except:
             self.key_pair = None
             print(
                 "No or incorrect private key. Equalizer changes to view only mode"
             )
示例#2
0
    def test_long_private_key(self):
        # Taken from the neo-python UserWallet test
        priv_key = b'[\\\x8c\xdc\xb3/\x8e\'\x8e\x11\x1a\x0b\xf5\x8e\xbbF9\x88\x02K\xb4\xe2P\xaaC\x10\xb4\x02R\x03\x0b`\xdd\xc4\x99[\xac\x00)\x8b"s\x1d\xe7\xa8?\xa4\x9d\xed*\xce\xeai\xfa=\xd8r\x93p \xc8\xa9\xb6\xc6ad\xf6V\x9b#\xdfX\xc5Ltnv\x84%\x1a\x17e:K2\xf1\xb4JW\x03\xfd\xad\x94\x8eu]'
        kp = KeyPair(priv_key)

        expected_result = b'025b5c8cdcb32f8e278e111a0bf58ebb463988024bb4e250aa4310b40252030b60'
        self.assertEqual(expected_result, kp.PublicKey.encode_point(True))
示例#3
0
def create_wallet():
    private_key = bytes(Random.get_random_bytes(32))
    keypair = KeyPair(priv_key=private_key)
    return {
        "private_key": keypair.Export(),
        "address": keypair.GetAddress()
    }
示例#4
0
    def test_sign_and_verify(self):
        privkey = KeyPair.PrivateKeyFromWIF(
            "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP")
        keypair = KeyPair(privkey)
        hashdata = b'aabbcc'

        keypair_signature = Crypto.Sign(hashdata, bytes(keypair.PrivateKey))
        keypair_signature2 = Crypto.Default().Sign(hashdata,
                                                   bytes(keypair.PrivateKey))
        self.assertEqual(keypair_signature, keypair_signature2)

        verification_result = Crypto.VerifySignature(hashdata.decode('utf8'),
                                                     keypair_signature,
                                                     keypair.PublicKey)
        verification_result2 = Crypto.Default().VerifySignature(
            hashdata.decode('utf8'), keypair_signature, keypair.PublicKey)
        self.assertEqual(verification_result, verification_result2)
        self.assertTrue(verification_result)

        # verify with compressed key
        verification_result3 = Crypto.VerifySignature(
            hashdata.decode('utf8'), keypair_signature,
            binascii.unhexlify(keypair.PublicKey.encode_point(True)))
        self.assertTrue(verification_result3)

        # this should fail because the signature will not match the input data
        verification_result = Crypto.VerifySignature(b'aabb',
                                                     keypair_signature,
                                                     keypair.PublicKey)
        self.assertFalse(verification_result)
示例#5
0
    def test_fail_to_determine_plublic_key(self, patched_priv_to_pubkey):
        # https://github.com/vbuterin/pybitcointools/blob/aeb0a2bbb8bbfe421432d776c649650eaeb882a5/bitcoin/main.py#L291
        patched_priv_to_pubkey.side_effect = Exception("Invalid privkey")

        with self.assertRaises(Exception) as context:
            KeyPair(bytes(32 * 'A', 'utf8'))
        self.assertEqual('Could not determine public key',
                         str(context.exception))
 def test_should_export_valid_wif_key(self):
     kp = KeyPair(
         binascii.unhexlify(
             "cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5"
         ))
     wif = kp.Export()
     self.assertEqual(
         wif, "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP")
    def test_should_throw_error_on_too_short_passphrase(self):
        kp = KeyPair(
            binascii.unhexlify(
                "cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5"
            ))
        with self.assertRaises(ValueError) as context:
            kp.ExportNEP2("x")

        self.assertIn('Passphrase must have a minimum', str(context.exception))
 def test_should_export_valid_nep2_key(self):
     kp = KeyPair(
         binascii.unhexlify(
             "cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5"
         ))
     nep2_key = kp.ExportNEP2("TestingOneTwoThree")
     self.assertEqual(
         nep2_key,
         "6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL")
    def test_publickey_to_scripthash(self):
        expected_scripthash = binascii.unhexlify(
            '79ecf967a02f9bdbd147fc97b18efd7877d27f78')
        priv_key = KeyPair.PrivateKeyFromWIF(
            'L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP')
        kp = KeyPair(priv_key=priv_key)
        pub_bytes = kp.PublicKey.encode_point(True)

        result = Helper.pubkey_to_pubhash(pub_bytes)
        self.assertEqual(result, expected_scripthash)
示例#10
0
def get_private_key_from_wif(wif):
    """Fetch the private key from a wif represented in string format.

    Args:
        wif (str) : wif from which we need to extract the private key

    Returns:
        private key in bytearray format
    """
    pk = KeyPair.PrivateKeyFromWIF(wif)
    return KeyPair(pk).PrivateKey
示例#11
0
    def test_neon_sig(self):

        key = KeyPair(priv_key=self.nmpk)

        hhex = hashlib.sha256(binascii.unhexlify(self.nmsg)).hexdigest()

        self.assertEqual(hhex, self.hashhex)

        sig = Crypto.Sign(self.nmsg, key.PrivateKey)

        self.assertEqual(sig.hex(), self.neon_sig)
    def test_should_export_valid_nep2_key_with_emoji_pwd(self):
        pwd = "hellö♥️"
        privkey = "03eb20a711f93c04459000c62cc235f9e9da82382206b812b07fd2f81779aa42"

        # expected outputs
        target_address = "AXQUduANGZF4e7wDazVAtyRLHwMounaUMA"
        target_encrypted_key = "6PYWdv8bP9vbfGsNnjzDawCoXCYpk4rnWG8xTZrvdzx6FjB6jv4H9MM586"

        kp = KeyPair(binascii.unhexlify(privkey))
        nep2_key = kp.ExportNEP2(pwd)
        self.assertEqual(nep2_key, target_encrypted_key)
        self.assertEqual(kp.GetAddress(), target_address)
示例#13
0
def nep2_to_wallet(NEP2, passphrase):
    private_key = KeyPair.PrivateKeyFromNEP2(NEP2, passphrase)
    keypair = KeyPair(priv_key=private_key)
    public_key = keypair.PublicKey.encode_point(True)
    address = keypair.GetAddress()
    script_hash = address_to_scripthash(address)
    return {
        "private_key": keypair.Export(),
        "address": address,
        "script_hash": "0x{}".format(script_hash[::-1].hex()),
        "public_key": public_key.decode("utf-8")
    }
示例#14
0
def create_wallet():
    private_key = bytes(Random.get_random_bytes(32))
    keypair = KeyPair(priv_key=private_key)
    public_key = keypair.PublicKey.encode_point(True)
    address = keypair.GetAddress()
    script_hash = address_to_scripthash(address)
    return {
        "private_key": keypair.Export(),
        "address": address,
        "script_hash": "0x{}".format(script_hash[::-1].hex()),
        "public_key": public_key.decode("utf-8")
    }
示例#15
0
    def test_b(self):

        key = KeyPair(priv_key=self.pk)

        contract = Contract.CreateSignatureContract(key.PublicKey)

        self.assertEqual(binascii.unhexlify(contract.Script), self.contract_script)
        self.assertEqual(contract.ScriptHash.ToBytes(), self.contract_script_hash)

        self.assertEqual(contract.Address, self.contract_address)

        self.assertEqual(contract.PublicKeyHash, key.PublicKeyHash)
        self.assertEqual(contract.PublicKeyHash.ToBytes(), self.pubkeyhash)
示例#16
0
def get_script_hash_from_wif(wif):
    """Fetch the script hash of the public key from a wif represented in string format.

    Args:
        wif (str) : wif from which we need to extract the public key script hash

    Returns:
        public key script hash in string format
    """
    pk = KeyPair.PrivateKeyFromWIF(wif)
    keypair = KeyPair(pk)
    logger.debug("Public Address is {}".format(keypair.GetAddress()))
    return get_script_hash_from_address(keypair.GetAddress())
示例#17
0
 def new_wallet(self, request):
     request.setHeader('Content-Type', 'application/json')
     private_key = bytes(Random.get_random_bytes(32))
     key = KeyPair(priv_key=private_key)
     return json.dumps(
         {
             'public_key': str(key.PublicKey.encode_point(True), 'utf-8'),
             'public_key_hash': key.PublicKeyHash.ToString(),
             'private_key': key.PrivateKey.hex(),
             'wif': key.Export(),
             'address': key.GetAddress()
         },
         indent=4,
         sort_keys=True)
示例#18
0
    def CreateKey(self, private_key=None):
        """
        Create a KeyPair

        Args:
            private_key (iterable_of_ints): (optional) 32 byte private key

        Returns:
            KeyPair: a KeyPair instance
        """
        if private_key is None:
            private_key = bytes(Random.get_random_bytes(32))

        key = KeyPair(priv_key=private_key)
        self._keys[key.PublicKeyHash.ToBytes()] = key
        return key
示例#19
0
    def test_c(self):

        key = KeyPair(priv_key=self.decrypted_pk)

        self.assertEqual(key.PublicKey.x, self.pubkey_x)
        self.assertEqual(key.PublicKey.y, self.pubkey_y)

        self.assertEqual(key.PublicKey.encode_point(True), self.pubkey_encoded)
        self.assertEqual(key.PublicKey.encode_point(False), self.pubkey_not_comp)

        self.assertIsInstance(key.PublicKeyHash, UInt160)

        self.assertEqual(key.PublicKeyHash.ToBytes(), self.pubkeyhash)
        self.assertEqual(key.Export(), self.wif)

        private_key_from_wif = KeyPair.PrivateKeyFromWIF(self.wif)

        self.assertEqual(private_key_from_wif, self.pk)
示例#20
0
    def test_publickey_to_redeemscript_to_scripthash_to_address(self):
        # NEP 2 testvector
        expected_redeemscript = binascii.unhexlify(
            '21026241e7e26b38bb7154b8ad49458b97fb1c4797443dc921c5ca5774f511a2bbfcac'
        )
        expected_scripthash = binascii.unhexlify(
            '79ecf967a02f9bdbd147fc97b18efd7877d27f78')
        expected_address = 'AStZHy8E6StCqYQbzMqi4poH7YNDHQKxvt'

        priv_key = KeyPair.PrivateKeyFromWIF(
            'L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP')
        kp = KeyPair(priv_key=priv_key)
        pub_bytes = kp.PublicKey.encode_point(True)
        redeemscript = Helper.pubkey_to_redeem(pub_bytes)
        scripthash = Helper.redeem_to_scripthash(redeemscript)
        address = Helper.scripthash_to_address(scripthash)

        self.assertEqual(redeemscript, expected_redeemscript)
        self.assertEqual(scripthash, expected_scripthash)
        self.assertEqual(address, expected_address)
示例#21
0
def SendBlog(wallet, tx, fee=Fixed8.Zero(), from_addr=None, privatekey=None):
    wallet_tx = wallet.MakeTransaction(tx=tx,
                                       fee=fee,
                                       use_standard=False,
                                       from_addr=from_addr)
    # wallet_tx = tx
    if wallet_tx:
        context = ContractParametersContext(wallet_tx)
        if privatekey != None:
            prikey = KeyPair.PrivateKeyFromWIF(privatekey)
            kp = KeyPair(prikey)
            wallet.Sign(context, kp)
        else:
            wallet.Sign(context)

        if context.Completed:

            wallet_tx.scripts = context.GetScripts()

            relayed = False

            #            print("SENDING TX: %s " % json.dumps(wallet_tx.ToJson(), indent=4))

            relayed = NodeLeader.Instance().Relay(wallet_tx)
            print("Tx: %s " % wallet_tx.ToJson())
            if relayed:
                print("Relayed Tx: %s " % wallet_tx.Hash.ToString())

                wallet.SaveTransaction(wallet_tx)

                return wallet_tx
            else:
                print("Could not relay tx %s " % wallet_tx.Hash.ToString())
        else:

            print("Incomplete signature")

    else:
        print("Insufficient funds")

    return False
示例#22
0
 def get_data_from_wif(self, request, wif):
     request.setHeader('Content-Type', 'application/json')
     try:
         print("get_data_from_wif ", wif)
         private_key = KeyPair.PrivateKeyFromWIF(wif)
         key = KeyPair(priv_key=private_key)
         return json.dumps(
             {
                 'public_key': str(key.PublicKey.encode_point(True),
                                   'utf-8'),
                 'public_key_hash': key.PublicKeyHash.ToString(),
                 'private_key': key.PrivateKey.hex(),
                 'wif': key.Export(),
                 'address': key.GetAddress()
             },
             indent=4,
             sort_keys=True)
     except Exception as e:
         return self.format_message(
             "Error: Could not get data from wif %s " % (wif))
     return self.format_message("Could not get data from wif %s " % (wif))
示例#23
0
 def test_get_contains_key_should_not_be_found(self):
     wallet = Wallet("fakepath", to_aes_key("123"), True)
     wallet.CreateKey()
     keypair = KeyPair(priv_key=self.pk)
     self.assertFalse(wallet.ContainsKey(keypair.PublicKey))
示例#24
0
import unittest
from switcheo.neo.utils import create_offer_hash, encode_message, to_neo_asset_amount, private_key_to_hex, open_wallet,\
    neo_get_scripthash_from_address, neo_get_address_from_scripthash, neo_get_scripthash_from_private_key,\
    neo_get_public_key_from_private_key, sign_message, sign_transaction, sign_txn_array
from neocore.KeyPair import KeyPair


testnet_privatekey = b'p\xf6B\x89K\xc7=\xc5\x00\x13\xbem\x1d\xbe\x19\x8fC#~\xaf\x94X\xd1\x93\xc0\xb4\x16\xc58]\x97\x17'
kp = KeyPair(priv_key=testnet_privatekey)
testnet_privatekey_hexstring = '70f642894bc73dc50013be6d1dbe198f43237eaf9458d193c0b416c5385d9717'
testnet_scripthash = 'fea2b883725ef2d194c9060f606cd0a0468a2c59'
testnet_scripthash_uint160 = neo_get_scripthash_from_private_key(private_key=testnet_privatekey)
testnet_address = 'APuP9GsSCPJKrexPe49afDV8CQYubZGWd8'
testnet_publickey = '303231353534363535356234326164643737343933636332316462356461396639376163646666343966346433653739633239666363303361303661356539373662'

message = 'This is a test.'
encoded_message = '010001f0112254686973206973206120746573742e220000'
json_message = {"name": "John Smith", "age": 27, "siblings": ["Jane", "Joe"]}
json_encoded_message = '010001f0387b22616765223a32372c226e616d65223a224a6f686e20536d697468222c227369626c696e6773223a5b224a616e65222c224a6f65225d7d0000'

transaction_dict = {'hash': '72b74c96b9174e9b9e1b216f7e8f21a6475e6541876a62614df7c1998c6e8376',
                    'sha256': '2109cbb5eea67a06f5dd8663e10fcd1128e28df5721a25d993e05fe2097c34f3',
                    'type': 209,
                    'version': 1,
                    'attributes': [{'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'}],
                    'inputs': [{'prevHash': 'f09b3b697c580d1730cd360da5e1f0beeae00827eb2f0055cbc85a5a4dadd8ea', 'prevIndex': 0},
                               {'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 31}],
                    'outputs': [{'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08}],
                    'scripts': [],
                    'script': '0800e1f505000000001432e125258b7db0a0dffde5bd03b2b859253538ab14592c8a46a0d06c600f06c994d1f25e7283b8a2fe53c1076465706f73697467823b63e7c70a795a7615a38d1ba67d9e54c195a1',
                    'gas': 0}
示例#25
0
def privtKey_to_publicKey(privtKey):

    pk = binascii.unhexlify(privtKey)
    keypair = KeyPair(pk)
    vk = keypair.PublicKey.encode_point(True).decode()
    return vk
 def test_should_return_valid_address(self):
     kp = KeyPair(
         binascii.unhexlify(
             "cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5"
         ))
     self.assertEqual(kp.GetAddress(), "AStZHy8E6StCqYQbzMqi4poH7YNDHQKxvt")
 def test_wrong_private_key_length(self):
     priv_key = b'\xDE\xAD\xBE\xEF'
     with self.assertRaises(ValueError) as context:
         KeyPair(priv_key)
     self.assertEqual('Invalid private key', str(context.exception))
示例#28
0
def neo_get_public_key_from_private_key(private_key):
    kp = KeyPair(priv_key=private_key)
    return kp.PublicKey
示例#29
0
def open_wallet(private_key):
    pk = bytes.fromhex(private_key)
    return KeyPair(priv_key=pk)
示例#30
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'A utility for signing messages.  Example usage: "like "neosign mymessage -n"'
    )
    parser.add_argument('message',
                        type=str,
                        nargs='?',
                        default=None,
                        help='The message in hex string format to be signed')
    parser.add_argument(
        '-n',
        '--nep2',
        action='store_true',
        help="Whether to use an NEP2 passhrase rather than a wallet")
    parser.add_argument('-w',
                        '--wif',
                        type=str,
                        default=None,
                        help='If using a wif pass in the wif')
    parser.add_argument('-i',
                        '--input',
                        type=str,
                        default=None,
                        help='Pass in file with signable contents')
    args = parser.parse_args()
    try:

        to_sign = None
        if args.message:
            to_sign = args.message

        elif args.input:
            f = open(args.input, 'r')
            to_sign = f.read()
            regex = re.compile(r'\s+')
            to_sign = regex.sub('', to_sign)

        if args.nep2:

            nep2_key = prompt('[nep2 key]> ', is_password=True)
            nep2_passwd = prompt("[nep2 key password]> ", is_password=True)

            prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd)
            keypair = KeyPair(priv_key=prikey)
            address = addr_from_pubkey(keypair.PublicKey)
            print("Signing With Address %s " % address)
            signature = Crypto.Sign(to_sign, prikey)

            pubkey = keypair.PublicKey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

        elif args.wif:
            prikey = KeyPair.PrivateKeyFromWIF(args.wif)
            keypair = KeyPair(priv_key=prikey)
            address = addr_from_pubkey(keypair.PublicKey)
            print("Signing With Address %s " % address)
            signature = Crypto.Sign(to_sign, prikey)

            pubkey = keypair.PublicKey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

        else:
            raise Exception("Please Specify -n or -w")
    except Exception as e:
        print("Could not sign: %s " % e)