示例#1
0
def create_wallet(request):
    try:
        body = json.loads(request.content.read().decode("utf-8"))
    except JSONDecodeError as e:
        request.setResponseCode(400)
        return build_error(STATUS_ERROR_JSON, "JSON Error: %s" % str(e))

    # Fail if not a password
    if not "password" in body:
        request.setResponseCode(400)
        return build_error(STATUS_ERROR_JSON, "No password in request body.")

    # Fail if no good password
    pwd = body["password"]
    if len(pwd) < 8:
        request.setResponseCode(400)
        return build_error(STATUS_ERROR_JSON, "Password needs a minimum length of 8 characters.")

    private_key = bytes(Random.get_random_bytes(32))
    key = KeyPair(priv_key=private_key)

    return {
        "address": key.GetAddress(),
        "nep2_key": key.ExportNEP2(pwd)
    }
示例#2
0
    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)
示例#3
0
    def do_import(self, arguments):
        item = get_arg(arguments)

        if item:

            if item == 'wif':

                if not self.Wallet:
                    print("Please open a wallet before importing WIF")
                    return

                wif = get_arg(arguments, 1)

                if wif:
                    prikey = KeyPair.PrivateKeyFromWIF(wif)
                    if prikey:

                        key = self.Wallet.CreateKey(prikey)
                        print("imported key %s " % wif)
                        print("Pubkey: %s \n" %
                              key.PublicKey.encode_point(True).hex())
                        print("Wallet: %s " %
                              json.dumps(self.Wallet.ToJson(), indent=4))
                    else:
                        print("invalid wif")
                    return

            elif item == 'contract':
                return self.load_smart_contract(arguments)

            elif item == 'contract_addr':
                return ImportContractAddr(self.Wallet, arguments[1:])

        print("please specify something to import")
        return
示例#4
0
 def test_should_work(self):
     nep2_key = "6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL"
     pwd = "TestingOneTwoThree"
     should_equal_private_key = b"cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5"
     privkey = KeyPair.PrivateKeyFromNEP2(nep2_key, pwd)
     privkey_hex = binascii.hexlify(privkey)
     self.assertEqual(privkey_hex, should_equal_private_key)
示例#5
0
    def test_should_throw_error_on_invalid_password(self):
        nep2_key = "6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL"
        pwd = "invalid-pwd"
        with self.assertRaises(ValueError) as context:
            KeyPair.PrivateKeyFromNEP2(nep2_key, pwd)

        self.assertEqual('Wrong passphrase', str(context.exception))
示例#6
0
文件: Wallet.py 项目: lcux/neo-python
    def CreateKeyPairFromPrivateKey(self, private_key):

        keypair = KeyPair(private_key=private_key)

        self._keys[keypair.PublicKeyHash] = keypair

        return keypair
示例#7
0
    def do_import(self, arguments):
        item = self.get_arg(arguments)

        if item and item == 'wif':

            if not self.Wallet:
                print("Please open a wallet before importing WIF")
                return

            wif = self.get_arg(arguments, 1)

            if wif:
#                self.Wallet.
                prikey = KeyPair.PrivateKeyFromWIF(wif)
                if prikey:

                    key = self.Wallet.CreateKey(prikey)
                    print("imported key %s " % wif)
                    print("Pubkey: %s \n" % key.PublicKey.encode_point(True).hex())
                    print("Wallet: %s " % json.dumps(self.Wallet.ToJson(), indent=4))
                else:
                    print("invalid wif")
                return
            else:
                print("Please specify a wif")
                return

        print("please specify something to import")
        return
示例#8
0
    def CreateKey(self):
        private_key = bytes(Random.get_random_bytes(32))
        #        self.__log.debug("private key %s " % private_key)

        key = KeyPair(priv_key=private_key)
        self._keys[key.PublicKeyHash.ToBytes()] = key
        self.__log.debug("keys %s " % self._keys.items())
        return key
