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))
    def execute(self, arguments):
        wallet = PromptData.Wallet

        if len(arguments) != 1:
            print("Please specify the required parameter")
            return False

        nep2_key = arguments[0]
        passphrase = prompt("[key password] ", is_password=True)

        try:
            kp = KeyPair.PrivateKeyFromNEP2(nep2_key, passphrase)
        except ValueError as e:
            print(str(e))
            return False

        try:
            key = wallet.CreateKey(kp)
            print(f"Imported key: {nep2_key}")
            pub_key = key.PublicKey.encode_point(True).decode('utf-8')
            print(f"Pubkey: {pub_key}")
            print(f"Address: {key.GetAddress()}")

        except Exception as e:
            # couldn't find an exact call that throws this but it was in the old code. Leaving it in for now.
            print(f"Key creation error: {str(e)}")
            return False
 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)
예제 #4
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")
    }
예제 #5
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)
    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))
    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))
예제 #8
0
파일: sign.py 프로젝트: CityOfZion/neosign
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)
예제 #9
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'A utility for signing messages.  Example usage: "np-sign mymessage --wallet_file path/to/my/wallet" or use an NEP2 key/passphrase like "np-sign mymessage -n"'
    )
    parser.add_argument('message',
                        type=str,
                        help='The message in string format to be signed')
    parser.add_argument(
        '-w',
        '--wallet_file',
        type=str,
        default=None,
        help='If using a wallet file, the path to the wallet file')
    parser.add_argument(
        '-a',
        '--address',
        type=str,
        default=False,
        help=
        'If using a wallet file with more than 1 address, the address you would like to use.  Otherwise the default address will be used'
    )
    parser.add_argument(
        '-n',
        '--nep2',
        action='store_true',
        help="Whether to use an NEP2 passhrase rather than a wallet")
    parser.add_argument('--wif',
                        type=str,
                        default=None,
                        help='If using a wif pass in the wif')
    args = parser.parse_args()
    try:

        if args.wallet_file:

            passwd = prompt('[Wallet password]> ', is_password=True)
            wallet = UserWallet.Open(args.wallet_file, to_aes_key(passwd))

            contract = wallet.GetDefaultContract()
            if args.address:
                addr = args.address
                script_hash = Helper.AddrStrToScriptHash(addr)
                contract = wallet.GetContract(script_hash)

                if contract is None:
                    raise Exception('Address %s not found in wallet %s ' %
                                    (addr, args.wallet_file))

            print("Signing With Address %s " % contract.Address)
            signature, pubkey = wallet.SignMessage(args.message,
                                                   contract.ScriptHash)

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

        elif 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)
            contract = Contract.CreateSignatureContract(keypair.PublicKey)
            print("Signing With Address %s " % contract.Address)
            signature = Crypto.Sign(args.message, 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)
            contract = Contract.CreateSignatureContract(keypair.PublicKey)
            print("Signing With Address %s " % contract.Address)
            signature = Crypto.Sign(args.message, prikey)

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

    except Exception as e:
        print("Could not sign: %s " % e)
예제 #10
0
def nep2_to_scripthash(nep2, passphrase):
    private_key = KeyPair.PrivateKeyFromNEP2(nep2, passphrase)
    keypair = KeyPair(priv_key=private_key)
    address = keypair.GetAddress()
    script_hash = address_to_scripthash(address)
    return "0x{}".format(script_hash[::-1].hex())
예제 #11
0
def nep2_to_public_key(nep2, passphrase):
    private_key = KeyPair.PrivateKeyFromNEP2(nep2, passphrase)
    keypair = KeyPair(priv_key=private_key)
    public_key = keypair.PublicKey.encode_point(True)
    return public_key.decode("utf-8")
예제 #12
0
def nep2_to_address(nep2, passphrase):
    private_key = KeyPair.PrivateKeyFromNEP2(nep2, passphrase)
    keypair = KeyPair(priv_key=private_key)
    address = keypair.GetAddress()
    return address
예제 #13
0
def nep2_to_wif(NEP2, passphrase):
    private_key = KeyPair.PrivateKeyFromNEP2(NEP2, passphrase)
    keypair = KeyPair(priv_key=private_key)
    return keypair.Export()