docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def DeserializeExclusiveData(self, reader): self.Type = TransactionType.IssueTransaction if self.Version > 1: raise Exception('Invalid TX Type')
317,426
Parameter descriptor Args: name: 1 word parameter identifier. description: short description of the purpose of the parameter. What does it configure/do. optional: flag indicating whether the parameter is optional. Defaults to mandatory (false).
def __init__(self, name, description, optional=False): self.name = name self.description = description self.optional = optional
317,429
Command descriptor Args: command: 1 word command identifier short_help: short description of the purpose of the command params: list of parameter descriptions belonging to the command
def __init__(self, command, short_help, params: List[ParameterDesc] = None): self.command = command self.short_help = short_help self.params = params if params else []
317,430
Register a command as a subcommand. It will have it's CommandDesc.command string used as id. Additional ids can be provided. Args: sub_command (CommandBase): Subcommand to register. additional_ids (List[str]): List of additional ids. Can be empty.
def register_sub_command(self, sub_command, additional_ids=[]): self.__register_sub_command(sub_command, sub_command.command_desc().command) self.__additional_ids.update(additional_ids) for id in additional_ids: self.__register_sub_command(sub_command, id)
317,433
Dynamically load a class from a module at the specified path Args: path_and_class: relative path where to find the module and its class name i.e. 'neo.<package>.<package>.<module>.<class name>' Raises: ValueError: if the Module or Class is not found. Returns: class object
def load_class_from_path(path_and_class: str): try: module_path = '.'.join(path_and_class.split('.')[:-1]) module = importlib.import_module(module_path) except ImportError as err: raise ValueError(f"Failed to import module {module_path} with error: {err}") try: class_na...
317,449
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
def Run(script, container=None, exit_on_error=False, gas=Fixed8.Zero(), test_mode=True): from neo.Core.Blockchain import Blockchain from neo.SmartContract.StateMachine import StateMachine from neo.EventHub import events bc = Blockchain.Default() accounts = DBCollectio...
317,466
Create an instance. Args: inputs (list): outputs (list): assettype (neo.Core.AssetType): assetname (str): amount (Fixed8): precision (int): number of decimals the asset has. owner (EllipticCurve.ECPoint): admin (UIn...
def __init__(self, inputs=None, outputs=None, assettype=AssetType.GoverningToken, assetname='', amount=Fixed8(0), precision=0, owner=None, admin=None): super(RegisterTransaction, self)...
317,486
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def DeserializeExclusiveData(self, reader): self.Type = TransactionType.RegisterTransaction self.AssetType = reader.ReadByte() self.Name = reader.ReadVarString() self.Amount = reader.ReadFixed8() self.Precision = reader.ReadByte() self.Owner = ECDSA.Deserialize_S...
317,488
Serialize object. Args: writer (neo.IO.BinaryWriter):
def SerializeExclusiveData(self, writer): writer.WriteByte(self.AssetType) writer.WriteVarString(self.Name) writer.WriteFixed8(self.Amount) writer.WriteByte(self.Precision) self.Owner.Serialize(writer) writer.WriteUInt160(self.Admin)
317,489
Create an instance. Args: *args: **kwargs:
def __init__(self, *args, **kwargs): super(ClaimTransaction, self).__init__(*args, **kwargs) self.Type = TransactionType.ClaimTransaction
317,496
Deserialize full object. Args: reader (neo.IO.BinaryReader): Raises: Exception: If the transaction type is incorrect or if there are no claims.
def DeserializeExclusiveData(self, reader): self.Type = TransactionType.ClaimTransaction if self.Version != 0: raise Exception('Format Exception') numrefs = reader.ReadVarInt() claims = [] for i in range(0, numrefs): c = CoinReference() ...
317,497
Verify the transaction. Args: mempool: Returns: bool: True if verified. False otherwise.
def Verify(self, mempool): if not super(ClaimTransaction, self).Verify(mempool): return False # wat does this do # get all claim transactions from mempool list # that are not this claim # and gather all the claims of those claim transactions # and se...
317,500
Wait for tx to show up on blockchain Args: tx (Transaction or UInt256 or str): Transaction or just the hash max_seconds (float): maximum seconds to wait for tx to show up. default: 120 Returns: True: if transaction was found Raises: AttributeError: if supplied tx is not Tr...
def wait_for_tx(self, tx, max_seconds=120): tx_hash = None if isinstance(tx, (str, UInt256)): tx_hash = str(tx) elif isinstance(tx, Transaction): tx_hash = tx.Hash.ToString() else: raise AttributeError("Supplied tx is type '%s', but must be Transaction or UInt256 or str" % t...
317,502
Add a contract to the wallet. Args: contract (Contract): a contract of type neo.SmartContract.Contract. Raises: Exception: Invalid operation - public key mismatch.
def AddContract(self, contract): if not contract.PublicKeyHash.ToBytes() in self._keys.keys(): raise Exception('Invalid operation - public key mismatch') self._contracts[contract.ScriptHash.ToBytes()] = contract if contract.ScriptHash in self._watch_only: self._...
317,504
Add a watch only address to the wallet. Args: script_hash (UInt160): a bytearray (len 20) representing the public key. Note: Prints a warning to the console if the address already exists in the wallet.
def AddWatchOnly(self, script_hash): if script_hash in self._contracts: logger.error("Address already in contracts") return self._watch_only.append(script_hash)
317,505
Add a NEP-5 compliant token to the wallet. Args: token (NEP5Token): an instance of type neo.Wallets.NEP5Token. Note: Prints a warning to the console if the token already exists in the wallet.
def AddNEP5Token(self, token): if token.ScriptHash.ToBytes() in self._tokens.keys(): logger.error("Token already in wallet") return self._tokens[token.ScriptHash.ToBytes()] = token
317,506
Change the password used to protect the private key. Args: password_old (str): the current password used to encrypt the private key. password_new (str): the new to be used password to encrypt the private key. Returns: bool: whether the password has been changed
def ChangePassword(self, password_old, password_new): if not self.ValidatePassword(password_old): return False if isinstance(password_new, str): password_new = password_new.encode('utf-8') password_key = hashlib.sha256(password_new) self.SaveStoredData(...
317,507
Test if the wallet contains the supplied public key. Args: public_key (edcsa.Curve.point): a public key to test for its existance. e.g. KeyPair.PublicKey Returns: bool: True if exists, False otherwise.
def ContainsKey(self, public_key): return self.ContainsKeyHash(Crypto.ToScriptHash(public_key.encode_point(True), unhex=True))
317,508
Determine if the wallet contains the address. Args: address (str): a string representing the public key. Returns: bool: True, if the address is present in the wallet. False otherwise.
def ContainsAddressStr(self, address): for key, contract in self._contracts.items(): if contract.Address == address: return True return False
317,509
Create a KeyPair Args: private_key (iterable_of_ints): (optional) 32 byte private key Returns: KeyPair: a KeyPair instance
def CreateKey(self, private_key=None): if private_key is None: private_key = bytes(Random.get_random_bytes(32)) key = KeyPair(priv_key=private_key) self._keys[key.PublicKeyHash.ToBytes()] = key return key
317,510
Encrypt the provided plaintext with the initialized private key. Args: decrypted (byte string): the plaintext to be encrypted. Returns: bytes: the ciphertext.
def EncryptPrivateKey(self, decrypted): aes = AES.new(self._master_key, AES.MODE_CBC, self._iv) return aes.encrypt(decrypted)
317,511
Decrypt the provided ciphertext with the initialized private key. Args: encrypted_private_key (byte string): the ciphertext to be decrypted. Returns: bytes: the ciphertext.
def DecryptPrivateKey(self, encrypted_private_key): aes = AES.new(self._master_key, AES.MODE_CBC, self._iv) return aes.decrypt(encrypted_private_key)
317,512
Deletes an address from the wallet (includes watch-only addresses). Args: script_hash (UInt160): a bytearray (len 20) representing the public key. Returns: tuple: bool: True if address removed, False otherwise. list: a list of any ``neo.Wallet.Co...
def DeleteAddress(self, script_hash): coin_keys_toremove = [] coins_to_remove = [] for key, coinref in self._coins.items(): if coinref.Output.ScriptHash.ToBytes() == script_hash.ToBytes(): coin_keys_toremove.append(key) coins_to_remove.append(...
317,513
Looks through the current collection of coins in a wallet and chooses coins that match the specified CoinReference objects. Args: vins: A list of ``neo.Core.CoinReference`` objects. Returns: list: A list of ``neo.Wallet.Coin`` objects.
def FindCoinsByVins(self, vins): ret = [] for coin in self.GetCoins(): coinref = coin.Reference for vin in vins: if coinref.PrevIndex == vin.PrevIndex and \ coinref.PrevHash == vin.PrevHash: ret.append(coin) ...
317,514
Finds unspent coin objects in the wallet. Args: from_addr (UInt160): a bytearray (len 20) representing an address. use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ). watch_only_val (int): a flag ( 0 or 64 ) indicating wh...
def FindUnspentCoins(self, from_addr=None, use_standard=False, watch_only_val=0): ret = [] for coin in self.GetCoins(): if coin.State & CoinState.Confirmed > 0 and \ coin.State & CoinState.Spent == 0 and \ coin.State & CoinState.Locked == 0 an...
317,515
Get the KeyPair belonging to the public key hash. Args: public_key_hash (UInt160): a public key hash to get the KeyPair for. Returns: KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None
def GetKey(self, public_key_hash): if public_key_hash.ToBytes() in self._keys.keys(): return self._keys[public_key_hash.ToBytes()] return None
317,521
Get the KeyPair belonging to the script hash. Args: script_hash (UInt160): a bytearray (len 20) representing the public key. Returns: KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None
def GetKeyByScriptHash(self, script_hash): contract = self.GetContract(script_hash) if contract: return self.GetKey(contract.PublicKeyHash) return None
317,522
Get the balance of the specified token. Args: token (NEP5Token): an instance of type neo.Wallets.NEP5Token to get the balance from. watch_only (bool): True, to limit to watch only wallets. Returns: Decimal: total balance for `token`.
def GetTokenBalance(self, token, watch_only=0): total = Decimal(0) if watch_only > 0: for addr in self._watch_only: balance = token.GetBalance(self, addr) total += balance else: for contract in self._contracts.values(): ...
317,523
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: ...
def GetBalance(self, asset_id, watch_only=0): total = Fixed8(0) if type(asset_id) is NEP5Token.NEP5Token: return self.GetTokenBalance(asset_id, watch_only) for coin in self.GetCoins(): if coin.Output.AssetId == asset_id: if coin.State & CoinStat...
317,524
Processes a block on the blockchain. This should be done in a sequential order, ie block 4 should be only processed after block 3. Args: block: (neo.Core.Block) a block on the blockchain.
def ProcessNewBlock(self, block): added = set() changed = set() deleted = set() try: # go through the list of transactions in the block and enumerate # over their outputs for tx in block.FullTransactions: for index, output in...
317,526
Verifies if a transaction belongs to the wallet. Args: tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify. Returns: bool: True, if transaction belongs to wallet. False, if not.
def IsWalletTransaction(self, tx): for key, contract in self._contracts.items(): for output in tx.outputs: if output.ScriptHash.ToBytes() == contract.ScriptHash.ToBytes(): return True for script in tx.scripts: if script.Veri...
317,527
Determine the address state of the provided script hash. Args: script_hash (UInt160): a script hash to determine the address state of. Returns: AddressState: the address state.
def CheckAddressState(self, script_hash): for key, contract in self._contracts.items(): if contract.ScriptHash.ToBytes() == script_hash.ToBytes(): return AddressState.InWallet for watch in self._watch_only: if watch == script_hash: return ...
317,528
Retrieve the script_hash based from an address. Args: address (str): a base58 encoded address. Raises: ValuesError: if an invalid address is supplied or the coin version is incorrect Exception: if the address string does not start with 'A' or the checksum fails ...
def ToScriptHash(self, address): if len(address) == 34: if address[0] == 'A': data = b58decode(address) if data[0] != self.AddressVersion: raise ValueError('Not correct Coin Version') checksum = Crypto.Default().Hash256(da...
317,529
Validates if the provided password matches with the stored password. Args: password (string): a password. Returns: bool: the provided password matches with the stored password.
def ValidatePassword(self, password): password = to_aes_key(password) return hashlib.sha256(password).digest() == self.LoadStoredData('PasswordHash')
317,530
Get the address where change is send to. Args: from_address (UInt160): (optional) from address script hash. Raises: Exception: if change address could not be found. Returns: UInt160: script hash.
def GetChangeAddress(self, from_addr=None): if from_addr is not None: for contract in self._contracts.values(): if contract.ScriptHash == from_addr: return contract.ScriptHash for contract in self._contracts.values(): if contract.IsSt...
317,532
Get contract for specified script_hash. Args: script_hash (UInt160): a bytearray (len 20). Returns: Contract: if a contract was found matching the provided script hash, otherwise None
def GetContract(self, script_hash): if script_hash.ToBytes() in self._contracts.keys(): return self._contracts[script_hash.ToBytes()] return None
317,535
Sign the verifiable items ( Transaction, Block, etc ) in the context with the Keypairs in this wallet. Args: context (ContractParameterContext): the context to sign. Returns: bool: if signing is successful for all contracts in this wallet.
def Sign(self, context): success = False for hash in context.ScriptHashes: contract = self.GetContract(hash) if contract is None: logger.info( f"Cannot find key belonging to script_hash {hash}. Make sure the source address you're try...
317,538
Sign a message with a specified script_hash. Args: message (str): a hex encoded message to sign script_hash (UInt160): a bytearray (len 20). Returns: str: the signed message
def SignMessage(self, message, script_hash): keypair = self.GetKeyByScriptHash(script_hash) prikey = bytes(keypair.PrivateKey) res = Crypto.Default().Sign(message, prikey) return res, keypair.PublicKey
317,539
Get a MemoryStream instance. Args: data (bytes, bytearray, BytesIO): (Optional) data to create the stream from. Returns: MemoryStream: instance.
def GetStream(data=None): if len(__mstreams_available__) == 0: if data: mstream = MemoryStream(data) mstream.seek(0) else: mstream = MemoryStream() __mstreams__.append(mstream) return mstream mstrea...
317,542
Create an instance. Args: *args: **kwargs:
def __init__(self, *args, **kwargs): super(MemoryStream, self).__init__(*args, **kwargs)
317,543
Create a new user wallet. Args: path (str): A path indicating where to create or open the wallet e.g. "/Wallets/mywallet". password (str): a 10 characters minimum password to secure the wallet with. Returns: UserWallet: a UserWallet instance.
def Create(path, password, generate_default_key=True): wallet = UserWallet(path=path, passwordKey=password, create=True) if generate_default_key: wallet.CreateKey() return wallet
317,548
Create a KeyPair and store it encrypted in the database. Args: private_key (iterable_of_ints): (optional) 32 byte private key. Returns: KeyPair: a KeyPair instance.
def CreateKey(self, prikey=None): account = super(UserWallet, self).CreateKey(private_key=prikey) self.OnCreateAccount(account) contract = WalletContract.CreateSignatureContract(account.PublicKey) self.AddContract(contract) return account
317,549
Save a KeyPair in encrypted form into the database. Args: account (KeyPair):
def OnCreateAccount(self, account): pubkey = account.PublicKey.encode_point(False) pubkeyunhex = binascii.unhexlify(pubkey) pub = pubkeyunhex[1:65] priv = bytearray(account.PrivateKey) decrypted = pub + priv encrypted_pk = self.EncryptPrivateKey(bytes(decrypted)...
317,550
Add a contract to the database. Args: contract(neo.SmartContract.Contract): a Contract instance.
def AddContract(self, contract): super(UserWallet, self).AddContract(contract) try: db_contract = Contract.get(ScriptHash=contract.ScriptHash.ToBytes()) db_contract.delete_instance() except Exception as e: logger.debug("contract does not exist yet") ...
317,551
Create an instance. The NeoNode class is the equivalent of the C# RemoteNode.cs class. It represents a single Node connected to the client. Args: incoming_client (bool): True if node is an incoming client and the handshake should be initiated.
def __init__(self, incoming_client=False): from neo.Network.NodeLeader import NodeLeader self.leader = NodeLeader.Instance() self.nodeid = self.leader.NodeId self.remote_nodeid = random.randint(1294967200, 4294967200) self.endpoint = '' self.address = None ...
317,595
Process a message. Args: m (neo.Network.Message):
def MessageReceived(self, m): if m.Command == 'verack': # only respond with a verack when we connect to another client, not when a client connected to us or # we might end up in a verack loop if self.incoming_client: if self.expect_verack_next: ...
317,606
Process a block header inventory payload. Args: inventory (neo.Network.Payloads.InvPayload):
def HandleInvMessage(self, payload): if self.sync_mode != MODE_MAINTAIN: return inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.InvPayload.InvPayload') if not inventory: return if inventory.Type == InventoryType.BlockInt: ...
317,619
Send the `message` to the remote client. Args: message (neo.Network.Message):
def SendSerializedMessage(self, message): try: ba = Helper.ToArray(message) ba2 = binascii.unhexlify(ba) self.bytes_out += len(ba2) self.transport.write(ba2) except Exception as e: logger.debug(f"Could not send serialized message {e}")
317,620
Process a block header inventory payload. Args: inventory (neo.Network.Inventory):
def HandleBlockHeadersReceived(self, inventory): try: inventory = IOHelper.AsSerializableWithType(inventory, 'neo.Network.Payloads.HeadersPayload.HeadersPayload') if inventory is not None: logger.debug(f"{self.prefix} received headers") self.heart...
317,621
Process a Block inventory payload. Args: inventory (neo.Network.Inventory):
def HandleBlockReceived(self, inventory): block = IOHelper.AsSerializableWithType(inventory, 'neo.Core.Block.Block') if not block: return blockhash = block.Hash.ToBytes() try: if blockhash in BC.Default().BlockRequests: BC.Default().Block...
317,622
Process a InvPayload payload. Args: payload (neo.Network.Inventory):
def HandleGetDataMessageReceived(self, payload): inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.InvPayload.InvPayload') if not inventory: return for hash in inventory.Hashes: hash = hash.encode('utf-8') item = None ...
317,627
Process a GetBlocksPayload payload. Args: payload (neo.Network.Payloads.GetBlocksPayload):
def HandleGetBlocksMessageReceived(self, payload): if not self.leader.ServiceEnabled: return inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.GetBlocksPayload.GetBlocksPayload') if not inventory: return blockchain = BC.Default(...
317,628
Wrap the inventory in a InvPayload object and send it over the write to the remote node. Args: inventory: Returns: bool: True (fixed)
def Relay(self, inventory): inventory = InvPayload(type=inventory.InventoryType, hashes=[inventory.Hash.ToBytes()]) m = Message("inv", inventory) self.SendSerializedMessage(m) return True
317,629
Create an instance. Args: command (str): payload command e.g. "inv", "getdata". See NeoNode.MessageReceived() for more commands. payload (bytes): raw bytes of the payload. print_payload: UNUSED
def __init__(self, command=None, payload=None, print_payload=False): self.Command = command self.Magic = settings.MAGIC if payload is None: payload = bytearray() else: payload = binascii.unhexlify(Helper.ToArray(payload)) self.Checksum = Message...
317,630
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def Deserialize(self, reader): self.Magic = reader.ReadUInt32() self.Command = reader.ReadFixedString(12).decode('utf-8') self.Length = reader.ReadUInt32() if self.Length > self.PayloadMaxSizeInt: raise Exception("invalid format- payload too large") self.Ch...
317,632
Serialize object. Args: writer (neo.IO.BinaryWriter):
def Serialize(self, writer): writer.WriteUInt32(self.Magic) writer.WriteFixedString(self.Command, 12) writer.WriteUInt32(len(self.Payload)) writer.WriteUInt32(self.Checksum) writer.WriteBytes(self.Payload)
317,633
Filter out duplicate `Script` TransactionAttributeUsage types. Args: attributes: a list of TransactionAttribute's Returns: list:
def make_unique_script_attr(attributes): filtered_attr = [] script_list = [] for attr in attributes: if attr.Usage != TransactionAttributeUsage.Script: filtered_attr.append(attr) else: data = attr.Data if isinstance(data, UInt160): # c...
317,667
Deserialize the stream into a Transaction object. Args: buffer (BytesIO): stream to deserialize the Transaction from. Returns: neo.Core.TX.Transaction:
def DeserializeTX(buffer): mstream = MemoryStream(buffer) reader = BinaryReader(mstream) tx = Transaction.DeserializeFrom(reader) return tx
317,673
Create an instance. Args: usage (neo.Core.TX.TransactionAttribute.TransactionAttributeUsage): data (bytes):
def __init__(self, usage=None, data=None): super(TransactionAttribute, self).__init__() self.Usage = usage self.Data = data
317,674
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def Deserialize(self, reader): usage = reader.ReadByte() self.Usage = usage if usage == TransactionAttributeUsage.ContractHash or usage == TransactionAttributeUsage.Vote or \ (usage >= TransactionAttributeUsage.Hash1 and usage <= TransactionAttributeUsage.Hash15): ...
317,675
Serialize object. Args: writer (neo.IO.BinaryWriter): Raises: Exception: if the length exceeds the maximum allowed number of attributes in a transaction.
def Serialize(self, writer): writer.WriteByte(self.Usage) if isinstance(self.Data, UIntBase): self.Data = self.Data.Data length = len(self.Data) if length > self.MAX_ATTR_DATA_SIZE: raise Exception("Invalid transaction attribute") if self.Usag...
317,676
Get unspent outputs from a list of transaction outputs. Args: outputs (list): of neo.Core.TX.Transaction.TransactionOutput items. Returns: UnspentCoinState:
def FromTXOutputsConfirmed(outputs): uns = UnspentCoinState() uns.Items = [0] * len(outputs) for i in range(0, len(outputs)): uns.Items[i] = int(CoinState.Confirmed) return uns
317,681
Deserialize full object. Args: reader (neocore.IO.BinaryReader):
def Deserialize(self, reader): super(UnspentCoinState, self).Deserialize(reader) blen = reader.ReadVarInt() self.Items = [0] * blen for i in range(0, blen): self.Items[i] = int.from_bytes(reader.ReadByte(do_ord=False), 'little')
317,685
Deserialize full object. Args: buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from. Returns: UnspentCoinState:
def DeserializeFromDB(buffer): m = StreamManager.GetStream(buffer) reader = BinaryReader(m) uns = UnspentCoinState() uns.Deserialize(reader) StreamManager.ReleaseStream(m) return uns
317,686
Serialize full object. Args: writer (neo.IO.BinaryWriter):
def Serialize(self, writer): super(UnspentCoinState, self).Serialize(writer) writer.WriteVarInt(len(self.Items)) for item in self.Items: byt = item.to_bytes(1, 'little') writer.WriteByte(byt)
317,687
Deserialize full object. Args: reader (neocore.IO.BinaryReader): Raises: Exception: if the state version is incorrect.
def Deserialize(self, reader): sv = reader.ReadByte() if sv != self.StateVersion: raise Exception("Incorrect State format")
317,689
Create an instance. Args: asset_id (UInt256): amount (Fixed8):
def __init__(self, asset_id, amount): self.AssetId = asset_id self.Amount = amount
317,721
Create an instance. Args: AssetId (UInt256): Value (Fixed8): script_hash (UInt160):
def __init__(self, AssetId=None, Value=None, script_hash=None): super(TransactionOutput, self).__init__() self.AssetId = AssetId self.Value = Value self.ScriptHash = script_hash
317,723
Serialize object. Args: writer (neo.IO.BinaryWriter):
def Serialize(self, writer): writer.WriteUInt256(self.AssetId) writer.WriteFixed8(self.Value) writer.WriteUInt160(self.ScriptHash)
317,724
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def Deserialize(self, reader): self.AssetId = reader.ReadUInt256() self.Value = reader.ReadFixed8() self.ScriptHash = reader.ReadUInt160() if self.ScriptHash is None: raise Exception("Script hash is required from deserialize!!!!!!!!")
317,725
Convert object members to a dictionary that can be parsed as JSON. Args: index (int): The index of the output in a transaction Returns: dict:
def ToJson(self, index): return { 'n': index, 'asset': self.AssetId.To0xString(), 'value': self.Value.ToNeoJsonString(), 'address': self.Address }
317,726
Create an instance. Args: prevHash (UInt256): prevIndex (int):
def __init__(self, prevHash=None, prevIndex=None): super(TransactionInput, self).__init__() self.PrevHash = prevHash self.PrevIndex = prevIndex
317,727
Serialize object. Args: writer (neo.IO.BinaryWriter):
def Serialize(self, writer): writer.WriteUInt256(self.PrevHash) writer.WriteUInt16(self.PrevIndex)
317,728
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def Deserialize(self, reader): self.PrevHash = reader.ReadUInt256() self.PrevIndex = reader.ReadUInt16()
317,729
Create an instance. Args: inputs (list): of neo.Core.CoinReference.CoinReference. outputs (list): of neo.Core.TX.Transaction.TransactionOutput items. attributes (list): of neo.Core.TX.TransactionAttribute. scripts:
def __init__(self, inputs=[], outputs=[], attributes=[], scripts=[]): super(Transaction, self).__init__() self.inputs = inputs self.outputs = outputs self.Attributes = attributes self.scripts = scripts self.InventoryType = 0x01 # InventoryType TX 0x01 se...
317,730
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def Deserialize(self, reader): self.DeserializeUnsigned(reader) self.scripts = reader.ReadSerializableArray() self.OnDeserialized()
317,736
Deserialize object instance from the specified buffer. Args: buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from. offset: UNUSED Returns: Transaction:
def DeserializeFromBufer(buffer, offset=0): mstream = StreamManager.GetStream(buffer) reader = BinaryReader(mstream) tx = Transaction.DeserializeFrom(reader) StreamManager.ReleaseStream(mstream) return tx
317,737
Deserialize full object. Args: reader (neo.IO.BinaryReader): Returns: Transaction:
def DeserializeFrom(reader): ttype = reader.ReadByte() tx = None from neo.Core.TX.RegisterTransaction import RegisterTransaction from neo.Core.TX.IssueTransaction import IssueTransaction from neo.Core.TX.ClaimTransaction import ClaimTransaction from neo.Core.TX....
317,738
Deserialize object. Args: reader (neo.IO.BinaryReader): Raises: Exception: if transaction type is incorrect.
def DeserializeUnsigned(self, reader): txtype = reader.ReadByte() if txtype != int.from_bytes(self.Type, 'little'): raise Exception('incorrect type {}, wanted {}'.format(txtype, int.from_bytes(self.Type, 'little'))) self.DeserializeUnsignedWithoutType(reader)
317,739
Deserialize object without reading transaction type data. Args: reader (neo.IO.BinaryReader):
def DeserializeUnsignedWithoutType(self, reader): self.Version = reader.ReadByte() self.DeserializeExclusiveData(reader) self.Attributes = reader.ReadSerializableArray('neo.Core.TX.TransactionAttribute.TransactionAttribute', max=sel...
317,740
Serialize object. Args: writer (neo.IO.BinaryWriter):
def Serialize(self, writer): self.SerializeUnsigned(writer) writer.WriteSerializableArray(self.scripts)
317,742
Serialize object. Args: writer (neo.IO.BinaryWriter):
def SerializeUnsigned(self, writer): writer.WriteByte(self.Type) writer.WriteByte(self.Version) self.SerializeExclusiveData(writer) if len(self.Attributes) > self.MAX_TX_ATTRIBUTES: raise Exception("Cannot have more than %s transaction attributes" % self.MAX_TX_ATTR...
317,743
Verify the transaction. Args: mempool: Returns: bool: True if verified. False otherwise.
def Verify(self, mempool): logger.info("Verifying transaction: %s " % self.Hash.ToBytes()) return Helper.VerifyScripts(self)
317,745
Create an instance. Args: *args: **kwargs:
def __init__(self, *args, **kwargs): super(ContractTransaction, self).__init__(*args, **kwargs) self.Type = TransactionType.ContractTransaction
317,748
Convert a StackItem to a ContractParameter object Args: item (neo.VM.InteropService.StackItem) The item to convert to a ContractParameter object Returns: ContractParameter
def ToParameter(item: StackItem): if isinstance(item, Array) or isinstance(item, Struct): items = item.GetArray() output = [ContractParameter.ToParameter(subitem) for subitem in items] return ContractParameter(type=ContractParameterType.Array, value=output) ...
317,754
Convert a StackItem to a ContractParameter object of a specified ContractParameterType Args: type (neo.SmartContract.ContractParameterType): The ContractParameterType to convert to item (neo.VM.InteropService.StackItem): The item to convert to a ContractParameter object Returns:
def AsParameterType(type: ContractParameterType, item: StackItem): if type == ContractParameterType.Integer: return ContractParameter(type, value=item.GetBigInteger()) elif type == ContractParameterType.Boolean: return ContractParameter(type, value=item.GetBoolean()) ...
317,755
Convert a json object to a ContractParameter object Args: item (dict): The item to convert to a ContractParameter object Returns: ContractParameter
def FromJson(json): type = ContractParameterType.FromString(json['type']) value = json['value'] param = ContractParameter(type=type, value=None) if type == ContractParameterType.Signature or type == ContractParameterType.ByteArray: param.Value = bytearray.fromhex(v...
317,758
Get a Coin object using a CoinReference. Args: coin_ref (neo.Core.CoinReference): an object representing a single UTXO / transaction input. tx_output (neo.Core.Transaction.TransactionOutput): an object representing a transaction output. state (neo.Core.State.CoinState): ...
def CoinFromRef(coin_ref, tx_output, state=CoinState.Unconfirmed, transaction=None): coin = Coin(coin_reference=coin_ref, tx_output=tx_output, state=state) coin._transaction = transaction return coin
317,760
Create an instance. Args: prev_hash (UInt256): hash of the previous output. prev_index (int):
def __init__(self, prev_hash=None, prev_index=None): self.PrevHash = prev_hash self.PrevIndex = prev_index
317,763
Test for equality. Args: other (obj): Returns: bool: True `other` equals self.
def Equals(self, other): if other is None: return False if other.PrevHash.ToBytes() == self.PrevHash.ToBytes() and other.PrevIndex == self.PrevIndex: return True return False
317,764
Create an instance. Args: address (str): port (int): services (int): timestamp (int):
def __init__(self, address=None, port=None, services=0, timestamp=int(datetime.utcnow().timestamp())): self.Address = address self.Port = port self.Services = services self.Timestamp = timestamp
317,769
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def Deserialize(self, reader): self.Timestamp = reader.ReadUInt32() self.Services = reader.ReadUInt64() addr = bytearray(reader.ReadFixedString(16)) addr.reverse() addr.strip(b'\x00') nums = [] for i in range(0, 4): nums.append(str(addr[i])) ...
317,770
Serialize object. Args: writer (neo.IO.BinaryWriter):
def Serialize(self, writer): writer.WriteUInt32(self.Timestamp) writer.WriteUInt64(self.Services) # turn ip address into bytes octets = bytearray(map(lambda oct: int(oct), self.Address.split('.'))) # pad to fixed length 16 octets += bytearray(12) # and fi...
317,771
Get the data used for hashing. Args: hashable (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin Returns: bytes:
def GetHashData(hashable): ms = StreamManager.GetStream() writer = BinaryWriter(ms) hashable.SerializeUnsigned(writer) ms.flush() retVal = ms.ToArray() StreamManager.ReleaseStream(ms) return retVal
317,779
Sign the `verifiable` object with the private key from `keypair`. Args: verifiable: keypair (neocore.KeyPair): Returns: bool: True if successfully signed. False otherwise.
def Sign(verifiable, keypair): prikey = bytes(keypair.PrivateKey) hashdata = verifiable.GetHashData() res = Crypto.Default().Sign(hashdata, prikey) return res
317,780
Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: hex formatted bytes
def ToArray(value): ms = StreamManager.GetStream() writer = BinaryWriter(ms) value.Serialize(writer) retVal = ms.ToArray() StreamManager.ReleaseStream(ms) return retVal
317,781
Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: not hexlified
def ToStream(value): ms = StreamManager.GetStream() writer = BinaryWriter(ms) value.Serialize(writer) retVal = ms.getvalue() StreamManager.ReleaseStream(ms) return retVal
317,782
Convert a public address to a script hash. Args: address (str): base 58 check encoded public address. Raises: ValueError: if the address length of address version is incorrect. Exception: if the address checksum fails. Returns: UInt160:
def AddrStrToScriptHash(address): data = b58decode(address) if len(data) != 25: raise ValueError('Not correct Address, wrong length.') if data[0] != settings.ADDRESS_VERSION: raise ValueError('Not correct Coin Version') checksum = Crypto.Default().Hash25...
317,783
Get a hash of the provided raw bytes using the ripemd160 algorithm. Args: raw (bytes): byte array of raw bytes. e.g. b'\xAA\xBB\xCC' Returns: UInt160:
def RawBytesToScriptHash(raw): rawh = binascii.unhexlify(raw) rawhashstr = binascii.unhexlify(bytes(Crypto.Hash160(rawh), encoding='utf-8')) return UInt160(data=rawhashstr)
317,784
Verify the scripts of the provided `verifiable` object. Args: verifiable (neo.IO.Mixins.VerifiableMixin): Returns: bool: True if verification is successful. False otherwise.
def VerifyScripts(verifiable): try: hashes = verifiable.GetScriptHashesForVerifying() except Exception as e: logger.debug("couldn't get script hashes %s " % e) return False if len(hashes) != len(verifiable.Scripts): logger.debug(f"hash - ...
317,785