示例#9
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))
示例#10
0
    def run(self):

        to_addr = self.target_address

        dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
        dbloop.start(.1)

        Blockchain.Default().PersistBlocks()

        wallets = []
        i = 0
        tx_json = ''

        print("Signing new transaction with 3 of 4 node keys...")

        for pkey, wif in nodekeys.items():
            walletpath = "wallet{}.db3".format(i + 1)
            if os.path.exists(walletpath):
                os.remove(walletpath)
            wallet = UserWallet.Create(path=walletpath, password=mypassword)
            wallets.append(wallet)

            print("Importing node private key to to {}".format(walletpath))
            prikey = KeyPair.PrivateKeyFromWIF(wif)
            wallet.CreateKey(prikey)

            print("Importing multi-sig contract to {}".format(walletpath))
            multisig_args = [pkey, '3']
            multisig_args.extend(list(nodekeys.keys()))
            ImportMultiSigContractAddr(wallet, multisig_args)

            dbloop = task.LoopingCall(wallet.ProcessBlocks)
            dbloop.start(1)

            while Blockchain.Default().Height < 2:
                print("Waiting for wallet to sync...")
                time.sleep(1)

            #print("Wallet %s " % json.dumps(wallet.ToJson(), indent=4))

            if i == 0:
                print("Creating spend transaction to {}".format(to_addr))
                tx_json = self.begin_send(
                    wallet, ['neo', to_addr, '100000000', multisig_addr])
                if tx_json is None:
                    break
            else:
                tx_json = self.sign_and_finish(wallet, tx_json)

            if tx_json == 'success':
                print(
                    "Finished, {} should now own all the NEO on the private network."
                    .format(to_addr))
                break
            i += 1

        self.quit()
示例#11
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)
示例#12
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, key.PublicKey)

        self.assertEqual(sig.hex(), self.neon_sig)
示例#13
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)
示例#14
0
    def test_6_import_wif(self):

        wallet = self.GetWallet1()

        key_to_import = 'L3MBUkKU5kYg16KSZnqcaTj2pG5ei3fN9A4X7rxXys18GBDa3bH8'

        prikey = KeyPair.PrivateKeyFromWIF(key_to_import)
        keypair = wallet.CreateKey(prikey)

        key_out = keypair.PublicKey.encode_point(True).decode('utf-8')

        self.assertEqual(
            key_out,
            '03f3a3b5a4d873933fc7f4b53113e8eb999fb20038271fbbb10255585670c3c312'
        )
示例#15
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
示例#16
0
    def test_should_throw_error_on_invalid_checksum(self):
        # build fake wif
        fakewif = bytearray(34 * 'A', 'utf8')
        fakewif[0] = 0x80
        fakewif[33] = 0x01
        # fake checksum
        fakewif.append(0xDE)
        fakewif.append(0xAD)
        fakewif.append(0xBE)
        fakewif.append(0xEF)

        encodedFakeWIF = base58.b58encode(bytes(fakewif))

        with self.assertRaises(ValueError) as context:
            KeyPair.PrivateKeyFromWIF(encodedFakeWIF)

        self.assertEqual('Invalid WIF Checksum!', str(context.exception))
示例#17
0
    def claim_initial_neo(self, target_address):
        wallets = []
        i = 0
        tx_json = None
        dbloops = []

        print("Signing new transaction with 3 of 4 node keys...")
        for pkey, wif in nodekeys.items():
            walletpath = "wallet{}.db3".format(i + 1)
            if os.path.exists(walletpath):
                os.remove(walletpath)
            wallet = UserWallet.Create(path=walletpath,
                                       password=self.wallet_pwd)
            wallets.append(wallet)

            print("Importing node private key to to {}".format(walletpath))
            prikey = KeyPair.PrivateKeyFromWIF(wif)
            wallet.CreateKey(prikey)

            print("Importing multi-sig contract to {}".format(walletpath))
            multisig_args = [pkey, '3']
            multisig_args.extend(list(nodekeys.keys()))
            ImportMultiSigContractAddr(wallet, multisig_args)

            dbloop = task.LoopingCall(wallet.ProcessBlocks)
            dbloop.start(1)
            dbloops.append(dbloop)

            # print("Wallet %s " % json.dumps(wallet.ToJson(), indent=4))

            if i == 0:
                print(
                    "Creating spend transaction to {}".format(target_address))
                tx_json = self.send_neo(wallet, multisig_addr, target_address,
                                        '100000000')
                if tx_json is None:
                    break
            else:
                tx_json = self.sign_and_finish(wallet, tx_json)

            if tx_json == 'success':
                print(
                    "Finished, {} should now own all the NEO on the private network."
                    .format(target_address))
                break
            i += 1
示例#18
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, key.PublicKey)

        self.assertEqual(sig.hex(), self.neon_sig)


#    def test_sig_verify(self):
#        key = KeyPair(priv_key=self.nmpk)

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

#        self.assertEqual(sig.hex(), self.neon_sig)

#        verify = Crypto.VerifySignature(self.nmsg, sig, key.PublicKey)

#        print("verify? " % verify)
示例#19
0
 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))
