def test_wallet_create_successfully(self): """Case both of each wallets are created successfully without a private key.""" wallet1 = KeyWallet.create() wallet2 = KeyWallet.create() self.assertTrue(wallet1.get_address() != wallet2.get_address()) self.assertTrue(is_wallet_address(wallet1.get_address())) self.assertTrue(is_wallet_address(wallet2.get_address()))
def test_wallet_store_overwriting(self): """Case when overwriting the existing keystore file.""" wallet = KeyWallet.create() wallet.store(self.TEST_NEW_PATH, self.TEST_KEYSTORE_FILE_NEW_PASSWORD) wallet2 = KeyWallet.create() self.assertRaises(KeyStoreException, wallet2.store, self.TEST_NEW_PATH, self.TEST_KEYSTORE_FILE_NEW_PASSWORD)
def test_4_register_100_preps_and_check_total_delegated(self): accounts = [KeyWallet.create() for _ in range(100)] tx_list = self._distribute_icx(accounts) self.process_transaction_bulk(tx_list, self.icon_service) tx_list = [] for i in range(100): params = { "name": f"banana node{i}", "email": f"banana@banana{i}.com", "website": f"https://banana{i}.com", "details": f"detail{i}", "publicKey": f"0x1234", "p2pEndPoint": f"target://{i}.213.123.123:7100" } tx = self.create_register_prep_tx(accounts[i], params, step_limit=10000000) tx_list.append(tx) tx_results = self.process_transaction_bulk(tx_list, self.icon_service) for result in tx_results: self.assertEqual(result['status'], 1) # check total delegated # distribute icx delegators = [KeyWallet.create() for _ in range(10)] tx_list = self._distribute_icx(delegators) self.process_transaction_bulk(tx_list, self.icon_service) # stake stake_tx_list = [] for index, key_wallet in enumerate(delegators): tx = self.create_set_stake_tx(key_wallet, 10**18) stake_tx_list.append(tx) self.process_transaction_bulk(stake_tx_list, self.icon_service) # delegate delegate_info_list = [] delegate_amount = [100 - i for i in range(100)] for index, key_wallet in enumerate(accounts): delegate_info = (key_wallet, 100 - index) delegate_info_list.append(delegate_info) delegate_tx_list = [] for index, key_wallet in enumerate(delegators): tx = self.create_set_delegation_tx( key_wallet, delegate_info_list[index * 10:index * 10 + 10], step_limit=10000000) delegate_tx_list.append(tx) self.process_transaction_bulk(delegate_tx_list, self.icon_service) # check total Delegated 50 to 70 response_50_to_70 = self.get_prep_list(50, 70) print(response_50_to_70)
def setUpClass(cls): cls._score_root_path = '.testscore' cls._state_db_root_path = '.teststatedb' cls._icx_factor = 10**18 cls._genesis: 'KeyWallet' = KeyWallet.create() cls._fee_treasury: 'KeyWallet' = KeyWallet.create() cls._test1: 'KeyWallet' = KeyWallet.load( bytes.fromhex(TEST1_PRIVATE_KEY)) cls._wallet_array = [KeyWallet.load(v) for v in TEST_ACCOUNTS]
def transfer(self, conf: dict) -> dict: """Transfer ICX Coin. :param conf: transfer command configuration. :return: response of transfer. """ # check value type (must be int), address and keystore file # if valid, return user input password password = conf.get('password', None) password = self._check_transfer(conf, password) if password: try: wallet = KeyWallet.load(conf['keyStore'], password) from_ = wallet.get_address() except KeyStoreException as e: print(e.args[0]) return None else: # make dummy wallet wallet = KeyWallet.create() from_ = conf['from'] uri, version = uri_parser(conf['uri']) icon_service = IconService(HTTPProvider(uri, version)) transaction = TransactionBuilder() \ .from_(from_) \ .to(conf['to']) \ .value(int(conf['value'])) \ .nid(convert_hex_str_to_int(conf['nid'])) \ .timestamp(int(time() * 10 ** 6)) \ .build() if 'stepLimit' not in conf: step_limit = icon_service.estimate_step(transaction) else: step_limit = convert_hex_str_to_int(conf['stepLimit']) transaction.step_limit = step_limit # Returns the signed transaction object having a signature signed_transaction = SignedTransaction(transaction, wallet) if not password: signed_transaction.signed_transaction_dict['signature'] = 'sig' # Sends transaction and return response response = send_transaction_with_logger(icon_service, signed_transaction, uri) if 'result' in response: print('Send transfer request successfully.') tx_hash = response['result'] print(f"transaction hash: {tx_hash}") else: print('Got an error response') print(json.dumps(response, indent=4)) return response
def _make_account(self, balance: int = 1000) -> 'KeyWallet': # create account account: 'KeyWallet' = KeyWallet.create() # Generates an instance of transaction for sending icx. transaction = TransactionBuilder() \ .from_(self._test1.get_address()) \ .to(account.get_address()) \ .value(balance) \ .step_limit(1000000) \ .nid(3) \ .nonce(100) \ .build() # Returns the signed transaction object having a signature signed_transaction = SignedTransaction(transaction, self._test1) # process the transaction tx_result = self.process_transaction(signed_transaction, self.icon_service) self.assertTrue('status' in tx_result) self.assertEqual(1, tx_result['status']) return account
def test_3_register_one_prep(self): account = KeyWallet.create() tx = self.create_transfer_icx_tx(self._test1, account.get_address(), 10**18) tx_result = self.process_transaction(tx, self.icon_service) self.assertEqual(tx_result['status'], 1) params = { "name": "banana node", "email": "*****@*****.**", "website": "https://banana.com", "details": "detail", "publicKey": "0x1234", "p2pEndPoint": "target://123.213.123.123:7100" } tx = self.create_register_prep_tx(account, params) tx_result = self.process_transaction(tx, self.icon_service) self.assertEqual(tx_result['status'], 1) # set prep on pre-voting params1 = { "name": "apple node", "email": "*****@*****.**", "website": "https://apple.com", "details": "detail", "p2pEndPoint": "target://123.213.123.123:7100" } tx = self.create_set_prep_tx(account, set_data=params1) tx_result = self.process_transaction(tx, self.icon_service) self.assertEqual(tx_result['status'], 1) response = self.get_prep(account) prep_data = response['registration'] self.assertEqual(prep_data['name'], params1['name']) self.assertEqual(prep_data['email'], params1['email']) self.assertEqual(prep_data['website'], params1['website']) self.assertEqual(prep_data['details'], params1['details']) self.assertEqual(prep_data['p2pEndPoint'], params1['p2pEndPoint']) # set irep on pre-voting irep = 40000 params = { "name": "apple node2", "email": "*****@*****.**", "website": "https://apple.com", "details": "detail", "p2pEndPoint": "target://123.213.123.123:7100", } tx = self.create_set_prep_tx(account, irep, params) tx_result = self.process_transaction(tx, self.icon_service) self.assertEqual(tx_result['status'], 0) response = self.get_prep(account) prep_data = response['registration'] self.assertEqual(prep_data['name'], params1['name']) self.assertEqual(prep_data['email'], params1['email']) self.assertEqual(prep_data['website'], params1['website']) self.assertEqual(prep_data['details'], params1['details']) self.assertEqual(prep_data['p2pEndPoint'], params1['p2pEndPoint']) self.assertNotEqual(prep_data['irep'], hex(irep))
def _show_mine(self, _from: KeyWallet = KeyWallet.create()): call = CallBuilder().from_(_from.get_address()) \ .to(self._sample_game_score_address) \ .method("showMine") \ .build() response = self.process_call(call, self.icon_service) return response
def test_wallet_store_successfully(self): """Creates a wallet and validate the wallet.""" wallet = KeyWallet.create() wallet.store(self.TEST_NEW_PATH, self.TEST_KEYSTORE_FILE_NEW_PASSWORD) wallet2 = wallet.load(self.TEST_NEW_PATH, self.TEST_KEYSTORE_FILE_NEW_PASSWORD) self.assertEqual(wallet.get_address(), wallet2.get_address()) self.assertEqual(wallet.get_private_key(), wallet2.get_private_key())
def create_operator_wallet(self): if not self.operator_keystore_path: self.operator_keystore_path = os.path.join(os.path.abspath(Path(self.keystore).parent), '-'.join([os.path.basename(self.keystore), "operator"])) if not self.operator_keystore_password: self.operator_keystore_password = self._generate_random_password() content = KeyWallet.create() content.store(self.operator_keystore_path, self.operator_keystore_password)
def _keystore(args): password = args.password password = _check_keystore(password) content = KeyWallet.create() content.store(args.path, password) print(f"Made keystore file successfully") return 0
def sendtx(self, conf: dict): """Send transaction. :param conf: sendtx command configuration. :return: response of transfer. """ with open(conf['json_file'], 'r') as jf: payload = json.load(jf) password = conf.get('password', None) password = self._check_sendtx(conf, password) params = payload['params'] if password and conf.get('keyStore'): try: wallet = KeyWallet.load(conf['keyStore'], password) params['from'] = wallet.get_address() except KeyStoreException as e: print(e.args[0]) return None else: # make dummy wallet wallet = KeyWallet.create() uri, version = uri_parser(conf['uri']) icon_service = IconService(HTTPProvider(uri, version)) transaction = self.get_transaction(conf, params) if 'stepLimit' not in conf: step_limit = icon_service.estimate_step(transaction) else: step_limit = convert_hex_str_to_int(conf['stepLimit']) transaction.step_limit = step_limit signed_transaction = SignedTransaction(transaction, wallet) if not password: signed_transaction.signed_transaction_dict['signature'] = 'sig' # Sends transaction response = send_transaction_with_logger(icon_service, signed_transaction, uri) if 'result' in response: print('Send transaction request successfully.') tx_hash = response['result'] print(f"transaction hash: {tx_hash}") else: print('Got an error response') print(json.dumps(response, indent=4)) return response
def post(self): parser = reqparse.RequestParser() parser.add_argument('id', type=str) parser.add_argument('password', type=str) args = parser.parse_args(); #DB check wallet = KeyWallet.create() wallet.store("./key/"+args['id'], args['password']); return "PublicKey : " + wallet.get_address() + ", PrivateKey : " + wallet.get_private_key()
def test_duplicated_tx(self): # test start, deploy, stop, clean command conf = self.cmd.cmdUtil.get_init_args(project=self.project_name, score_class=self.project_class) # init self.cmd.cmdUtil.init(conf) # start tbears_config_path = os.path.join(TEST_UTIL_DIRECTORY, f'test_tbears_server_config.json') start_conf = IconConfig(tbears_config_path, tbears_server_config) start_conf.load() start_conf['config'] = tbears_config_path self.start_conf = start_conf self.cmd.cmdServer.start(start_conf) self.assertTrue(self.cmd.cmdServer.is_service_running()) # prepare to send genesis_info = start_conf['genesis']['accounts'][0] from_addr = genesis_info['address'] uri = f'http://127.0.0.1:{start_conf["port"]}/api/v3' uri, version = uri_parser(uri) icon_service = IconService(HTTPProvider(uri, version)) to_addr = f'hx{"d" * 40}' timestamp = int(time.time() * 10**6) transaction = TransactionBuilder()\ .from_(from_addr)\ .to(to_addr)\ .timestamp(timestamp)\ .step_limit(convert_hex_str_to_int('0x100000'))\ .build() wallet = KeyWallet.create() signed_transaction = SignedTransaction(transaction, wallet) signed_transaction.signed_transaction_dict['signature'] = 'sig' # send transaction response = send_transaction_with_logger(icon_service, signed_transaction, uri) self.assertTrue('result' in response) # send again response = send_transaction_with_logger(icon_service, signed_transaction, uri) self.assertTrue('error' in response) self.assertEqual( responseCodeMap[Response.fail_tx_invalid_duplicated_hash][1], response['error']['message'])
def generate_wallet(file, password): from iconsdk.wallet.wallet import KeyWallet # Generates a wallet wallet = KeyWallet.create() # Loads a wallet from a keystore file # wallet = KeyWallet.load("./keystore.json", "password") # # Stores a keystore file on the file path wallet.store(file, password) # throw exception if having an error. # Returns an Address kvPrint("wallet address", wallet.get_address()) # Returns a private key kvPrint("wallet private_key", wallet.get_private_key())
def keystore(self, conf: dict): """Create a keystore file with the specified path and password. :param conf: keystore command configuration """ # check if the given keystore file already exists, and if user input is a valid password password = conf.get('password', None) password = self._check_keystore(password) key_store_content = KeyWallet.create() key_store_content.store(conf['path'], password) print(f"Made keystore file successfully")
def test_4_join_with_custom_preps_and_vote(self): """ 1. Join with 20 ICX, vote for two different preps with 10 ICX each and perform basic checks 2. Second join with additional 10 ICX, which are delegated to first prep in list 3. """ # 1 delegation = { self.prep_list[1]: 6 * 10 ** 18, self.prep_list[2]: 6 * 10 ** 18 } join_tx = self._join(value=12, prep_list=delegation) self.assertTrue(join_tx["status"], msg=pp.pformat(join_tx)) self.assertEqual(len(self._get_wallets()), 1) # check wallet owner = self._get_wallet() self.assertEqual(6 * 10 ** 18, int(owner["delegation_values"][0], 16), msg=pp.pformat(owner)) self.assertEqual(6 * 10 ** 18, int(owner["delegation_values"][1], 16), msg=pp.pformat(owner)) self.assertEqual(self.prep_list[1], owner["delegation_addr"][0], msg=pp.pformat(owner)) self.assertEqual(self.prep_list[2], owner["delegation_addr"][1], msg=pp.pformat(owner)) # check contract staking/delegating self.assertEqual(hex(12 * 10 ** 18), self._get_staked(), msg=pp.pformat(owner)) self.assertEqual(hex(12 * 10 ** 18), self._get_delegation()["totalDelegated"], msg=pp.pformat(owner)) delegations = self._get_delegation()["delegations"] self.assertEqual(hex(6 * 10 ** 18), delegations[0]["value"], msg=pp.pformat(owner)) self.assertEqual(self.prep_list[1], delegations[0]["address"], msg=pp.pformat(owner)) self.assertEqual(hex(6 * 10 ** 18), delegations[1]["value"], msg=pp.pformat(owner)) self.assertEqual(self.prep_list[2], delegations[1]["address"], msg=pp.pformat(owner)) # 2 delegation = {self.prep_list[0]: 10 * 10 ** 18} join_tx = self._join(value=10, prep_list=delegation) self.assertTrue(join_tx["status"], msg=pp.pformat(join_tx)) # check contract staking/delegating self.assertEqual(self._get_staked(), hex(22 * 10 ** 18), msg=pp.pformat(owner)) self.assertEqual(self._get_delegation()["totalDelegated"], hex(22 * 10 ** 18), msg=pp.pformat(owner)) delegations = self._get_delegation()["delegations"] self.assertEqual(delegations[0]["value"], hex(6 * 10 ** 18), msg=pp.pformat(owner)) self.assertEqual(delegations[0]["address"], self.prep_list[1], msg=pp.pformat(owner)) self.assertEqual(delegations[1]["value"], hex(6 * 10 ** 18), msg=pp.pformat(owner)) self.assertEqual(delegations[1]["address"], self.prep_list[2], msg=pp.pformat(owner)) self.assertEqual(delegations[2]["value"], hex(10 * 10 ** 18), msg=pp.pformat(owner)) self.assertEqual(delegations[2]["address"], self.prep_list[0], msg=pp.pformat(owner)) # 3 delegation = {self.prep_list[3]: 50 * 10 ** 18} self._vote(self._wallet, delegation, condition=False) delegation = {KeyWallet.create().get_address(): 22 * 10 ** 18} self._vote(self._wallet, delegation, condition=False) delegation = {self.prep_list[3]: 22 * 10 ** 18} self._vote(self._wallet, delegation, condition=True) next_term = self._getNextTermStart()
def __init__(self, endpoint: str, keystore_path: str, passwd=None) -> None: icon_service, nid = get_icon_service(endpoint) self.tx_handler = TxHandler(icon_service, nid) self.endpoint = endpoint self.owner = load_keystore(keystore_path, passwd) # generate some test accounts if endpoint in ('local', 'gochain'): self.accounts = [] for i in range(2): wallet = KeyWallet.create() self.tx_handler.transfer(self.owner, wallet.get_address(), in_loop(1)) self.accounts.append(wallet)
def test_make_key_store_content(self): # make keystore file content = KeyWallet.create() content.store(self.keystore_path, self.keystore_password) # get private key from keystore file # written_key = key_from_key_store(file_path=self.keystore_path, password=self.keystore_password) written_key = convert_hex_str_to_bytes( KeyWallet.load(self.keystore_path, self.keystore_password).get_private_key()) self.assertTrue(isinstance(written_key, bytes)) os.remove(self.keystore_path)
def createWallet(request): print(request.body) postData = json.loads(request.body) data = json.loads(postData) wallet = KeyWallet.create() wallet_status = { "status" : "ok"} print( os.path.dirname(os.path.abspath(__file__))) if request.session.session_key ==None: request.session.save() os.mkdir(BASE_DIR+"/keystore/"+request.session.session_key+'/') wallet.store( BASE_DIR+"/keystore/"+request.session.session_key+'/'+data['wallet_name'],data['wallet_password']) request.session['wallet_name'] = data['wallet_name'] request.session['wallet_password'] = data['wallet_password'] # file_path = BASE_DIR+wallet.get_address()+"/keystore" # wallet.store(file_path,"keystore") return JsonResponse(wallet_status);
def generate_wallet(result, pattern): try: if result.value: sys.exit() while not result.value: wallet = KeyWallet.create() address = wallet.get_address() private_key = wallet.get_private_key() if address.startswith("hx" + pattern): print("ran for:", round(time.time() - start_time, 2), "seconds") print("address:", address) print("private key:", private_key) result.value = True except KeyboardInterrupt: sys.exit()
def test_icx_token_transfer_ownership(self): new_owner = KeyWallet.create() # Failure case: only owner can transfer ownership send_tx_params = {"_newOwner": new_owner.get_address()} self.assertRaises(AssertionError, transaction_call, super(), self._genesis, self.icx_token_address, "transferOwnerShip", send_tx_params) # Failure case: cannot set new owner as previous owner send_tx_params = {"_newOwner": self._test1.get_address()} self.assertRaises(RevertException, self._icx_call_default, self.icx_token_address, "transferOwnerShip", send_tx_params) # Success case: owner can transfer ownership send_tx_params = {"_newOwner": new_owner.get_address()} self._transaction_call_default(self.icx_token_address, "transferOwnerShip", send_tx_params) # Checks current owner, ownership can not be transferred until accept ownership actual_owner = self._icx_call_default(self.icx_token_address, "getOwner") self.assertEqual(self._test1.get_address(), actual_owner) # Failure case: except new owner, no one cannot accept ownership even owner self.assertRaises(AssertionError, self._transaction_call_default, self.icx_token_address, "acceptOwnerShip", {}) self.assertRaises(AssertionError, transaction_call, super(), self._genesis, self.icx_token_address, "acceptOwnerShip", {}) # Success case: accept ownership tx_result = transaction_call(super(), new_owner, self.icx_token_address, "acceptOwnerShip", {}) # Checks event log self.assertEqual(self._test1.get_address(), tx_result["eventLogs"][0]["indexed"][1]) self.assertEqual(new_owner.get_address(), tx_result["eventLogs"][0]["indexed"][2]) # Checks current owner actual_owner = self._icx_call_default(self.icx_token_address, "getOwner") self.assertEqual(new_owner.get_address(), actual_owner)
def _make_account_bulk(self, accounts: list, balance: int = 1000, count: int = 100) -> None: tx_list: list = [] for i in range(count): # create account account: 'KeyWallet' = KeyWallet.create() accounts.append(account) # Generates an instance of transaction for sending icx. signed_transaction = self.create_transfer_icx_tx(self._test1, account.get_address(), balance) tx_list.append(signed_transaction) # process the transaction tx_results: list = self.process_transaction_bulk(tx_list, self.icon_service) for tx in tx_results: self.assertTrue('status' in tx) self.assertEqual(1, tx['status'])
def test_private_key(self): path = 'keystoretest' password = '******' content = KeyWallet.create() content.store(path, password) # get private key from keystore file written_key = key_from_key_store(file_path=path, password=password) self.assertTrue(isinstance(written_key, bytes)) # wrong password self.assertRaises(KeyStoreException, key_from_key_store, path, 'wrongpasswd') # wrong path self.assertRaises(KeyStoreException, key_from_key_store, 'wrongpath', password) os.remove(path)
def _join_with_new_created_wallet(self) -> KeyWallet: # create a wallet and transfer 11 ICX to it wallet = KeyWallet.create() tx = self._build_transaction(type_="transfer", to=wallet.get_address(), value=11 * 10**18) tx_result = self.process_transaction( SignedTransaction(tx, self._wallet), self._icon_service) self.assertEqual(True, tx_result["status"], msg=pp.pformat(tx_result)) # make a join request tx = self._build_transaction(method="join", from_=wallet.get_address(), params={}, value=10 * 10**18) tx_result = self.process_transaction(SignedTransaction(tx, wallet), self._icon_service) self.assertEqual(True, tx_result["status"], msg=pp.pformat(tx_result)) return wallet
def test_2_register_one_prep_invalid_case2(self): account = KeyWallet.create() tx = self.create_transfer_icx_tx(self._test1, account.get_address(), 10**18) tx_result = self.process_transaction(tx, self.icon_service) self.assertEqual(tx_result['status'], 1) params = { "name": "banana node", "email": "*****@*****.**", "website": "https://banana.com", "details": "detail", "p2pEndPoint": "target://123.213.123.123:7100" } tx = self.create_register_prep_tx(account, params) tx_result = self.process_transaction(tx, self.icon_service) self.assertEqual(tx_result['status'], 0) response = self.get_prep(account) self.assertTrue(response['message'].startswith('P-Rep not found: '))
def setUpClass(cls) -> None: super().setUpClass() if not cls.LOCAL_NETWORK_TEST: cls._wallet = KeyWallet.load("../../keystore_test3", "test3_Account") cls._wallet2 = KeyWallet.load("../../keystore_test2", "test2_Account") cls._icon_service = IconService( HTTPProvider("https://bicon.net.solidwallet.io/api/v3")) cls._score_address = str() cls._fake_sys_score = str() cls.prep_list = cls.PREP_LIST_YEOUIDO else: cls._wallet = cls._test1 cls._wallet2 = KeyWallet.create() cls._icon_service = IconService( HTTPProvider("http://127.0.0.1:9000/api/v3")) cls._score_address = str() cls.prep_list = cls.PREP_LIST_LOCAL
def main(): global args, fastpeer_domains parser = argparse.ArgumentParser(prog='icon_wallet') parser.add_argument('command', nargs='?', help='cat, tail', default="keystore") parser.add_argument('-p', '--password', type=str, help=f'keystore password', default=None) parser.add_argument('-f', '--filename', type=str, help=f'keystore filename', default="keystore.json") args = parser.parse_args() wallet = KeyWallet.create() if args.password is None: print("[ERROR] need a password") sys.exit(127) wallet.store(args.filename, args.password) print(f"store file={args.filename} / password={args.password}")
def create_eoa_accounts(count: int) -> List['EOAAccount']: accounts: list = [] wallets: List['KeyWallet'] = [KeyWallet.create() for _ in range(count)] for wallet in wallets: accounts.append(EOAAccount(wallet)) return accounts
walletPath = os.path.join(currPath, "wallet") if not os.path.exists(walletPath): os.mkdir(walletPath) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # using solidwallet default_ctz_api = "https://ctz.solidwallet.io/api/v3" icon_service = IconService(HTTPProvider(default_ctz_api)) ## Creating Wallet if does not exist (only done for the first time) tester_wallet = os.path.join(walletPath, "test_keystore_1") if os.path.exists(tester_wallet): wallet = KeyWallet.load(tester_wallet, "abcd1234*") else: wallet = KeyWallet.create() wallet.get_address() wallet.get_private_key() wallet.store(tester_wallet, "abcd1234*") tester_address = wallet.get_address() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ## value extraction function def extract_values(obj, key): # Pull all values of specified key from nested JSON arr = [] def extract(obj, arr, key):