def send_neo(wallet, address_from, address_to, amount): assetId = None assetId = Blockchain.Default().SystemShare().Hash scripthash_to = wallet.ToScriptHash(address_to) scripthash_from = wallet.ToScriptHash(address_from) f8amount = Fixed8.TryParse(amount) if f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState(assetId.ToBytes()).Precision) != 0: raise Exception("incorrect amount precision") fee = Fixed8.Zero() output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=scripthash_to) tx = ContractTransaction(outputs=[output]) ttx = wallet.MakeTransaction(tx=tx, change_address=None, fee=fee, from_addr=scripthash_from) if ttx is None: raise Exception("insufficient funds, were funds already moved from multi-sig contract?") context = ContractParametersContext(tx, isMultiSig=True) wallet.Sign(context) if context.Completed: raise Exception("Something went wrong, multi-sig transaction failed") else: print("Transaction initiated") return json.dumps(context.ToJson(), separators=(',', ':'))
def __init__(self, asset_id=None, asset_type=None, name=None, amount=Fixed8(0), available=Fixed8(0), precision=0, fee_mode=0, fee=Fixed8(0), fee_addr=UInt160(data=bytearray(20)), owner=None, admin=None, issuer=None, expiration=None, is_frozen=False): self.AssetId = asset_id self.AssetType = asset_type self.Name = name self.Amount = amount self.Available = available self.Precision = precision self.FeeMode = fee_mode self.Fee = fee self.FeeAddress = fee_addr if owner is not None and type(owner) is not EllipticCurve.ECPoint: raise Exception("Owner must be ECPoint Instance") self.Owner = owner self.Admin = admin self.Issuer = issuer self.Expiration = expiration self.IsFrozen = is_frozen
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_fixed8_div(self): f1 = Fixed8(27) f2 = Fixed8(3) f3 = f1 / f2 self.assertIsInstance(f3, Fixed8) self.assertEqual(f3.value, 9)
def test_fixed8_mul(self): f1 = Fixed8(3) f2 = Fixed8(9) f3 = f1 * f2 self.assertIsInstance(f3, Fixed8) self.assertEqual(f3.value, 27)
def test_fixed8_sub(self): f1 = Fixed8(100) f2 = Fixed8(300) f3 = f1 - f2 self.assertIsInstance(f3, Fixed8) self.assertEqual(f3.value, -200)
def test_fixed8_add(self): f1 = Fixed8(100) f2 = Fixed8(300) f3 = f1 + f2 self.assertIsInstance(f3, Fixed8) self.assertEqual(f3.value, 400)
def test_fixed8_pow(self): f1 = Fixed8(2) f2 = Fixed8(3) f3 = pow(f1, f2) self.assertIsInstance(f3, Fixed8) self.assertEqual(f3.value, 8)
def SystemFee(self): if self.Version >= 1: return Fixed8.Zero() # if all outputs are NEO or gas, return 0 all_neo_gas = True for output in self.outputs: if output.AssetId != GetSystemCoin().Hash and output.AssetId != GetSystemShare().Hash: all_neo_gas = False if all_neo_gas: return Fixed8.Zero() return Fixed8(int(settings.ISSUE_TX_FEE))
def CalculateBonusInternal(unclaimed): amount_claimed = Fixed8.Zero() decInterval = Blockchain.DECREMENT_INTERVAL genAmount = Blockchain.GENERATION_AMOUNT genLen = len(genAmount) for coinheight, group in groupby(unclaimed, lambda x: x.Heights): amount = 0 ustart = int(coinheight.start / decInterval) if ustart < genLen: istart = coinheight.start % decInterval uend = int(coinheight.end / decInterval) iend = coinheight.end % decInterval if uend >= genLen: iend = 0 if iend == 0: uend -= 1 iend = decInterval while ustart < uend: amount += (decInterval - istart) * genAmount[ustart] ustart += 1 istart = 0 amount += (iend - istart) * genAmount[ustart] endamount = Blockchain.Default().GetSysFeeAmountByHeight( coinheight.end - 1) startamount = 0 if coinheight.start == 0 else Blockchain.Default( ).GetSysFeeAmountByHeight(coinheight.start - 1) amount += endamount - startamount outputSum = 0 for spentcoin in group: outputSum += spentcoin.Value.value outputSum = outputSum / 100000000 outputSumFixed8 = Fixed8(int(outputSum * amount)) amount_claimed += outputSumFixed8 return amount_claimed
def test_fixed8_mod(self): f1 = Fixed8(10) f2 = Fixed8(5) f3 = f1 % f2 self.assertIsInstance(f3, Fixed8) self.assertEqual(f3.value, 0) f4 = Fixed8(7) f5 = f1 % f4 self.assertEqual(f5.value, 3)
def DeserializeExclusiveData(self, reader): 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 InvokeContract(wallet, tx, fee=Fixed8.Zero()): wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee) if wallet_tx: context = ContractParametersContext(wallet_tx) wallet.Sign(context) if context.Completed: wallet_tx.scripts = context.GetScripts() wallet.SaveTransaction(wallet_tx) relayed = NodeLeader.Instance().Relay(wallet_tx) if relayed: print("Relayed Tx: %s " % tx.Hash.ToString()) return True else: print("Could not relay tx %s " % tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False
def Account_SetVotes(self, engine): try: account = engine.EvaluationStack.Pop().GetInterface( 'neo.Core.State.AccountState.AccountState') vote_list = engine.EvaluationStack.Pop().GetArray() except Exception as e: self.__log.debug("could not get account or votes: %s " % e) return False if account is None or len(vote_list) > 1024: return False if account.IsFrozen: return False balance = account.BalanceFor(Blockchain.SystemShare().Hash) if balance == Fixed8.Zero() and len(vote_list) > 0: print("no balance, return false!") return False print("Setting votes!!!") acct = self._accounts.GetAndChange(account.AddressBytes) voteset = set() for v in vote_list: voteset.add(v.GetByteArray()) acct.Votes = list(voteset) print("*****************************************************") print("SET ACCOUNT VOTES %s " % json.dumps(acct.ToJson(), indent=4)) print("*****************************************************") return True
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 Run(script, container=None): from neo.Core.Blockchain import Blockchain from neo.SmartContract.StateMachine import StateMachine 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 ) engine.LoadScript(script, False) engine.Execute() return engine
def __init__(self, inputs=None, outputs=None, assettype=AssetType.GoverningToken, assetname='', amount=Fixed8(0), precision=0, owner=None, admin=None): super(RegisterTransaction, self).__init__(inputs, outputs) self.Type = TransactionType.RegisterTransaction # 0x40 self.AssetType = assettype self.Name = assetname self.Amount = amount # Unlimited Mode: -0.00000001 if inputs is not None: self.inputs = inputs else: self.inputs = [] if outputs is not None: self.outputs = outputs else: self.outputs = [] if owner is not None and type(owner) is not EllipticCurve.ECPoint: raise Exception("Invalid owner, must be ECPoint instance") self.Owner = owner self.Admin = admin self.Precision = precision
def InvokeWithTokenVerificationScript(wallet, tx, token, fee=Fixed8.Zero()): wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True) if wallet_tx: token_contract_state = Blockchain.Default().GetContract( token.ScriptHash.ToString()) print("token contract %s " % token_contract_state) tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=token.ScriptHash.Data) ] reedeem_script = token_contract_state.Code.Script.hex() # there has to be at least 1 param, and the first # one needs to be a signature param param_list = bytearray(b'\x00\x00') verification_contract = Contract.Create( reedeem_script, param_list, wallet.GetDefaultContract().PublicKeyHash) context = ContractParametersContext(wallet_tx) wallet.Sign(context) context.Add(verification_contract, 0, 0) if context.Completed: wallet_tx.scripts = context.GetScripts() relayed = False # print("full wallet tx: %s " % json.dumps(wallet_tx.ToJson(), indent=4)) # check if we can save the tx first save_tx = wallet.SaveTransaction(wallet_tx) if save_tx: relayed = NodeLeader.Instance().Relay(wallet_tx) else: print("Could not save tx to wallet, will not send tx") if relayed: print("Relayed Tx: %s " % wallet_tx.Hash.ToString()) 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 SubtractFromBalance(self, assetId, fixed8_val): found = False for key, balance in self.Balances.items(): if key == assetId: self.Balances[assetId] = self.Balances[assetId] - fixed8_val if not found: self.Balances[assetId] = fixed8_val * Fixed8(-1)
def GetBalance(self, asset_id, watch_only=0): """ Get the balance of a specific token by its asset id. Args: asset_id (NEP5Token|TransactionOutput): an instance of type neo.Wallets.NEP5Token or neo.Core.TX.Transaction.TransactionOutput to get the balance from. watch_only (bool): True, to limit to watch only wallets. Returns: Fixed8: total balance. """ total = Fixed8(0) if type(asset_id) is NEP5Token: return self.GetTokenBalance(asset_id, watch_only) for coin in self.GetCoins(): if coin.Output.AssetId == asset_id: if coin.State & CoinState.Confirmed > 0 and \ coin.State & CoinState.Spent == 0 and \ coin.State & CoinState.Locked == 0 and \ coin.State & CoinState.Frozen == 0 and \ coin.State & CoinState.WatchOnly == watch_only: total = total + coin.Output.Value return total
def Account_SetVotes(self, engine): try: account = engine.EvaluationStack.Pop().GetInterface() vote_list = engine.EvaluationStack.Pop().GetArray() except Exception as e: logger.error("could not get account or votes: %s " % e) return False if account is None or len(vote_list) > 1024: return False if account.IsFrozen: return False balance = account.BalanceFor(Blockchain.SystemShare().Hash) if balance == Fixed8.Zero() and len(vote_list) > 0: return False acct = self._accounts.GetAndChange(account.AddressBytes) voteset = [] for v in vote_list: if v not in voteset: voteset.append(v.GetByteArray()) acct.Votes = voteset # print("*****************************************************") # print("SET ACCOUNT VOTES %s " % json.dumps(acct.ToJson(), indent=4)) # print("*****************************************************") return True
def test_fixed8_neg(self): f1 = Fixed8(2) f1 = -f1 self.assertIsInstance(f1, Fixed8) self.assertEqual(f1.value, -2)
def Account_SetVotes(self, engine): try: account = engine.EvaluationStack.Pop().GetInterface( 'neo.Core.State.AccountState.AccountState') vote_list = engine.EvaluationStack.Pop().GetArray() except Exception as e: self.__log.debug("could not get account or votes: %s " % e) return False if account is None or len(vote_list) > 1024: return False if account.IsFrozen: return False balance = account.BalanceFor(Blockchain.SystemShare().Hash) if balance == Fixed8.Zero() and len(vote_list) > 0: return False # disable setting votes for now until further testing to make sure we're not duplicating votes # # acct = self._accounts.GetAndChange(account.AddressBytes) # voteset = set() # for v in vote_list: # voteset.add(v.GetByteArray()) # acct.Votes = list(voteset) # self.__log.debug("SET ACCOUNT VOTES %s " % json.dumps(acct.ToJson(), indent=4)) return True
def test_from_decimal(self): decimal = 2042.02556 f8 = Fixed8.FromDecimal(decimal) self.assertIsInstance(f8, Fixed8) self.assertEqual(f8.value, 204202556000)
def _get_context(self): neo_balance = Fixed8.Zero() for coin in self.wallet.FindUnspentCoinsByAsset(Blockchain.SystemShare().Hash): neo_balance += coin.Output.Value gas_balance = Fixed8.Zero() for coin in self.wallet.FindUnspentCoinsByAsset(Blockchain.SystemCoin().Hash): gas_balance += coin.Output.Value return { 'message':'Hello', 'height':Blockchain.Default().Height, 'neo': neo_balance.ToInt(), 'gas': gas_balance.ToInt(), 'wallet_height': self.wallet.WalletHeight }
def NetworkFee(self): if self.__network_fee == -Fixed8.Satoshi(): # Fixed8 input = References.Values.Where(p= > p.AssetId.Equals(.SystemCoin.Hash)).Sum(p= > p.Value); # Fixed8 output = Outputs.Where(p= > p.AssetId.Equals(Blockchain.SystemCoin.Hash)).Sum(p= > p.Value); # _network_fee = input - output - SystemFee; pass return self.__network_fee
def ReadFixed8(self, unsigned=False): if unsigned: fval = self.ReadUInt64() else: fval = self.ReadInt64() return Fixed8(fval)
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 GetBalance(self, asset_id): total = Fixed8(0) for coin in self.GetCoins(): if coin.State & CoinState.Spent == 0 \ and coin.Output.AssetId == asset_id: total = total + coin.Output.Value return total
def TotalFees(self): amount=0 for tx in self.Transactions: if type(tx.SystemFee()) is int: raise Exception("TX %s is baddddddd %s %s" % (tx, tx.Type)) elif type(tx.SystemFee().value) is Fixed8: raise Exception("TX ISSS BADD:::: %s %s" % (tx, tx.Type)) amount += tx.SystemFee().value return Fixed8(amount)