示例#20
0
 def test_should_export_valid_wif_key(self):
     kp = KeyPair(binascii.unhexlify("cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5"))
     wif = kp.Export()
     self.assertEqual(wif, "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP")
示例#21
0
    def test_should_throw_error_on_too_short_wif(self):
        with self.assertRaises(ValueError) as context:
            KeyPair.PrivateKeyFromWIF('brokenwif')

        self.assertIn('Please provide a wif with a length of 52 bytes', str(context.exception))
示例#22
0
    def test_should_throw_error_on_invalid_wif(self):
        with self.assertRaises(ValueError) as context:
            KeyPair.PrivateKeyFromWIF(52 * 'A')

        self.assertEqual('Invalid format!', str(context.exception))
示例#23
0
    def test_should_throw_error_on_too_short_nep2_key(self):
        with self.assertRaises(ValueError) as context:
            KeyPair.PrivateKeyFromNEP2('invalid', 'pwd')

        self.assertIn('Please provide a nep2_key with a length of 58 bytes', str(context.exception))
示例#24
0
    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))
示例#25
0
 def test_should_return_valid_address(self):
     kp = KeyPair(binascii.unhexlify("cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5"))
     self.assertEqual(kp.GetAddress(), "AStZHy8E6StCqYQbzMqi4poH7YNDHQKxvt")
示例#26
0
 def test_get_contains_key_should_not_be_found(self):
     wallet = Wallet("fakepath", "123", True)
     wallet.CreateKey()
     keypair = KeyPair(priv_key=self.pk)
     self.assertFalse(wallet.ContainsKey(keypair.PublicKey))
示例#27
0
    def do_import(self, arguments):
        item = get_arg(arguments)

        if not item:
            print("please specify something to import")
            return

        if item == 'wif':
            if not self.Wallet:
                print("Please open a wallet before importing WIF")
                return

            wif = get_arg(arguments, 1)
            if not wif:
                print("Please supply a valid WIF key")
                return

            try:
                prikey = KeyPair.PrivateKeyFromWIF(wif)
                key = self.Wallet.CreateKey(prikey)
                print("Imported key %s " % wif)
                print("Pubkey: %s \n" % key.PublicKey.encode_point(True).hex())
                print("Wallet: %s " %
                      json.dumps(self.Wallet.ToJson(), indent=4))
            except ValueError as e:
                print(str(e))
            except Exception as e:
                print(str(e))

            return

        elif item == 'nep2':
            if not self.Wallet:
                print("Please open a wallet before importing a NEP2 key")
                return

            nep2_key = get_arg(arguments, 1)
            if not nep2_key:
                print("Please supply a valid nep2 encrypted private key")
                return

            nep2_passwd = prompt("[Key Password]> ", is_password=True)

            try:
                prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd)
                key = self.Wallet.CreateKey(prikey)
                print("Imported nep2 key: %s " % nep2_key)
                print("Pubkey: %s \n" % key.PublicKey.encode_point(True).hex())
                print("Wallet: %s " %
                      json.dumps(self.Wallet.ToJson(), indent=4))
            except ValueError as e:
                print(str(e))
            except Exception as e:
                print(str(e))

            return

        elif item == 'contract':
            return self.load_smart_contract(arguments)

        elif item == 'contract_addr':
            return ImportContractAddr(self.Wallet, arguments[1:])

        elif item == 'watch_addr':
            return ImportWatchAddr(self.Wallet, get_arg(arguments, 1))

        elif item == 'multisig_addr':
            return ImportMultiSigContractAddr(self.Wallet, arguments[1:])

        elif item == 'token':
            return ImportToken(self.Wallet, get_arg(arguments, 1))

        else:
            print("Import of '%s' not implemented" % item)
示例#28
0
    def test_should_throw_error_on_invalid_nep2_key(self):
        with self.assertRaises(ValueError) as context:
            KeyPair.PrivateKeyFromNEP2(58 * 'A', 'pwd')

        self.assertEqual('Invalid nep2_key', str(context.exception))
示例#29
0
 def test_should_work(self):
     privkey = KeyPair.PrivateKeyFromWIF("L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP")
     self.assertEqual(binascii.hexlify(privkey), b"cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5")
示例#30
0
 def test_should_export_valid_nep2_key(self):
     kp = KeyPair(binascii.unhexlify("cbf4b9f70470856bb4f40f80b87edb90865997ffee6df315ab166d713af433a5"))
     nep2_key = kp.ExportNEP2("TestingOneTwoThree")
     self.assertEqual(nep2_key, "6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL")