def SearchAssetState(self, query): res = [] snapshot = self._db.createSnapshot() keys = [] with self._db.openIter( DBProperties(DBPrefix.ST_Asset, include_value=False)) as it: for key in it: keys.append(key[1:]) # remove prefix byte if query.lower() == "neo": query = "AntShare" if query.lower() in {"gas", "neogas"}: query = "AntCoin" for item in keys: asset = snapshot.Assets.TryGet(item) if query in asset.Name.decode('utf-8'): res.append(asset) elif query in Crypto.ToAddress(asset.Issuer): res.append(asset) elif query in Crypto.ToAddress(asset.Admin): res.append(asset) return res
def test_invocation_assetcreate_block(self): hexdata = binascii.unhexlify(self.asset_create_block) block = Helper.AsSerializableWithType(hexdata, 'neo.Core.Block.Block') self.assertEqual(block.Index, self.asset_create_index) snapshot = Blockchain.Default()._db.createSnapshot() snapshot.PersistingBlock = block snapshot.UnspentCoins.Add(b'aa2051096e7be45ed991279a1a4c2678eb886690829a2729f4caa82192ff7f34', UnspentCoinState.FromTXOutputsConfirmed([0])) result = False with BlockchainFixtureTestCase.MPPersist(): result = Blockchain.Default().Persist(block, snapshot) self.assertTrue(result) # now the asset that was created should be there newasset = snapshot.Assets.TryGet(self.asset_create_id) self.assertIsNotNone(newasset) self.assertEqual(newasset.AssetType, 1) self.assertEqual(newasset.Precision, 8) self.assertEqual(Crypto.ToAddress(newasset.Admin), self.asset_admin) self.assertEqual(Crypto.ToAddress(newasset.Issuer), self.asset_admin) self.assertIsInstance(newasset.AssetId, UInt256) self.assertEqual(newasset.AssetId.ToBytes(), self.asset_create_id)
def test_invocation_assetcreate_block(self): hexdata = binascii.unhexlify(self.asset_create_block) block = Helper.AsSerializableWithType(hexdata, 'neo.Core.Block.Block') self.assertEqual(block.Index, self.asset_create_index) result = Blockchain.Default().Persist(block) self.assertTrue(result) # now the asset that was created should be there assets = DBCollection(Blockchain.Default()._db, DBPrefix.ST_Asset, AssetState) newasset = assets.TryGet(self.asset_create_id) self.assertIsNotNone(newasset) self.assertEqual(newasset.AssetType, 1) self.assertEqual(newasset.Precision, 8) self.assertEqual(Crypto.ToAddress(newasset.Admin), self.asset_admin) self.assertEqual(Crypto.ToAddress(newasset.Issuer), self.asset_admin) self.assertIsInstance(newasset.AssetId, UInt256) self.assertEqual(newasset.AssetId.ToBytes(), self.asset_create_id)
def Storage_Delete(self, engine: ExecutionEngine): context = engine.CurrentContext.EvaluationStack.Pop().GetInterface() if not self.CheckStorageContext(context): return False key = engine.CurrentContext.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) keystr = key if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) self.events_to_dispatch.append( SmartContractEvent(SmartContractEvent.STORAGE_DELETE, ContractParameter(ContractParameterType.String, keystr), context.ScriptHash, Blockchain.Default().Height + 1, engine.ScriptContainer.Hash if engine.ScriptContainer else None, test_mode=engine.testMode)) self._storages.Remove(storage_key.ToArray()) return True
def Blockchain_GetAccount(self, engine: ExecutionEngine): hash = UInt160(data=engine.CurrentContext.EvaluationStack.Pop().GetByteArray()) address = Crypto.ToAddress(hash).encode('utf-8') account = self.Accounts.GetOrAdd(address, new_instance=AccountState(script_hash=hash)) engine.CurrentContext.EvaluationStack.PushT(StackItem.FromInterface(account)) return True
async def verify_signature(message): """ Verifies a signature of a message, return True if verified, false if not """ Crypto.SetupSignatureCurve() try: signature = json.loads(message['signature']) except Exception: LOGGER.exception("NEO Signature deserialization error") return False try: script_hash = Crypto.ToScriptHash("21" + signature['publicKey'] + "ac") address = Crypto.ToAddress(script_hash) except Exception: LOGGER.exception("NEO Signature Key error") return False if address != message['sender']: LOGGER.warning('Received bad signature from %s for %s' % (address, message['sender'])) return False try: verification = await buildNEOVerification(message, signature['salt']) result = Crypto.VerifySignature(verification, bytes.fromhex(signature['data']), bytes.fromhex(signature['publicKey']), unhex=True) except Exception: LOGGER.exception("NULS Signature verification error") result = False return result
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ jsn = super(RegisterTransaction, self).ToJson() asset = { 'type': self.AssetType, 'name': self.Name, 'amount': self.Amount.value, 'precision': self.Precision if type(self.Precision) is int else self.Precision.decode('utf-8'), 'owner': self.Owner.ToString(), 'admin': Crypto.ToAddress(self.Admin) } jsn['asset'] = asset return jsn
def Address(self): """ Get the public address of the transaction. Returns: str: base58 encoded string representing the address. """ return Crypto.ToAddress(self.ScriptHash)
def Address(self): """ Get the accounts public address. Returns: str: base58 encoded string representing the account address. """ return Crypto.ToAddress(self.ScriptHash)
def Address(self): """ Get the wallet address associated with the coin. Returns: str: base58 encoded string representing the wallet address. """ if self._address is None: self._address = Crypto.ToAddress(self.Output.ScriptHash) return self._address
def scripthash_to_address(scripthash): try: if scripthash[0:2] != "0x": # litle endian. convert to big endian now. print("Detected little endian scripthash. Converting to big endian for internal use.") scripthash_bytes = binascii.unhexlify(scripthash) scripthash = "0x%s" % binascii.hexlify(scripthash_bytes[::-1]).decode("utf-8") print("Big endian scripthash:", scripthash) return Crypto.ToAddress(UInt160.ParseString(scripthash)) except Exception as e: raise ConversionError("Wrong format")
def GetAddress(self): """ Returns the public NEO address for this KeyPair Returns: str: The private key """ script = b'21' + self.PublicKey.encode_point(True) + b'ac' script_hash = Crypto.ToScriptHash(script) address = Crypto.ToAddress(script_hash) return address
def SearchAssetState(self, query): res = [] assets = DBCollection(self._db, DBPrefix.ST_Asset, AssetState) keys = assets.Keys if query.lower() == "neo": query = "AntShare" if query.lower() in {"gas", "neogas"}: query = "AntCoin" for item in keys: asset = assets.TryGet(keyval=item) if query in asset.Name.decode('utf-8'): res.append(asset) elif query in Crypto.ToAddress(asset.Issuer): res.append(asset) elif query in Crypto.ToAddress(asset.Admin): res.append(asset) return res
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ return { 'assetId': self.AssetId.To0xString(), 'assetType': self.AssetType, 'name': self.GetName(), 'amount': self.Amount.value, 'available': self.Available.value, 'precision': self.Precision, 'fee': self.Fee.value, 'address': self.FeeAddress.ToString(), 'owner': self.Owner.ToString(), 'admin': Crypto.ToAddress(self.Admin), 'issuer': Crypto.ToAddress(self.Issuer), 'expiration': self.Expiration, 'is_frozen': self.IsFrozen }
def Storage_Put(self, engine: ExecutionEngine): context = None try: context = engine.CurrentContext.EvaluationStack.Pop().GetInterface( ) except Exception as e: logger.error("Storage Context Not found on stack") return False if not self.CheckStorageContext(context): return False key = engine.CurrentContext.EvaluationStack.Pop().GetByteArray() if len(key) > 1024: return False value = engine.CurrentContext.EvaluationStack.Pop().GetByteArray() new_item = StorageItem(value=value) storage_key = StorageKey(script_hash=context.ScriptHash, key=key) item = self._storages.ReplaceOrAdd(storage_key.ToArray(), new_item) keystr = key valStr = bytearray(item.Value) if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) try: valStr = int.from_bytes(valStr, 'little') except Exception as e: pass self.events_to_dispatch.append( SmartContractEvent( SmartContractEvent.STORAGE_PUT, ContractParameter(ContractParameterType.String, '%s -> %s' % (keystr, valStr)), context.ScriptHash, Blockchain.Default().Height + 1, engine.ScriptContainer.Hash if engine.ScriptContainer else None, test_mode=engine.testMode)) return True
def Storage_Get(self, engine: ExecutionEngine): context = None try: item = engine.CurrentContext.EvaluationStack.Pop() context = item.GetInterface() except Exception as e: logger.error("could not get storage context %s " % e) return False if not self.CheckStorageContext(context): return False key = engine.CurrentContext.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) item = self.Storages.TryGet(storage_key.ToArray()) keystr = key valStr = bytearray(0) if item is not None: valStr = bytearray(item.Value) if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) try: valStr = int.from_bytes(valStr, 'little') except Exception as e: logger.error("Could not convert %s to number: %s " % (valStr, e)) if item is not None: engine.CurrentContext.EvaluationStack.PushT(bytearray(item.Value)) else: engine.CurrentContext.EvaluationStack.PushT(bytearray(0)) tx_hash = None if engine.ScriptContainer: tx_hash = engine.ScriptContainer.Hash self.events_to_dispatch.append( SmartContractEvent(SmartContractEvent.STORAGE_GET, ContractParameter(ContractParameterType.String, value='%s -> %s' % (keystr, valStr)), context.ScriptHash, Blockchain.Default().Height + 1, tx_hash, test_mode=engine.testMode)) return True
def GetBalance(self, wallet, address, as_string=False): """ Get the token balance. Args: wallet (neo.Wallets.Wallet): a wallet instance. address (str): public address of the account to get the token balance of. as_string (bool): whether the return value should be a string. Default is False, returning an integer. Returns: int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed. """ addr = PromptUtils.parse_param(address, wallet) if isinstance(addr, UInt160): addr = addr.Data sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr]) tx, fee, results, num_ops, engine_success = test_invoke( sb.ToArray(), wallet, []) if engine_success: try: val = results[0].GetBigInteger() precision_divisor = pow(10, self.decimals) balance = Decimal(val) / Decimal(precision_divisor) if as_string: formatter_str = '.%sf' % self.decimals balance_str = format(balance, formatter_str) return balance_str return balance except Exception as e: logger.error("could not get balance: %s " % e) traceback.print_stack() else: addr_str = Crypto.ToAddress(UInt160(data=addr)) logger.error( f"Could not get balance of address {addr_str} for token contract {self.ScriptHash}. VM execution failed. Make sure the contract exists on the network and that it adheres to the NEP-5 standard" ) return 0
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ json = {} json["hash"] = self.Hash.To0xString() json["size"] = self.Size() json["version"] = self.Version json["previousblockhash"] = self.PrevHash.To0xString() json["merkleroot"] = self.MerkleRoot.To0xString() json["time"] = self.Timestamp json["index"] = self.Index nonce = bytearray(self.ConsensusData.to_bytes(8, 'little')) nonce.reverse() json["nonce"] = nonce.hex() json['nextconsensus'] = Crypto.ToAddress(self.NextConsensus) # json["consensus data"] = self.ConsensusData json["script"] = '' if not self.Script else self.Script.ToJson() return json
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ json = super(AccountState, self).ToJson() addr = Crypto.ToAddress(self.ScriptHash) json['address'] = addr json['script_hash'] = str(self.ScriptHash) json['frozen'] = self.IsFrozen json['votes'] = [v.hex() for v in self.Votes] balances = [] for key, value in self.Balances.items(): balances.append({ 'asset': key.To0xString(), 'value': value.ToString() }) json['balances'] = balances return json
def test_block_two(self): hexdata = binascii.unhexlify(self.b2raw) block = Helper.AsSerializableWithType(hexdata, 'neo.Core.Block.Block') self.assertEqual(block.Index, self.b2height) self.assertEqual(block.ConsensusData, self.b2nonce) self.assertEqual(block.Timestamp, self.b2timestamp) self.assertEqual(block.PrevHash.ToBytes(), self.b2prev_hash) self.assertEqual(block.Hash.ToString(), self.b2hash) next_consensus_address = Crypto.ToAddress(block.NextConsensus) self.assertEqual(next_consensus_address, self.b2nextconsensus) witness = block.Script ins = binascii.hexlify(witness.InvocationScript) vns = binascii.hexlify(witness.VerificationScript) self.assertEqual(ins, self.b2invocation) self.assertEqual(vns, self.b2verification) self.assertEqual(len(block.Transactions), self.b2tx_len) tx = block.Transactions[0] self.assertEqual(tx.inputs, self.b2tx_vin) self.assertEqual(tx.outputs, self.b2tx_vout) self.assertEqual(tx.Nonce, self.b2tx_nonce) txhash = tx.Hash.ToBytes() self.assertEqual(txhash, self.b2tx_id) root = MerkleTree.ComputeRoot([tx.Hash for tx in block.Transactions]) self.assertEqual(root, block.MerkleRoot)
def ToString(self): return Crypto.ToAddress(UInt160(data=self.ScriptHash))
def ToJson(self, verbose=False): assets = self.GetCoinAssets() tokens = list(self._tokens.values()) assets = assets + tokens if Blockchain.Default().Height == 0: percent_synced = 0 else: percent_synced = int(100 * self._current_height / Blockchain.Default().Height) jsn = {} jsn['path'] = self._path addresses = [] has_watch_addr = False for addr in Address.select(): addr_str = Crypto.ToAddress(UInt160(data=addr.ScriptHash)) acct = Blockchain.Default().GetAccountState(addr_str) token_balances = self.TokenBalancesForAddress(addr_str) if acct: json = acct.ToJson() json['is_watch_only'] = addr.IsWatchOnly addresses.append(json) if token_balances: json['tokens'] = token_balances if addr.IsWatchOnly: has_watch_addr = True else: script_hash = binascii.hexlify(addr.ScriptHash) json = { 'address': addr_str, 'script_hash': script_hash.decode('utf8'), 'tokens': token_balances } addresses.append(json) balances = [] watch_balances = [] for asset in assets: if type(asset) is UInt256: bc_asset = Blockchain.Default().GetAssetState(asset.ToBytes()) total = self.GetBalance(asset).value / Fixed8.D watch_total = self.GetBalance( asset, CoinState.WatchOnly).value / Fixed8.D balances.append("[%s]: %s " % (bc_asset.GetName(), total)) watch_balances.append("[%s]: %s " % (bc_asset.GetName(), watch_total)) elif type(asset) is WalletNEP5Token: balances.append("[%s]: %s " % (asset.symbol, self.GetBalance(asset))) watch_balances.append( "[%s]: %s " % (asset.symbol, self.GetBalance(asset, True))) tokens = [] for t in self._tokens.values(): tokens.append(t.ToJson()) jsn['addresses'] = addresses jsn['height'] = self._current_height jsn['percent_synced'] = percent_synced jsn['synced_balances'] = balances if has_watch_addr: jsn['synced_watch_only_balances'] = watch_balances jsn['public_keys'] = self.PubKeys() jsn['tokens'] = tokens jsn['claims'] = { 'available': self.GetAvailableClaimTotal().ToString(), 'unavailable': self.GetUnavailableBonus().ToString() } alia = NamedAddress.select() if len(alia): na = {} for n in alia: na[n.Title] = n.ToString() jsn['named_addr'] = na if verbose: jsn['coins'] = [coin.ToJson() for coin in self.FindUnspentCoins()] jsn['transactions'] = [ tx.ToJson() for tx in self.GetTransactions() ] return jsn
def AddressTo(self): if self.addr_to: return Crypto.ToAddress(self.addr_to) return None
def AddressFrom(self): if self.addr_from: return Crypto.ToAddress(self.addr_from) return None
def InputAddr(self): return Crypto.ToAddress(self.InputHash)
def Address(self): if self._address is None: self._address = Crypto.ToAddress(self.ScriptHash) return self._address
def OutputAddr(self): return Crypto.ToAddress(self.OutputHash)