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 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)
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 Sign(self, NEP2orPrivateKey, NEP2password=None, multisig_args=[]): """ Sign the raw transaction Args: NEP2orPrivateKey: (str) the NEP2 or PrivateKey string from the address you are sending from. NOTE: Assumes WIF if NEP2password is None. NEP2password: (str, optional) the NEP2 password associated with the NEP2 key string. Defaults to None. multisig_args: (list, optional) the arguments for importing a multsig address (e.g. [<owner pubkey>, <num required sigs>, [<signing pubkey>, ...]]) """ temp_path = "temp_wallet.wallet" temp_password = "******" wallet = UserWallet.Create(temp_path, to_aes_key(temp_password), generate_default_key=False) if NEP2password: private_key = KeyPair.PrivateKeyFromNEP2(NEP2orWIF, NEP2password) else: private_key = binascii.unhexlify(NEP2orPrivateKey) wallet.CreateKey(private_key) if multisig_args: # import a multisig address verification_contract = Contract.CreateMultiSigContract( Crypto.ToScriptHash(multisig_args[0], unhex=True), multisig_args[1], multisig_args[2]) wallet.AddContract(verification_contract) if self.Type == b'\xd1' and not self.SOURCE_SCRIPTHASH: # in case of an invocation with no funds transfer context = ContractParametersContext(self) elif not self._context: # used during transactions involving a funds transfer signer_contract = wallet.GetContract(self.SOURCE_SCRIPTHASH) context = ContractParametersContext( self, isMultiSig=signer_contract.IsMultiSigContract) else: context = self._context # used for a follow-on signature for a multi-sig transaction wallet.Sign(context) if context.Completed: self.scripts = context.GetScripts() self.Validate() # ensure the tx is ready to be relayed elif context.ContextItems: self._context = context print( "Transaction initiated, but the signature is incomplete. Sign again with another valid multi-sig keypair." ) else: raise SignatureError("Unable to sign transaction.") wallet.Close() wallet = None os.remove(temp_path)
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)
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))