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 SearchAssetState(self, query): res = [] assets = DBCollection(self._db, DBPrefix.ST_Asset, AssetState) keys = assets.Keys 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 Storage_Delete(self, engine): context = engine.EvaluationStack.Pop().GetInterface() if not self.CheckStorageContext(context): return False key = engine.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) self.events_to_dispatch.append( SmartContractEvent(SmartContractEvent.STORAGE_DELETE, [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): hash = UInt160(data=engine.EvaluationStack.Pop().GetByteArray()) address = Crypto.ToAddress(hash).encode('utf-8') account = self.Accounts.GetOrAdd(address, new_instance=AccountState(script_hash=hash)) engine.EvaluationStack.PushT(StackItem.FromInterface(account)) return True
def hex2address(input): try: output = Crypto.ToAddress( UInt160(data=binascii.unhexlify(bytearray(input.encode("utf8"))))) except: output = None return output
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.decode('utf-8'), '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 openWallet(self): """ open a Wallet. Needed for invoking contract methods """ if not os.path.exists(self.walletpath): logger.info("Wallet file not found") return else: assert self.Wallet is None aespasswd = to_aes_key(self.walletpw) self.Wallet = UserWallet.Open(self.walletpath, aespasswd) print("Opened wallet at: ", self.walletpath) self.wallet_sh = self.Wallet.GetStandardAddress() self.wallet_addr = Crypto.ToAddress(self.wallet_sh) print('Wallet Sh', self.wallet_sh) print('Wallet Addr', self.wallet_addr) self.Wallet.Rebuild() print("Wallet is syncing...") while self.Wallet.IsSynced is False: self._walletdb_loop = task.LoopingCall( self.Wallet.ProcessBlocks) self._walletdb_loop.start(1) print(self.Wallet._current_height, "/", Blockchain.Default().Height) return len(self.Wallet.GetTransactions())
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 token. Returns: str: base58 encoded string representing the wallet address. """ if self._address is None: self._address = Crypto.ToAddress(self.ScriptHash) return self._address
def Storage_Get(self, engine): context = None try: item = engine.EvaluationStack.Pop() context = item.GetInterface() shash = context.ScriptHash except Exception as e: logger.error("could not get storage context %s " % e) return False contract = Blockchain.Default().GetContract( context.ScriptHash.ToBytes()) if contract is not None: if not contract.HasStorage: return False else: return False key = engine.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) item = Blockchain.Default().GetStorageItem(storage_key) 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.EvaluationStack.PushT(bytearray(item.Value)) else: engine.EvaluationStack.PushT(bytearray(0)) self.events_to_dispatch.append( SmartContractEvent(SmartContractEvent.STORAGE_GET, ['%s -> %s' % (keystr, valStr)], context.ScriptHash, Blockchain.Default().Height + 1, engine.ScriptContainer.Hash, test_mode=engine.testMode)) return True
def sbytes2addr(value): sbytes = value['value'] s = '' for i in range(0, len(sbytes), 2): s = sbytes[i:i + 2] + s s = '0x' + s try: h = UInt160.ParseString(s) return Crypto.ToAddress(h) except: return ""
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 Storage_Get(self, engine): context = None try: item = engine.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.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.EvaluationStack.PushT(bytearray(item.Value)) else: engine.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 Blockchain_GetAccount(self, engine): hash = UInt160(data=engine.EvaluationStack.Pop().GetByteArray()) address = Crypto.ToAddress(hash).encode('utf-8') account = Blockchain.Default().GetAccountState(address) if account: engine.EvaluationStack.PushT(StackItem.FromInterface(account)) else: engine.EvaluationStack.PushT(False) return True
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.ToString(), '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 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 initialized(self, message): if self.contract.state not in ('WAITING_FOR_DEPLOYMENT', 'ENDED'): return take_off_blocking(self.contract.network.name) self.contract.state = 'ACTIVE' if self.future_minting else 'ENDED' self.contract.save() if self.contract.user.email: send_mail( common_subject, neo_token_text.format(addr=Crypto.ToAddress( UInt160.ParseString(self.neo_contract.address)), ), DEFAULT_FROM_EMAIL, [self.contract.user.email])
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 sc_notify(event): if len(event.event_payload): #print("***** got new notify payload {}".format(event.event_payload[0])) if event.event_payload[0].decode("utf-8") == 'new_king': address = event.event_payload[1] bounty = int(event.event_payload[2]) newKingMessage = '' if len(event.event_payload[3]) > 0: name = event.event_payload[3].decode("utf-8", "ignore") newKingMessage = '{} is now king. Next bounty is {} TUT'.format( name, bounty / 100000000) else: newKingMessage = '{} is now king. Next bounty is {} TUT'.format( Crypto.ToAddress(UInt160(data=address)), bounty / 100000000) print(newKingMessage) send_message_sync(newKingMessage)
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['script_hash'] = addr json['frozen'] = self.IsFrozen json['votes'] = [v.hex() for v in self.Votes] balances = {} for key, value in self.Balances.items(): balances[key.To0xString()] = value.ToString() json['balances'] = balances return json
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 initialized(self, message): if self.contract.state not in ('WAITING_FOR_DEPLOYMENT', 'ENDED'): return take_off_blocking(self.contract.network.name) self.contract.state = 'ACTIVE' if self.future_minting else 'ENDED' self.contract.deployed_at = datetime.datetime.now() self.contract.save() if self.contract.user.email: send_mail( common_subject, neo_token_text.format(addr=Crypto.ToAddress( UInt160.ParseString(self.neo_contract.address)), ), DEFAULT_FROM_EMAIL, [self.contract.user.email]) if not 'MAINNET' in self.contract.network.name: send_testnet_gift_emails.delay(self.contract.user.profile.id) else: send_promo_mainnet.delay(self.contract.user.email) msg = self.bot_message transaction.on_commit(lambda: send_message_to_subs.delay(msg, True))
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 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 InputAddr(self): return Crypto.ToAddress(self.InputHash)
def OutputAddr(self): return Crypto.ToAddress(self.OutputHash)
def AddressFrom(self): if self.addr_from: return Crypto.ToAddress(self.addr_from) return None