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 SystemShare(): 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 test_from_decimal(self): decimal = 2042.02556 f8 = Fixed8.FromDecimal(decimal) self.assertIsInstance(f8, Fixed8) self.assertEqual(f8.value, 204202556000)
def _make_tx(self, addr_to): output1 = TransactionOutput( AssetId = Blockchain.SystemCoin().Hash, Value = Fixed8.FromDecimal(2000), script_hash = addr_to ) output2 = TransactionOutput( AssetId = Blockchain.SystemShare().Hash, Value = Fixed8.FromDecimal(100), script_hash = addr_to ) contract_tx = ContractTransaction() contract_tx.outputs = [output1, output2] contract_tx = self.wallet.MakeTransaction(contract_tx) print("tx to json: %s " % json.dumps(contract_tx.ToJson(), indent=4)) context = ContractParametersContext(contract_tx, isMultiSig=False) self.wallet.Sign(context) if context.Completed: contract_tx.scripts = context.GetScripts() self.wallet.SaveTransaction(contract_tx) # print("will send tx: %s " % json.dumps(tx.ToJson(),indent=4)) relayed = NodeLeader.Instance().Relay(contract_tx) if relayed: print("Relayed Tx: %s " % contract_tx.Hash.ToString()) return contract_tx else: print("Could not relay tx %s " % contract_tx.Hash.ToString()) else: print("Transaction initiated, but the signature is incomplete") print(json.dumps(context.ToJson(), separators=(',', ':'))) return False return False
def test_2_wallet_with_claimable_gas(self): wallet = self.GetWallet3() unspents = wallet.FindUnspentCoinsByAsset(self.NEO) self.assertEqual(2, len(unspents)) unavailable_bonus = wallet.GetUnavailableBonus() self.assertEqual(Fixed8.FromDecimal(0.00036456), unavailable_bonus) unclaimed_coins = wallet.GetUnclaimedCoins() self.assertEqual(4, len(unclaimed_coins)) available_bonus = wallet.GetAvailableClaimTotal() self.assertEqual(Fixed8.FromDecimal(0.0048411), available_bonus)
def SystemCoin(): amount = Fixed8.FromDecimal(sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL) owner = ECDSA.secp256r1().Curve.Infinity precision = 8 admin = Crypto.ToScriptHash(PUSHF) return RegisterTransaction([], [], AssetType.UtilityToken, "[{\"lang\":\"zh-CN\",\"name\":\"小蚁币\"},{\"lang\":\"en\",\"name\":\"AntCoin\"}]", amount, precision, owner, admin)
def construct_contract_withdrawal_request(wallet, arguments, fee=Fixed8.FromDecimal(.001), check_holds=False): if len(arguments) < 4: print("not enough arguments") return False # AG5xbb6QqHSUgDw8cHdyU73R1xy4qD7WEE neo AdMDZGto3xWozB1HSjjVv27RL3zUM8LzpV 20 from_address = get_arg(arguments, 0) to_send = get_arg(arguments, 1) to_address = get_arg(arguments, 2) amount = get_arg(arguments, 3) assetId = get_asset_id(wallet, to_send) f8amount = get_asset_amount(amount, assetId) scripthash_to = wallet.ToScriptHash(to_address) scripthash_from = wallet.ToScriptHash(from_address) withdraw_from_watch_only = get_withdraw_from_watch_only( wallet, scripthash_from) if f8amount is None or scripthash_to is None or withdraw_from_watch_only is None: print("Could not process to or from addr or amount") return False output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) withdraw_tx = InvocationTransaction(outputs=[output]) exclude_vin = None if check_holds: exclude_vin = lookup_contract_holds(wallet, scripthash_from) withdraw_constructed_tx = wallet.MakeTransaction( tx=withdraw_tx, change_address=scripthash_from, fee=fee, from_addr=scripthash_from, use_standard=False, watch_only_val=withdraw_from_watch_only, exclude_vin=exclude_vin) if withdraw_constructed_tx is not None: return withdraw_constructed_tx
def test_1_no_available_claim(self): wallet = self.GetWallet1() unspents = wallet.FindUnspentCoinsByAsset(self.NEO) self.assertEqual(1, len(unspents)) unavailable_bonus = wallet.GetUnavailableBonus() self.assertEqual(Fixed8.FromDecimal(0.124316), unavailable_bonus) unclaimed_coins = wallet.GetUnclaimedCoins() self.assertEqual(0, len(unclaimed_coins)) available_bonus = wallet.GetAvailableClaimTotal() self.assertEqual(Fixed8.Zero(), available_bonus)
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']) balance_should_be = Fixed8.FromDecimal(100) gas_balance = wallet.GetBalance(self.GAS) self.assertEqual(balance_should_be, gas_balance) neo_balance = wallet.GetBalance(self.NEO) self.assertEqual(balance_should_be, neo_balance) self.assertEqual(wallet.WalletHeight, 750131)
def construct_withdrawal_tx(wallet, args): from_address = get_arg(args, 0) assetId = get_asset_id(wallet, get_arg(args, 1)) to_address = get_arg(args, 2) f8amount = get_asset_amount(get_arg(args, 3), assetId) scripthash_to = wallet.ToScriptHash(to_address) scripthash_from = wallet.ToScriptHash(from_address) withdraw_from_watch_only = get_withdraw_from_watch_only( wallet, scripthash_from) if f8amount is None or scripthash_to is None or withdraw_from_watch_only is None: print("Could not process to or from addr or amount") return False requested_vins = get_contract_holds_for_address(wallet, scripthash_from, scripthash_to) use_vins_for_asset = [requested_vins, assetId] output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) withdraw_tx = InvocationTransaction(outputs=[output]) withdraw_constructed_tx = wallet.MakeTransaction( tx=withdraw_tx, change_address=scripthash_from, fee=Fixed8.FromDecimal(.001), from_addr=scripthash_from, use_standard=False, watch_only_val=withdraw_from_watch_only, use_vins_for_asset=use_vins_for_asset) if withdraw_constructed_tx is not None: return withdraw_constructed_tx
def test_deploy_and_invoke(deploy_script, invoke_args, wallet): bc = GetBlockchain() 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) dtx = InvocationTransaction() dtx.Version = 1 dtx.outputs = [] dtx.inputs = [] dtx.scripts = [] dtx.Script = binascii.unhexlify(deploy_script) dtx = wallet.MakeTransaction(tx=dtx) context = ContractParametersContext(dtx) wallet.Sign(context) dtx.scripts = context.GetScripts() script_table = CachedScriptTable(contracts) service = StateMachine(accounts, validators, assets, contracts, storages, None) contract = wallet.GetDefaultContract() dtx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash(contract.Script)) ] engine = ApplicationEngine(trigger_type=TriggerType.Application, container=dtx, table=script_table, service=service, gas=dtx.Gas, testMode=True) engine.LoadScript(dtx.Script, False) # first we will execute the test deploy # then right after, we execute the test invoke try: d_success = engine.Execute() if d_success: items = engine.EvaluationStack.Items contract_state = None for i in items: if type(i) is ContractState: contract_state = i break elif type(i) is InteropInterface: item = i.GetInterface('neo.whatever') if type(item) is ContractState: contract_state = item break shash = contract_state.Code.ScriptHash() invoke_args, neo_to_attach, gas_to_attach = get_asset_attachments( invoke_args) invoke_args.reverse() sb = ScriptBuilder() # print("neo, gas %s %s " % (neo_to_attach,gas_to_attach.ToString())) sb = ScriptBuilder() for p in invoke_args: item = parse_param(p) 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(item) sb.EmitAppCall(shash.Data) out = sb.ToArray() outputs = [] if neo_to_attach: output = TransactionOutput( AssetId=Blockchain.SystemShare().Hash, Value=neo_to_attach, script_hash=contract_state.Code.ScriptHash(), ) outputs.append(output) if gas_to_attach: output = TransactionOutput( AssetId=Blockchain.SystemCoin().Hash, Value=gas_to_attach, script_hash=contract_state.Code.ScriptHash()) outputs.append(output) itx = InvocationTransaction() itx.Version = 1 itx.outputs = outputs itx.inputs = [] itx.scripts = [] itx.Attributes = [] itx.Script = binascii.unhexlify(out) if len(outputs) < 1: contract = wallet.GetDefaultContract() itx.Attributes = [ TransactionAttribute( usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash(contract.Script).Data) ] itx = wallet.MakeTransaction(tx=itx) context = ContractParametersContext(itx) wallet.Sign(context) itx.scripts = context.GetScripts() # print("tx: %s " % json.dumps(itx.ToJson(), indent=4)) engine = ApplicationEngine(trigger_type=TriggerType.Application, container=itx, table=script_table, service=service, gas=itx.Gas, testMode=True) engine.LoadScript(itx.Script, False) i_success = engine.Execute() if i_success: service.TestCommit() if len(service.notifications) > 0: for n in service.notifications: Blockchain.Default().OnNotify(n) consumed = engine.GasConsumed() - Fixed8.FromDecimal(10) consumed.value = int(consumed.value) if consumed < Fixed8.One(): consumed = Fixed8.FromDecimal(.001) total_ops = engine.ops_processed # set the amount of gas the tx will need itx.Gas = consumed itx.Attributes = [] result = engine.ResultsForCode(contract_state.Code) return itx, result, total_ops else: print("error executing invoke contract...") else: print("error executing deploy contract.....") except Exception as e: print("COULD NOT EXECUTE %s " % e) traceback.print_stack() traceback.print_exc() return None, [], 0
def test_invoke(script, wallet, outputs, withdrawal_tx=None): # print("invoke script %s " % script) bc = GetBlockchain() 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) # if we are using a withdrawal tx, don't recreate the invocation tx # also, we don't want to reset the inputs / outputs # since those were already calculated if withdrawal_tx is not None: tx = withdrawal_tx else: tx = InvocationTransaction() tx.outputs = outputs tx.inputs = [] tx.Version = 1 tx.scripts = [] tx.Script = binascii.unhexlify(script) script_table = CachedScriptTable(contracts) service = StateMachine(accounts, validators, assets, contracts, storages, None) if len(outputs) < 1: contract = wallet.GetDefaultContract() tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash( contract.Script).Data) ] # same as above. we don't want to re-make the transaction if it is a withdrawal tx if withdrawal_tx is not None: wallet_tx = tx else: wallet_tx = wallet.MakeTransaction(tx=tx) if wallet_tx: context = ContractParametersContext(wallet_tx) wallet.Sign(context) if context.Completed: wallet_tx.scripts = context.GetScripts() engine = ApplicationEngine(trigger_type=TriggerType.Application, container=wallet_tx, table=script_table, service=service, gas=wallet_tx.Gas, testMode=True) engine.LoadScript(wallet_tx.Script, False) try: # drum roll? success = engine.Execute() if success: service.TestCommit() if len(service.notifications) > 0: for n in service.notifications: Blockchain.Default().OnNotify(n) consumed = engine.GasConsumed() - Fixed8.FromDecimal(10) consumed.value = int(consumed.value) net_fee = None tx_gas = None if consumed < Fixed8.FromDecimal(10.0): net_fee = Fixed8.FromDecimal(.001) tx_gas = Fixed8.Zero() else: tx_gas = consumed net_fee = Fixed8.Zero() # set the amount of gas the tx will need wallet_tx.Gas = tx_gas # reset the wallet outputs wallet_tx.outputs = outputs wallet_tx.Attributes = [] return wallet_tx, net_fee, engine.EvaluationStack.Items, engine.ops_processed else: print("error executing contract.....") return None, None, None, None except Exception as e: print("COULD NOT EXECUTE %s " % e) return None, None, None, None
def test_invoke(script, wallet): bc = GetBlockchain() 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) tx = InvocationTransaction() tx.Version = 0 tx.scripts = [] tx.Script = binascii.unhexlify(script) script_table = CachedScriptTable(contracts) service = StateMachine(accounts, validators, assets, contracts, storages, None) contract = wallet.GetDefaultContract() tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash(contract.Script)) ] engine = ApplicationEngine(trigger_type=TriggerType.Application, container=tx, table=script_table, service=service, gas=tx.Gas, testMode=True) engine.LoadScript(tx.Script, False) try: # drum roll? success = engine.Execute() if success: service.TestCommit() consumed = engine.GasConsumed() - Fixed8.FromDecimal(10) if consumed < Fixed8.One(): consumed = Fixed8.One() #set the amount of gas the tx will need tx.Gas = consumed #remove the attributes that are used to add a verification script to the tx tx.Attributes = [] return tx, engine.EvaluationStack.Items except Exception as e: print("COULD NOT EXECUTE %s " % e) return None, []