def test_various_methods(self): self.assertEqual(Fixed8.FD(), Fixed8(100000000)) self.assertEqual(Fixed8.FD(), Fixed8.One()) sat = Fixed8.Satoshi() self.assertEqual(sat, Fixed8(1)) self.assertEqual(sat.value, 1) negsat = Fixed8.NegativeSatoshi() self.assertEqual(negsat, Fixed8(-1)) self.assertEqual(negsat.value, -1) zero = Fixed8.Zero() self.assertEqual(zero, Fixed8(0)) self.assertEqual(zero.value, 0) decimal = 1.2 f8 = Fixed8.FromDecimal(decimal) self.assertEqual(f8.value, f8.GetData()) f8 = Fixed8.TryParse(123.123) f8 = Fixed8.TryParse(123) self.assertEqual(f8.Size(), 8) zero = Fixed8.TryParse(0) self.assertEqual(zero, Fixed8(0)) self.assertEqual(Fixed8.TryParse("foo"), None) self.assertEqual(Fixed8.TryParse(-1, require_positive=True), None)
def parse_send_from_params(self, params): if len(params) not in [4, 5, 6]: raise JsonRpcError(-32602, "Invalid params") asset_id = get_asset_id(self.wallet, params[0]) if not type(asset_id) is UInt256: raise JsonRpcError(-32602, "Invalid params") address_from = params[1] try: address_from_sh = self.wallet.ToScriptHash(address_from) except Exception: raise JsonRpcError(-32602, "Invalid params") address_to = params[2] try: address_to_sh = self.wallet.ToScriptHash(address_to) except Exception: raise JsonRpcError(-32602, "Invalid params") amount = Fixed8.TryParse(params[3], require_positive=True) if not amount or float(params[3]) == 0: raise JsonRpcError(-32602, "Invalid params") output = TransactionOutput(AssetId=asset_id, Value=amount, script_hash=address_to_sh) contract_tx = ContractTransaction(outputs=[output]) fee = Fixed8.TryParse(params[4]) if len(params) >= 5 else Fixed8.Zero() if fee < Fixed8.Zero(): raise JsonRpcError(-32602, "Invalid params") change_addr_sh = None if len(params) >= 6: change_addr = params[5] try: change_addr_sh = self.wallet.ToScriptHash(change_addr) except Exception: raise JsonRpcError(-32602, "Invalid params") return contract_tx, address_from_sh, fee, change_addr_sh
def parse_send_many_params(self, params): if type(params[0]) is not list: raise JsonRpcError(-32602, "Invalid params") if len(params) not in [1, 2, 3]: raise JsonRpcError(-32602, "Invalid params") output = [] for info in params[0]: asset = get_asset_id(self.wallet, info['asset']) if not type(asset) is UInt256: raise JsonRpcError(-32602, "Invalid params") address = info["address"] try: address = self.wallet.ToScriptHash(address) except Exception: raise JsonRpcError(-32602, "Invalid params") amount = Fixed8.TryParse(info["value"], require_positive=True) if not amount or float(info["value"]) == 0: raise JsonRpcError(-32602, "Invalid params") tx_output = TransactionOutput(AssetId=asset, Value=amount, script_hash=address) output.append(tx_output) contract_tx = ContractTransaction(outputs=output) fee = Fixed8.TryParse(params[1]) if len(params) >= 2 else Fixed8.Zero() if fee < Fixed8.Zero(): raise JsonRpcError(-32602, "Invalid params") change_addr_sh = None if len(params) >= 3: change_addr = params[2] try: change_addr_sh = self.wallet.ToScriptHash(change_addr) except Exception: raise JsonRpcError(-32602, "Invalid params") return contract_tx, fee, change_addr_sh
def get_asset_attachments(params): to_remove = [] neo_to_attach = None gas_to_attach = None for item in params: if type(item) is str: if '--attach-neo=' in item: to_remove.append(item) try: neo_to_attach = Fixed8.TryParse( int(item.replace('--attach-neo=', ''))) except Exception as e: pass if '--attach-gas=' in item: to_remove.append(item) try: gas_to_attach = Fixed8.FromDecimal( float(item.replace('--attach-gas=', ''))) except Exception as e: pass for item in to_remove: params.remove(item) return params, neo_to_attach, gas_to_attach
def AddOutput(self, asset, to_addr, amount): """ Specify an output for the transaction. NOTE: Can be used multiple times to create multiple outputs. Args: asset: (str) the asset name or asset hash to_addr: (str) the destination NEO address (e.g. 'AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3') amount: (int/decimal) the amount of the asset to send """ if asset[0:1] == "0x": asset == asset[2:] if asset.lower() == "neo": assetId = self.neo_asset_id elif asset == self.neo_asset_id: assetId = self.neo_asset_id elif asset.lower() == "gas": assetId = self.gas_asset_id elif asset == self.gas_asset_id: assetId = self.gas_asset_id else: raise AssetError( f'Asset {asset} not found. If trying to send tokens use the `buildTokenTransfer` function.' ) dest_scripthash = Helper.AddrStrToScriptHash( to_addr) # also verifies if the address is valid if float(amount) == 0: raise ValueError('Amount cannot be 0.') f8amount = Fixed8.TryParse(amount, require_positive=True) if f8amount is None: raise ValueError('Invalid amount format.') elif assetId == self.neo_asset_id and (f8amount.value / Fixed8.D) != f8amount.ToInt(): raise ValueError('Incorrect amount precision.') # check if the outputs exceed the available unspents subtotal = [] if self.outputs: for output in self.outputs: if output.AssetId == assetId: subtotal.append(output.Value.value) total = f8amount.value + sum(subtotal) total = float(Fixed8(total).ToString()) for asset in self.BALANCE: if assetId == asset['asset_hash']: if total > asset['amount']: raise AssetError( 'Total outputs exceed the available unspents.') self.outputs.append( TransactionOutput(AssetId=UInt256.ParseString(assetId), Value=f8amount, script_hash=dest_scripthash))
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) < 4: print("Please specify the required parameters") return if len(arguments) > 5: # the 5th argument is the optional attributes, print("Too many parameters supplied. Please check your command") return addr = arguments[0] if not isValidPublicAddress(addr): print("Invalid address specified") return try: from_addr = wallet.ToScriptHash(addr) except ValueError as e: print(str(e)) return asset_id = PromptUtils.get_asset_id(wallet, arguments[1]) if not asset_id: print(f"Unknown asset id: {arguments[1]}") return try: index = int(arguments[2]) except ValueError: print(f"Invalid unspent index value: {arguments[2]}") return try: divisions = int(arguments[3]) except ValueError: print(f"Invalid divisions value: {arguments[3]}") return if divisions < 2: print("Divisions cannot be lower than 2") return if len(arguments) == 5: fee = Fixed8.TryParse(arguments[4], require_positive=True) if not fee: print(f"Invalid fee value: {arguments[4]}") return else: fee = Fixed8.Zero() return SplitUnspentCoin(wallet, asset_id, from_addr, index, divisions, fee)
def get_asset_amount(amount, assetId): f8amount = Fixed8.TryParse(amount, require_positive=True) if f8amount is None: print("invalid amount format") return False elif f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState(assetId.ToBytes()).Precision) != 0: print("incorrect amount precision") return False return f8amount
def test_get_transaction(self): # delete any tx in the mempool self._clear_mempool() # generate a new tx tx = self._generate_tx(Fixed8.TryParse(5)) # try to get it res = NodeLeader.Instance().GetTransaction(tx.Hash.ToBytes()) self.assertIsNone(res) # now add it to the mempool NodeLeader.Instance().MemPool[tx.Hash.ToBytes()] = tx # and try to get it res = NodeLeader.Instance().GetTransaction(tx.Hash.ToBytes()) self.assertTrue(res is tx)
def test_mempool_check_loop(self): # delete any tx in the mempool self._clear_mempool() # add a tx which is already confirmed self._add_existing_tx() # and add a tx which is not confirmed tx = self._generate_tx(Fixed8.TryParse(20)) NodeLeader.Instance().MemPool[tx.Hash.ToBytes()] = tx # now remove the confirmed tx NodeLeader.Instance().MempoolCheck() self.assertEqual( len( list( map(lambda hash: "0x%s" % hash.decode('utf-8'), NodeLeader.Instance().MemPool.keys()))), 1)
def test_inventory_received(self): leader = NodeLeader.Instance() miner = MinerTransaction() miner.Nonce = 1234 res = leader.InventoryReceived(miner) self.assertFalse(res) block = Blockchain.Default().GenesisBlock() res2 = leader.InventoryReceived(block) self.assertFalse(res2) tx = self._generate_tx(Fixed8.TryParse(15)) res = leader.InventoryReceived(tx) self.assertIsNone(res)