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_name = path_and_class.split('.')[-1] class_obj = getattr(module, class_name) return class_obj except AttributeError as err: raise ValueError(f"Failed to get class {class_name} with error: {err}")
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 = DBCollection(bc._db, DBPrefix.ST_Account, AccountState) assets = DBCollection(bc._db, DBPrefix.ST_Asset, AssetState) validators = DBCollection(bc._db, DBPrefix.ST_Validator, ValidatorState) contracts = DBCollection(bc._db, DBPrefix.ST_Contract, ContractState) storages = DBCollection(bc._db, 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=gas, testMode=test_mode, exit_on_error=exit_on_error ) script = binascii.unhexlify(script) engine.LoadScript(script) try: success = engine.Execute() engine.testMode = True service.ExecutionCompleted(engine, success) except Exception as e: engine.testMode = True service.ExecutionCompleted(engine, False, e) for event in service.events_to_dispatch: events.emit(event.event_type, event) return engine
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 (UInt160):
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
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_Secp256r1(reader) # self.Owner = ecdsa.G self.Admin = reader.ReadUInt160()
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() c.Deserialize(reader) claims.append(c) self.Claims = claims if len(self.Claims) == 0: raise Exception('Format Exception')
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 see if they intersect the claims of this transaction # and if that number is greater than zero that we do not verify # (now, to do that in python) # if (mempool.OfType < ClaimTransaction > ().Where(p => p != this).SelectMany(p= > p.Claims).Intersect(Claims).Count() > 0) # return false; # im sorry about the below otherclaimTxs = [tx for tx in mempool if tx is ClaimTransaction and tx is not self] for other in otherclaimTxs: # check to see if the length of the intersection between this objects claim's and the other txs claims is > 0 if len([list(filter(lambda x: x in self.Claims, otherClaims)) for otherClaims in other.Claims]): return False txResult = None for tx in self.GetTransactionResults(): if tx.AssetId == Blockchain.SystemCoin().Hash: txResult = tx break if txResult is None or txResult.Amount > Fixed8(0): return False try: return Blockchain.CalculateBonusIgnoreClaimed(self.Claims, False) == -txResult.Amount except Exception as e: logger.error('Could not calculate bonus: %s ' % e) return False
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 Transaction or UInt256 or str TxNotFoundInBlockchainError: if tx is not found in blockchain after max_seconds
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" % type(tx)) wait_event = Event() time_start = time.time() while True: # Try to find transaction in blockchain _tx, height = Blockchain.Default().GetTransaction(tx_hash) if height > -1: return True # Using a wait event for the delay because it is not blocking like time.sleep() wait_event.wait(3) seconds_passed = time.time() - time_start if seconds_passed > max_seconds: raise TxNotFoundInBlockchainError("Transaction with hash %s not found after %s seconds" % (tx_hash, int(seconds_passed)))
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._watch_only.remove(contract.ScriptHash)
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("PasswordHash", password_key) self.SaveStoredData("MasterKey", AES.new(self._master_key, AES.MODE_CBC, self._iv)) return True
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.Coin`` objects to be removed from the wallet.
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(coinref) for k in coin_keys_toremove: del self._coins[k] ok = False if script_hash.ToBytes() in self._contracts.keys(): ok = True del self._contracts[script_hash.ToBytes()] elif script_hash in self._watch_only: ok = True self._watch_only.remove(script_hash) return ok, coins_to_remove
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) return ret
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 whether or not to find coins that are in 'watch only' addresses. Returns: list: a list of ``neo.Wallet.Coins`` in the wallet that are not spent.
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 and \ coin.State & CoinState.Frozen == 0 and \ coin.State & CoinState.WatchOnly == watch_only_val: do_exclude = False if self._vin_exclude: for to_exclude in self._vin_exclude: if coin.Reference.PrevIndex == to_exclude.PrevIndex and \ coin.Reference.PrevHash == to_exclude.PrevHash: do_exclude = True if do_exclude: continue if from_addr is not None: if coin.Output.ScriptHash == from_addr: ret.append(coin) elif use_standard: contract = self._contracts[coin.Output.ScriptHash.ToBytes()] if contract.IsStandard: ret.append(coin) else: ret.append(coin) return ret
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(): balance = token.GetBalance(self, contract.Address) total += balance return total
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: Fixed8: total balance.
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 & 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
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 enumerate(tx.outputs): # check to see if the outputs in the tx are in this wallet state = self.CheckAddressState(output.ScriptHash) if state & AddressState.InWallet > 0: # if it's in the wallet, check to see if the coin exists yet key = CoinReference(tx.Hash, index) # if it exists, update it, otherwise create a new one if key in self._coins.keys(): coin = self._coins[key] coin.State |= CoinState.Confirmed changed.add(coin) else: newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Confirmed, transaction=tx) self._coins[key] = newcoin added.add(newcoin) if state & AddressState.WatchOnly > 0: self._coins[key].State |= CoinState.WatchOnly changed.add(self._coins[key]) # now iterate over the inputs of the tx and do the same for tx in block.FullTransactions: for input in tx.inputs: if input in self._coins.keys(): if self._coins[input].Output.AssetId == Blockchain.SystemShare().Hash: coin = self._coins[input] coin.State |= CoinState.Spent | CoinState.Confirmed changed.add(coin) else: deleted.add(self._coins[input]) del self._coins[input] for claimTx in [tx for tx in block.Transactions if tx.Type == TransactionType.ClaimTransaction]: for ref in claimTx.Claims: if ref in self._coins.keys(): deleted.add(self._coins[ref]) del self._coins[ref] # update the current height of the wallet self._current_height += 1 # in the case that another wallet implementation needs to do something # with the coins that have been changed ( ie persist to db ) this # method is called self.OnProcessNewBlock(block, added, changed, deleted) # this is not necessary at the moment, but any outside process # that wants to subscribe to the balance changed event could do # so from the BalanceChanged method if len(added) + len(deleted) + len(changed) > 0: self.BalanceChanged() except Exception as e: traceback.print_stack() traceback.print_exc() logger.error("could not process %s " % e)
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.VerificationScript: if bytes(contract.Script) == script.VerificationScript: return True for watch_script_hash in self._watch_only: for output in tx.outputs: if output.ScriptHash == watch_script_hash: return True for script in tx.scripts: if Crypto.ToScriptHash(script.VerificationScript, unhex=False) == watch_script_hash: return True return False
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 AddressState.InWallet | AddressState.WatchOnly return AddressState.NoState
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 Returns: UInt160: script hash.
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(data[:21])[:4] if checksum != data[21:]: raise Exception('Address format error') return UInt160(data=data[1:21]) else: raise Exception('Address format error') else: raise ValueError('Not correct Address, wrong length.')
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.IsStandard: return contract.ScriptHash if len(self._contracts.values()): for k, v in self._contracts.items(): return v raise Exception("Could not find change address")
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 trying to sign the transaction for is imported in the wallet.") continue key = self.GetKeyByScriptHash(hash) if key is None: continue signature = Helper.Sign(context.Verifiable, key) res = context.AddSignature(contract, key.PublicKey, signature) success |= res return success
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 mstream = __mstreams_available__.pop() if data is not None and len(data): mstream.Cleanup() mstream.write(data) mstream.seek(0) return mstream
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)) db_account, created = Account.get_or_create( PrivateKeyEncrypted=encrypted_pk, PublicKeyHash=account.PublicKeyHash.ToBytes()) db_account.save() self.__dbaccount = db_account
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") sh = bytes(contract.ScriptHash.ToArray()) address, created = Address.get_or_create(ScriptHash=sh) address.IsWatchOnly = False address.save() db_contract = Contract.create(RawData=contract.ToArray(), ScriptHash=contract.ScriptHash.ToBytes(), PublicKeyHash=contract.PublicKeyHash.ToBytes(), Address=address, Account=self.__dbaccount) logger.debug("Creating db contract %s " % db_contract) db_contract.save()
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 self.buffer_in = bytearray() self.myblockrequests = set() self.bytes_in = 0 self.bytes_out = 0 self.sync_mode = MODE_CATCHUP self.host = None self.port = None self.incoming_client = incoming_client self.handshake_complete = False self.expect_verack_next = False self.start_outstanding_data_request = {HEARTBEAT_BLOCKS: 0, HEARTBEAT_HEADERS: 0} self.block_loop = None self.block_loop_deferred = None self.peer_loop = None self.peer_loop_deferred = None self.header_loop = None self.header_loop_deferred = None self.disconnect_deferred = None self.disconnecting = False logger.debug(f"{self.prefix} new node created, not yet connected")
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: self.expect_verack_next = False else: self.HandleVerack() elif m.Command == 'version': self.HandleVersion(m.Payload) elif m.Command == 'getaddr': self.SendPeerInfo() elif m.Command == 'getdata': self.HandleGetDataMessageReceived(m.Payload) elif m.Command == 'getblocks': self.HandleGetBlocksMessageReceived(m.Payload) elif m.Command == 'inv': self.HandleInvMessage(m.Payload) elif m.Command == 'block': self.HandleBlockReceived(m.Payload) elif m.Command == 'getheaders': self.HandleGetHeadersMessageReceived(m.Payload) elif m.Command == 'headers': self.HandleBlockHeadersReceived(m.Payload) elif m.Command == 'addr': self.HandlePeerInfoReceived(m.Payload) else: logger.debug(f"{self.prefix} Command not implemented: {m.Command}")
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: ok_hashes = [] for hash in inventory.Hashes: hash = hash.encode('utf-8') if hash not in self.myblockrequests and hash not in BC.Default().BlockRequests: ok_hashes.append(hash) BC.Default().BlockRequests.add(hash) self.myblockrequests.add(hash) if len(ok_hashes): message = Message("getdata", InvPayload(InventoryType.Block, ok_hashes)) self.SendSerializedMessage(message) elif inventory.Type == InventoryType.TXInt: pass elif inventory.Type == InventoryType.ConsensusInt: pass
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_beat(HEARTBEAT_HEADERS) BC.Default().AddHeaders(inventory.Headers) except Exception as e: logger.debug(f"Error handling Block headers {e}")
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().BlockRequests.remove(blockhash) except KeyError: pass try: if blockhash in self.myblockrequests: # logger.debug(f"{self.prefix} received block: {block.Index}") self.heart_beat(HEARTBEAT_BLOCKS) self.myblockrequests.remove(blockhash) except KeyError: pass self.leader.InventoryReceived(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 # try to get the inventory to send from relay cache if hash in self.leader.RelayCache.keys(): item = self.leader.RelayCache[hash] if inventory.Type == InventoryType.TXInt: if not item: item, index = BC.Default().GetTransaction(hash) if not item: item = self.leader.GetTransaction(hash) if item: message = Message(command='tx', payload=item, print_payload=False) self.SendSerializedMessage(message) elif inventory.Type == InventoryType.BlockInt: if not item: item = BC.Default().GetBlock(hash) if item: message = Message(command='block', payload=item, print_payload=False) self.SendSerializedMessage(message) elif inventory.Type == InventoryType.ConsensusInt: if item: self.SendSerializedMessage(Message(command='consensus', payload=item, print_payload=False))
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() hash = inventory.HashStart[0] if not blockchain.GetHeader(hash): return hashes = [] hcount = 0 while hash != inventory.HashStop and hcount < 500: hash = blockchain.GetNextBlockHash(hash) if hash is None: break hashes.append(hash) hcount += 1 if hcount > 0: self.SendSerializedMessage(Message('inv', InvPayload(type=InventoryType.Block, hashes=hashes)))
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.GetChecksum(payload) self.Payload = payload if print_payload: logger.info("PAYLOAD: %s " % self.Payload)
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.Checksum = reader.ReadUInt32() self.Payload = reader.ReadBytes(self.Length) checksum = Message.GetChecksum(self.Payload) if checksum != self.Checksum: raise ChecksumException("checksum mismatch")
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): # convert it to equal type data = attr.Data.ToArray() # only add if it's not already in the list if data not in script_list: script_list.append(data) filtered_attr.append(attr) return filtered_attr
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): self.Data = reader.ReadBytes(32) elif usage == TransactionAttributeUsage.ECDH02 or usage == TransactionAttributeUsage.ECDH03: self.Data = bytearray(usage) + bytearray(reader.ReadBytes(32)) elif usage == TransactionAttributeUsage.Script: self.Data = reader.ReadBytes(20) elif usage == TransactionAttributeUsage.DescriptionUrl: self.Data = reader.ReadBytes(reader.ReadByte()) elif usage == TransactionAttributeUsage.Description or usage >= TransactionAttributeUsage.Remark: self.Data = reader.ReadVarBytes(max=self.MAX_ATTR_DATA_SIZE) else: logger.error("format error!!!")
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.Usage == TransactionAttributeUsage.ContractHash or self.Usage == TransactionAttributeUsage.Vote or \ (self.Usage >= TransactionAttributeUsage.Hash1 and self.Usage <= TransactionAttributeUsage.Hash15): writer.WriteBytes(self.Data) elif self.Usage == TransactionAttributeUsage.ECDH02 or self.Usage == TransactionAttributeUsage.ECDH03: writer.WriteBytes(self.Data[1:33]) elif self.Usage == TransactionAttributeUsage.Script: writer.WriteBytes(self.Data) elif self.Usage == TransactionAttributeUsage.DescriptionUrl: writer.WriteVarString(self.Data) elif self.Usage == TransactionAttributeUsage.Description or self.Usage >= TransactionAttributeUsage.Remark: writer.WriteVarString(self.Data) else: logger.error("format error!!!")
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 self.__references = None
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.MinerTransaction import MinerTransaction from neo.Core.TX.PublishTransaction import PublishTransaction from neo.Core.TX.InvocationTransaction import InvocationTransaction from neo.Core.TX.EnrollmentTransaction import EnrollmentTransaction from neo.Core.TX.StateTransaction import StateTransaction if ttype == int.from_bytes(TransactionType.RegisterTransaction, 'little'): tx = RegisterTransaction() elif ttype == int.from_bytes(TransactionType.MinerTransaction, 'little'): tx = MinerTransaction() elif ttype == int.from_bytes(TransactionType.IssueTransaction, 'little'): tx = IssueTransaction() elif ttype == int.from_bytes(TransactionType.ClaimTransaction, 'little'): tx = ClaimTransaction() elif ttype == int.from_bytes(TransactionType.PublishTransaction, 'little'): tx = PublishTransaction() elif ttype == int.from_bytes(TransactionType.InvocationTransaction, 'little'): tx = InvocationTransaction() elif ttype == int.from_bytes(TransactionType.EnrollmentTransaction, 'little'): tx = EnrollmentTransaction() elif ttype == int.from_bytes(TransactionType.StateTransaction, 'little'): tx = StateTransaction() else: tx = Transaction() tx.Type = ttype tx.DeserializeUnsignedWithoutType(reader) tx.scripts = [] byt = reader.ReadVarInt() if byt > 0: for i in range(0, byt): witness = Witness() witness.Deserialize(reader) tx.scripts.append(witness) tx.OnDeserialized() return 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=self.MAX_TX_ATTRIBUTES) self.inputs = reader.ReadSerializableArray('neo.Core.CoinReference.CoinReference') self.outputs = reader.ReadSerializableArray('neo.Core.TX.Transaction.TransactionOutput')
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_ATTRIBUTES) writer.WriteSerializableArray(self.Attributes) writer.WriteSerializableArray(self.inputs) writer.WriteSerializableArray(self.outputs)
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) elif isinstance(item, Boolean): return ContractParameter(type=ContractParameterType.Boolean, value=item.GetBoolean()) elif isinstance(item, ByteArray): return ContractParameter(type=ContractParameterType.ByteArray, value=item.GetByteArray()) elif isinstance(item, Integer): return ContractParameter(type=ContractParameterType.Integer, value=str(item.GetBigInteger())) elif isinstance(item, InteropInterface): return ContractParameter(type=ContractParameterType.InteropInterface, value=item.GetInterface())
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()) elif type == ContractParameterType.Array: output = [ContractParameter.ToParameter(subitem) for subitem in item.GetArray()] return ContractParameter(type, value=output) elif type == ContractParameterType.String: return ContractParameter(type, value=item.GetString()) elif type == ContractParameterType.InteropInterface: return ContractParameter(type, value=item.GetInterface()) # all other types return a byte array else: return ContractParameter(type, value=item.GetByteArray())
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(value) elif type == ContractParameterType.Boolean: param.Value = bool(value) elif type == ContractParameterType.Integer: param.Value = int(value) elif type == ContractParameterType.Hash160: param.Value = UInt160.ParseString(value) elif type == ContractParameterType.Hash256: param.Value = UInt256.ParseString(value) # @TODO Not sure if this is working... elif type == ContractParameterType.PublicKey: param.Value = ECDSA.decode_secp256r1(value).G elif type == ContractParameterType.String: param.Value = str(value) elif type == ContractParameterType.Array: val = [ContractParameter.FromJson(item) for item in value] param.Value = val return param
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): Returns: Coin: self.
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])) nums.reverse() adddd = '.'.join(nums) self.Address = adddd self.Port = reader.ReadUInt16(endian='>')
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 finally write to stream writer.WriteBytes(octets) writer.WriteUInt16(self.Port, endian='>')
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().Hash256(data[:21])[:4] if checksum != data[21:]: raise Exception('Address format error') return UInt160(data=data[1:21])
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 - verification script length mismatch ({len(hashes)}/{len(verifiable.Scripts)})") return False blockchain = GetBlockchain() for i in range(0, len(hashes)): verification = verifiable.Scripts[i].VerificationScript if len(verification) == 0: sb = ScriptBuilder() sb.EmitAppCall(hashes[i].Data) verification = sb.ms.getvalue() else: verification_hash = Crypto.ToScriptHash(verification, unhex=False) if hashes[i] != verification_hash: logger.debug(f"hash {hashes[i]} does not match verification hash {verification_hash}") return False state_reader = GetStateReader() script_table = CachedScriptTable(DBCollection(blockchain._db, DBPrefix.ST_Contract, ContractState)) engine = ApplicationEngine(TriggerType.Verification, verifiable, script_table, state_reader, Fixed8.Zero()) engine.LoadScript(verification) invocation = verifiable.Scripts[i].InvocationScript engine.LoadScript(invocation) try: success = engine.Execute() state_reader.ExecutionCompleted(engine, success) except Exception as e: state_reader.ExecutionCompleted(engine, False, e) if engine.ResultStack.Count != 1 or not engine.ResultStack.Pop().GetBoolean(): Helper.EmitServiceEvents(state_reader) if engine.ResultStack.Count > 0: logger.debug(f"Result stack failure! Count: {engine.ResultStack.Count} bool value: {engine.ResultStack.Pop().GetBoolean()}") else: logger.debug(f"Result stack failure! Count: {engine.ResultStack.Count}") return False Helper.EmitServiceEvents(state_reader) return True
317,785