def split_to_vouts(asset, addr, input_val, divisions): divisor = Fixed8(divisions) new_amounts = input_val / divisor outputs = [] total = Fixed8.Zero() if asset == Blockchain.Default().SystemShare().Hash: if new_amounts % Fixed8.FD() > Fixed8.Zero(): new_amounts = new_amounts.Ceil() while total < input_val: if total + new_amounts < input_val: outputs.append(TransactionOutput(asset, new_amounts, addr)) total += new_amounts else: diff = input_val - total outputs.append(TransactionOutput(asset, diff, addr)) total += diff return outputs
def get_asset_amount(amount, assetId): f8amount = Fixed8.TryParse(amount) if f8amount is None: print("invalid amount format") elif f8amount.value % pow( 10, 8 - Blockchain.Default().GetAssetState( assetId.ToBytes()).Precision) != 0: print("incorrect amount precision") return None return f8amount
def Verify(self, mempool): """ Verify the transaction. Args: mempool: Returns: bool: True if verified. False otherwise. """ if not super(ClaimTransaction, self).Verify(mempool): return False # wat does this do # get all claim transactinos from mempool list # that are not this claim # and gather all the claims of those claim transactions # and see if they intersect the claims of this transaction # and if that number is greater than zero that we do not verify # (now, to do that in python) # if (mempool.OfType < ClaimTransaction > ().Where(p => p != this).SelectMany(p= > p.Claims).Intersect(Claims).Count() > 0) # return false; # im sorry about the below otherclaimTxs = [ tx for tx in mempool if tx is ClaimTransaction and tx is not self ] for other in otherclaimTxs: # check to see if the length of the intersection between this objects claim's and the other txs claims is > 0 if len([ list(filter(lambda x: x in self.Claims, otherClaims)) for otherClaims in other.Claims ]): return False txResult = None for tx in self.GetTransactionResults(): if tx.AssetId == Blockchain.SystemCoin().Hash: txResult = tx break if txResult is None or txResult.Amount > Fixed8(0): return False try: return Blockchain.CalculateBonusIgnoreClaimed( self.Claims, False) == -txResult.Amount except Exception as e: logger.error('Could not calculate bonus: %s ' % e) return False
def create_tx(contract_hash, address_from, address_to, tnc_amount, gas_change, input_txid, preIndex): nep5TokenId = get_nep5token_id(contract_hash) scripthash_from = ToScriptHash(address_from) scripthash_to = ToScriptHash(address_to) f8amount = amount_from_string(nep5TokenId, tnc_amount) f8amount_change = Fixed8.TryParse(gas_change, require_positive=True) assetId = get_asset_id("gas") preHash = UInt256(data=binascii.unhexlify(hex_reverse(input_txid))) input = TransactionInput(prevHash=preHash, prevIndex=preIndex) output = TransactionOutput(AssetId=assetId, Value=f8amount_change, script_hash=scripthash_from) tx = InvocationTransaction(outputs=[output], inputs=[input]) tx.Version = 1 context = ContractParametersContext(tx) tx.scripts = context.GetScripts() invoke_args = [ nep5TokenId.ScriptHash, 'transfer', [ bytearray.fromhex(hex_reverse(scripthash_from.ToString())), bytearray.fromhex(hex_reverse(scripthash_to.ToString())), BigInteger(f8amount) ] ] sb = ScriptBuilder() invoke_args.reverse() for item in invoke_args[:2]: if type(item) is list: item.reverse() listlength = len(item) for listitem in item: sb.push(listitem) sb.push(listlength) sb.Emit(PACK) else: sb.push(binascii.hexlify(item.encode())) sb.EmitAppCall(nep5TokenId.ScriptHash.ToArray()) op_data = sb.ToArray().decode() tx.Script = binascii.unhexlify(op_data) tx_data = get_tx_data(tx)[:-2] print("tx_data:", tx_data) signstr = binascii.hexlify( Crypto.Sign(message=tx_data, private_key=private_key)).decode() rawtx_data = tx_data + "014140" + signstr + "2321" + public_key + "ac" return rawtx_data
def Run(script, container=None, exit_on_error=False): """ Runs a script in a test invoke environment Args: script (bytes): The script to run container (neo.Core.TX.Transaction): [optional] the transaction to use as the script container Returns: ApplicationEngine """ from neo.Core.Blockchain import Blockchain from neo.SmartContract.StateMachine import StateMachine from neo.EventHub import events bc = Blockchain.Default() sn = bc._db.snapshot() accounts = DBCollection(bc._db, sn, DBPrefix.ST_Account, AccountState) assets = DBCollection(bc._db, sn, DBPrefix.ST_Asset, AssetState) validators = DBCollection(bc._db, sn, DBPrefix.ST_Validator, ValidatorState) contracts = DBCollection(bc._db, sn, DBPrefix.ST_Contract, ContractState) storages = DBCollection(bc._db, sn, DBPrefix.ST_Storage, StorageItem) script_table = CachedScriptTable(contracts) service = StateMachine(accounts, validators, assets, contracts, storages, None) engine = ApplicationEngine( trigger_type=TriggerType.Application, container=container, table=script_table, service=service, gas=Fixed8.Zero(), testMode=True, exit_on_error=exit_on_error ) script = binascii.unhexlify(script) engine.LoadScript(script, False) try: success = engine.Execute() service.ExecutionCompleted(engine, success) except Exception as e: service.ExecutionCompleted(engine, False, e) for event in service.events_to_dispatch: events.emit(event.event_type, event) return engine
def SystemShare(): """ Register AntShare. Returns: RegisterTransaction: """ amount = Fixed8.FromDecimal(sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL) owner = ECDSA.secp256r1().Curve.Infinity admin = Crypto.ToScriptHash(PUSHT) return RegisterTransaction([], [], AssetType.GoverningToken, "[{\"lang\":\"zh-CN\",\"name\":\"小蚁股\"},{\"lang\":\"en\",\"name\":\"AntShare\"}]", amount, 0, owner, admin)
def construct_tx(): assetId = get_asset_id(asset_type) scripthash_to = ToScriptHash(address_to) scripthash_from = ToScriptHash(address_from) f8amount_change = Fixed8.TryParse(change, require_positive=True) f8amount = Fixed8.TryParse(amount, require_positive=True) preHash = UInt256(data=binascii.unhexlify(hex_reverse(input_txid))) input_0 = TransactionInput(prevHash=preHash, prevIndex=preIndex) output_0 = TransactionOutput(AssetId=assetId, Value=f8amount_change, script_hash=scripthash_from) output_1 = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) data = hex_reverse(scripthash_from.ToString()) tx = ContractTransaction(outputs=[output_0, output_1], inputs=[input_0]) tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=bytearray.fromhex(data)) ] return tx
def LoadCoins(self): coins = {} try: for coin in Coin.select(): reference = CoinReference(prev_hash=UInt256(coin.TxId), prev_index=coin.Index) output = TransactionOutput(UInt256(coin.AssetId), Fixed8(coin.Value), UInt160(coin.ScriptHash)) walletcoin = WalletCoin.CoinFromRef(reference, output, coin.State) coins[reference] = walletcoin except Exception as e: logger.error("could not load coins %s " % e) return coins
def _generate_tx(self): wallet = self.GetWallet1() output = TransactionOutput( AssetId=Blockchain.SystemShare().Hash, Value=Fixed8.One(), script_hash=LeaderTestCase.wallet_1_script_hash) contract_tx = ContractTransaction(outputs=[output]) wallet.MakeTransaction(contract_tx) ctx = ContractParametersContext(contract_tx) wallet.Sign(ctx) contract_tx.scripts = ctx.GetScripts() return contract_tx
def __init__(self, *args, **kwargs): """ Create an instance. Args: *args: **kwargs: """ super(InvocationTransaction, self).__init__(*args, **kwargs) self.Type = TransactionType.InvocationTransaction self.Gas = Fixed8(0)
def load_smart_contract(self, args): if not self.Wallet: print("Please open a wallet") return args, from_addr = get_from_addr(args) function_code = LoadContract(args[1:]) if function_code: contract_script = GatherContractDetails(function_code) if contract_script is not None: tx, fee, results, num_ops = test_invoke(contract_script, self.Wallet, [], from_addr=from_addr) if tx is not None and results is not None: print( "\n-------------------------------------------------------------------------------------------------------------------------------------" ) print("Test deploy invoke successful") print("Total operations executed: %s " % num_ops) print("Results:") print([item.GetInterface() for item in results]) print("Deploy Invoke TX GAS cost: %s " % (tx.Gas.value / Fixed8.D)) print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D)) print( "-------------------------------------------------------------------------------------------------------------------------------------\n" ) print( "Enter your password to continue and deploy this contract" ) passwd = prompt("[password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") result = InvokeContract(self.Wallet, tx, Fixed8.Zero(), from_addr=from_addr) return else: print("Test invoke failed") print("TX is %s, results are %s" % (tx, results)) return
def worker(self): self.chain.Pause() BuildAndRun(self.args, wallet=self.wallet, verbose=True) self.chain.Resume() avm_path = self.scPath.replace('.py', '.avm') self.args[0] = avm_path from_addr = None current_height = 0 code = LoadContract(args=self.args) # /scripts/sc.avm 0710 02 True False False if code: script = generate_deploy_script( code.Script, "myTestSmartContract", # name "test", # version "", # author "", # email "", # description code.ContractProperties, code.ReturnTypeBigInteger, code.ParameterList) if script is not None: tx, fee, results, num_ops = test_invoke(script, self.wallet, [], from_addr=from_addr) if tx is not None and results is not None: print("Test deploy invoke successful") print("Deploy Invoke TX GAS cost: %s " % (tx.Gas.value / Fixed8.D)) print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D)) print("-------------------------") while not self.isSynced: self.show_state() time.sleep(1) result = InvokeContract(self.wallet, tx, Fixed8.Zero(), from_addr=from_addr) print("Result: ", result.ToJson(), self.isSynced) print("Result: ", tx.ToJson()) current_height = self.chain.Height + 1 print("Script:", script) # we expect the transaction to be included in the next block: while current_height > self.chain.Height: self.show_state() time.sleep(5) self.twist.stop()
def test_6_split_unspent(self): wallet = self.GetWallet1(True) # test bad tx = SplitUnspentCoin(wallet, []) self.assertEqual(tx, None) # bad inputs tx = SplitUnspentCoin( wallet, ['APRgMZHZubii29UXF9uFa6sohrsYupNAvx', 'neo', 3, 2]) self.assertEqual(tx, None) # should be ok tx = SplitUnspentCoin( wallet, ['APRgMZHZubii29UXF9uFa6sohrsYupNAvx', 'neo', 0, 2], prompt_passwd=False) self.assertIsNotNone(tx) # rebuild wallet and try with non-even amount of neo, should be split into integer values of NEO wallet = self.GetWallet1(True) tx = SplitUnspentCoin( wallet, ['APRgMZHZubii29UXF9uFa6sohrsYupNAvx', 'neo', 0, 3], prompt_passwd=False) self.assertIsNotNone(tx) self.assertEqual([ Fixed8.FromDecimal(34), Fixed8.FromDecimal(34), Fixed8.FromDecimal(32) ], [item.Value for item in tx.outputs]) # try with gas wallet = self.GetWallet1(True) tx = SplitUnspentCoin( wallet, ['APRgMZHZubii29UXF9uFa6sohrsYupNAvx', 'gas', 0, 3], prompt_passwd=False) self.assertIsNotNone(tx)
def BalanceFor(self, assetId): """ Get the balance for a given asset id. Args: assetId (UInt256): Returns: Fixed8: balance value. """ for key, fixed8 in self.Balances.items(): if key == assetId: return fixed8 return Fixed8(0)
def test_1_initial_setup(self): wallet = self.GetWallet1() jsn = wallet.ToJson() addr = jsn['addresses'][0] self.assertEqual(self.wallet_1_addr, addr['script_hash']) gas_balance_should_be = Fixed8.FromDecimal(13.9998) gas_balance = wallet.GetBalance(self.GAS) self.assertEqual(gas_balance_should_be, gas_balance) neo_balance_should_be = Fixed8.FromDecimal(50) neo_balance = wallet.GetBalance(self.NEO) self.assertEqual(neo_balance_should_be, neo_balance) self.assertEqual(wallet.WalletHeight, 12351)
def InvokeContract(wallet, tx, fee=Fixed8.Zero(), from_addr=None, owners=None): if from_addr is not None: from_addr = lookup_addr_str(wallet, from_addr) wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True, from_addr=from_addr) if wallet_tx: if owners: for owner in list(owners): wallet_tx.Attributes.append( TransactionAttribute( usage=TransactionAttributeUsage.Script, data=owner)) wallet_tx.Attributes = make_unique_script_attr(tx.Attributes) context = ContractParametersContext(wallet_tx) wallet.Sign(context) if owners: gather_signatures(context, wallet_tx, list(owners)) if context.Completed: wallet_tx.scripts = context.GetScripts() relayed = False # print("SENDING TX: %s " % json.dumps(wallet_tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(wallet_tx) if relayed: print("Relayed Tx: %s " % wallet_tx.Hash.ToString()) wallet.SaveTransaction(wallet_tx) return wallet_tx else: print("Could not relay tx %s " % wallet_tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False
def parse_send_params(self, params): if len(params) not in [3, 4]: 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_to = params[1] try: address_to_sh = self.wallet.ToScriptHash(address_to) except Exception: raise JsonRpcError(-32602, "Invalid params") amount = Fixed8.TryParse(params[2], require_positive=True) if not amount or float(params[2]) == 0: raise JsonRpcError(-32602, "Invalid params") fee = Fixed8.TryParse(params[3]) if len(params) == 4 else Fixed8.Zero() if fee < Fixed8.Zero(): raise JsonRpcError(-32602, "Invalid params") return asset_id, address_to_sh, amount, fee
def test_owner_and_assets(self): args = [1, 2, "--owners=['APRgMZHZubii29UXF9uFa6sohrsYupNAvx','AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK',]", '--attach-neo=10'] args, owners = Utils.get_owners_from_params(args) args, neo, gas = Utils.get_asset_attachments(args) self.assertEqual(args, [1, 2]) self.assertEqual(len(owners), 2) self.assertIsInstance(list(owners)[0], UInt160) self.assertEqual(neo, Fixed8.FromDecimal(10))
def create_withdraw_tx(wallet, hold): f8amount = Fixed8(hold.Amount) coinRef = CoinReference(prev_hash=hold.TXHash, prev_index=hold.Index) requested_vins = [coinRef] use_vins_for_asset = [requested_vins, hold.AssetId] output = TransactionOutput(AssetId=hold.AssetId, Value=f8amount, script_hash=hold.OutputHash) withdraw_tx = ContractTransaction(outputs=[output]) withdraw_tx.withdraw_hold = hold return wallet.MakeTransaction(tx=withdraw_tx, change_address=hold.InputHash, fee=Fixed8.Zero(), from_addr=hold.InputHash, use_standard=False, watch_only_val=64, use_vins_for_asset=use_vins_for_asset)
def test_build_contract_3(self): """ return from JSON-RPC is: {'state': 'HALT, BREAK', 'script': '06abababababab046b6579310b7075745f616e645f6765746780a1a5b87921dda4603b502ada749890cbca3434', 'stack': [{'type': 'ByteArray', 'value': 'abababababab'}], 'gas_consumed': '1.18'} """ wallet = self.GetWallet1() arguments = [ "neo/SmartContract/tests/StorageTest.py", "True", "False", "True", "070705", "05", "put_and_get", "key1", "b'abababababab'" ] tx, result, total_ops, engine = BuildAndRun(arguments, wallet, False) expected_cost = Fixed8.FromDecimal(1.153) expected_fee = Fixed8.FromDecimal(.0001) self.assertEqual(expected_cost, engine.GasConsumed()) self.assertEqual(tx.Gas, expected_fee) self.assertEqual(result[0].GetByteArray(), bytearray(b'\xab\xab\xab\xab\xab\xab'))
def test_6_split_unspent(self): wallet = self.GetWallet1(recreate=True) # test bad tx = SplitUnspentCoin(wallet, []) self.assertEqual(tx, None) # bad inputs tx = SplitUnspentCoin( wallet, ['AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3', 'neo', 3, 2]) self.assertEqual(tx, None) # should be ok tx = SplitUnspentCoin( wallet, ['AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3', 'neo', 0, 2], prompt_passwd=False) self.assertIsNotNone(tx) # rebuild wallet and try with non-even amount of neo, should be split into integer values of NEO wallet = self.GetWallet1(True) tx = SplitUnspentCoin( wallet, ['AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3', 'neo', 0, 3], prompt_passwd=False) self.assertIsNotNone(tx) self.assertEqual([ Fixed8.FromDecimal(17), Fixed8.FromDecimal(17), Fixed8.FromDecimal(16) ], [item.Value for item in tx.outputs]) # try with gas wallet = self.GetWallet1(True) tx = SplitUnspentCoin( wallet, ['AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3', 'gas', 0, 3], prompt_passwd=False) self.assertIsNotNone(tx)
def DeserializeExclusiveData(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): Raises: Exception: If the version read is incorrect. """ if self.Version > 1: raise Exception('Invalid format') self.Script = reader.ReadVarBytes() if len(self.Script) == 0: raise Exception('Invalid Format') if self.Version >= 1: self.Gas = reader.ReadFixed8() if self.Gas < Fixed8.Zero(): raise Exception("Invalid Format") else: self.Gas = Fixed8(0)
def test_9_send_neo_tx(self): wallet = self.GetWallet1() tx = ContractTransaction() tx.outputs = [TransactionOutput(Blockchain.SystemShare().Hash, Fixed8.FromDecimal(10.0), self.import_watch_addr)] tx = wallet.MakeTransaction(tx) cpc = ContractParametersContext(tx) wallet.Sign(cpc) tx.scripts = cpc.GetScripts() result = NodeLeader.Instance().Relay(tx) self.assertEqual(result, True)
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 test_build_contract(self): """ return from JSON-RPC is: {'state': 'HALT, BREAK', 'script': '01ab066b6579313233037075746780a1a5b87921dda4603b502ada749890cbca3434', 'stack': [{'type': 'Integer', 'value': '1'}], 'gas_consumed': '1.056'} """ wallet = self.GetWallet1() arguments = [ "neo/SmartContract/tests/StorageTest.py", "True", "False", "True", "070705", "05", "put", "key1", "b'ab'", "--from-addr=" + self.wallet_1_addr ] tx, result, total_ops, engine = BuildAndRun( arguments, wallet, False, min_fee=Fixed8.FromDecimal(.0004)) expected_cost = Fixed8(103900000) expected_fee = Fixed8.FromDecimal(.0004) self.assertEqual(expected_cost, engine.GasConsumed()) self.assertEqual(tx.Gas, expected_fee) self.assertEqual(bool(result), True)
def SubtractFromBalance(self, assetId, fixed8_val): """ Subtract amount to the specified balance. Args: assetId (UInt256): fixed8_val (Fixed8): amount to add. """ found = False for key, balance in self.Balances.items(): if key == assetId: self.Balances[assetId] = self.Balances[assetId] - fixed8_val found = True if not found: self.Balances[assetId] = fixed8_val * Fixed8(-1)
def test_register_tx(self): ms = MemoryStream(binascii.unhexlify(self.rr)) reader = BinaryReader(ms) tx = Transaction.DeserializeFrom(reader) self.assertEqual(self.rrid, tx.Hash.ToBytes()) json = tx.ToJson() asset = json['asset'] self.assertEqual(asset['admin'], 'ARFe4mTKRTETerRoMsyzBXoPt2EKBvBXFX') self.assertEqual(asset['name'], '[{"lang":"zh-CN","name":"TestCoin"}]') self.assertEqual(asset['precision'], 8) self.assertEqual( Fixed8.FromDecimal(settings.ALL_FEES['RegisterTransaction']), tx.SystemFee())
def GetUnavailableBonus(self): """ Gets the total claimable amount of Gas in the wallet that is not available to claim because it has not yet been spent. Returns: Fixed8: the amount of Gas unavailable to claim. """ height = Blockchain.Default().Height + 1 unspents = self.FindUnspentCoinsByAsset(Blockchain.SystemShare().Hash) refs = [coin.Reference for coin in unspents] try: unavailable_bonus = Blockchain.CalculateBonus(refs, height_end=height) return unavailable_bonus except Exception as e: pass return Fixed8(0)
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_testnet10412011(self): block = Helper.AsSerializableWithType(self.block_bytes, 'neo.Core.Block.Block') self.assertEqual(len(block.Transactions), 2) state_tx = block.Transactions[1] self.assertIsInstance(state_tx, StateTransaction) self.assertEqual(len(state_tx.Descriptors), 1) descriptor = state_tx.Descriptors[0] self.assertIsInstance(descriptor, StateDescriptor) self.assertEqual(descriptor.Type, StateType.Validator) self.assertEqual(descriptor.SystemFee, Fixed8.FromDecimal(1000)) self.assertEqual( descriptor.Key, binascii.unhexlify( b'03c089d7122b840a4935234e82e26ae5efd0c2acb627239dc9f207311337b6f2c1' ))