Unit Noso.Network

Description

Unit for network utils.

Uses

Overview

Classes, Interfaces, Objects and Records

Name Description
Packed Record TBotData Stores data related to a bot, such as its IP address and the timestamp of the last refused connection.
Class TClientReadThread Thread for handling client read operations in a connection slot.
Packed Record TConnectionData Represents the data of a network connection.
Packed Record TNodeData Stores basic data for a network node.
Class TNodeServerEvents Handles various TCP server events for the node, such as connect, disconnect, execution, and exceptions.

Functions and Procedures

procedure AddIncomingMessage(const SlotIndex: Integer; const IncomingMessage: String);
procedure AddTextToSlot(const Slot: Integer; const Text: String);
function AddTransactionToPool(const Order: TOrderData): Boolean;
function BotExists(const BotIp: String): Boolean;
procedure ClearAllPendingTransactions();
procedure ClearElements();
procedure ClearIncomingMessages(SlotIndex: Integer);
procedure ClearOutgoingTextForSlot(const Slot: Integer);
procedure CloseConnectionSlot(const Slot: Integer);
procedure DecrementClientReadThreadCount();
function GenerateMasternodeVerificationLine(const MasternodeIP: String): String;
function GetActiveClientReadThreadCount(): Integer;
function GetClientCount: Integer;
function GetConnectionData(const Slot: Integer): TConnectionData;
function GetIncomingMessage(const SlotIndex: Integer): String;
function GetIncomingMessageLength(const SlotIndex: Integer): Integer;
function GetNodeDataAtIndex(const Index: Integer): TNodeData;
function GetNodeListLength(): Integer;
function GetOutgoingTextForSlot(const Slot: Integer): String;
function GetPendingTransactionCount(): Integer;
function GetPingString(): String;
function GetProtocolHeader(): String;
function GetProtocolLineFromCode(const Code: Integer): String;
function GetSynchronizationStatus(): String;
function GetTotalConnections(): Integer;
procedure IncrementClientReadThreadCount();
procedure InitializeElements();
procedure InitializeNodeServer();
function IsAllSynchronized(): TSyncStatus;
function IsNodeValidator(const Ip: String): Boolean;
function IsSlotConnected(const Slot: Integer): Boolean;
function IsValidProtocol(const Line: String): Boolean;
procedure PopulateNodeList();
procedure ProcessIncomingCommand(const Slot: Integer; const Line: String);
procedure ProcessPingCommand(const Line: String; const Slot: Integer; ShouldRespond: Boolean);
procedure RemoveAllBots();
procedure ReserveConnectionSlot(const Slot: Integer; IsReserved: Boolean);
function RetrieveStreamFromClient(AContext: TIdContext; out Stream: TMemoryStream): Boolean;
procedure SafelyCloseClientConnection(AContext: TIdContext; CloseMessage: String = '');
procedure SendMasternodeChecksToPeer(const PeerSlot: Integer);
procedure SendMasternodeListToPeer(const PeerSlot: Integer);
function SendMessageToClient(AContext: TIdContext; Message: String): Boolean;
procedure SendPendingTransactionsToPeer(const Slot: Int64);
procedure SetConnectionBusy(const Slot: Integer; Busy: Boolean);
procedure SetConnectionData(const Slot: Integer; const Data: TConnectionData);
procedure StartConnectionThread(const Slot: Integer);
function TransactionAlreadyPending(const Hash: String): Boolean;
function TransferExistsInLastBlock(const TransferHash: String): Boolean;
procedure UpdateBotData(const BotIP: String);
procedure UpdateConnectionLastPing(const Slot: Integer; Value: String);
procedure UpdateNodeData();
function ValidateMasternodeCheck(const Line: String): String;

Types

TBlockNumber = String[15];
TConnectionChannelList = array [1..MaxConnections] of TIdTCPClient;
TConnectionCriticalSectionList = array[1..MaxConnections] of TRTLCriticalSection;
TConnectionList = array [1..MaxConnections] of TConnectionData;
TConnectionOutgoingMessagesList = array [1..MaxConnections] of TStringArray;
TConnectionStringListArray = array [1..MaxConnections] of TStringList;
THashIdentifier = String[5];
THashString = String[32];
TLongHashString = String[64];
TSyncStatus = (...);
TTimeStamp = String[15];
TTimestampInteger = Int64;

Constants

MainnetVersion = '0.4.4';
MaxConnections = 99;
ProtocolVersion = 2;

Variables

ActiveClientReadThreads: Integer = 0;
BotList: specialize TArray<TBotData>;
BotListLock: TRTLCriticalSection;
ClientChannels: TConnectionChannelList;
ClientReadThreadsLock: TRTLCriticalSection;
Connections: TConnectionList;
ConnectionsLock: TRTLCriticalSection;
DownloadingBlocks: Boolean = False;
DownloadingGVTs: Boolean = False;
DownloadingHeaders: Boolean = False;
DownloadingPSOs: Boolean = False;
DownloadingSummary: Boolean = False;
ForceHeadersDownload: Boolean = False;
IncomingMessagesLock: TConnectionCriticalSectionList;
LastAccountSummaryRequestTime: TTimestampInteger = 0;
LastBestHashRequestTime: TTimestampInteger = 0;
LastBlockData: BlockHeaderData;
LastBlockHash: String = '';
LastBlockIndex: Integer = 0;
LastBlockRequestTime: TTimestampInteger = 0;
LastBotClearTime: TTimestampInteger = 0;
LastGVTsRequestTime: TTimestampInteger = 0;
LastMasternodeCheckRequestTime: TTimestampInteger = 0;
LastMasternodeHashRequestTime: TTimestampInteger = 0;
LastMasternodeListRequestTime: TTimestampInteger = 0;
LastMasternodeVerificationTime: TTimestampInteger = 0;
LastPendingTransactionsRequestTime: TTimestampInteger = 0;
LastPSOsRequestTime: TTimestampInteger = 0;
LastSummaryRequestTime: TTimestampInteger = 0;
MasternodeVerificationCount: Integer = 0;
MultiOrderTransactionsLock: TRTLCriticalSection;
MultiOrderTransactionsPool: specialize TArray<TMultiOrderData>;
NodeList: specialize TArray<TNodeData>;
NodeListLock: TRTLCriticalSection;
NodeServer: TIdTCPServer;
OutgoingMessages: TConnectionOutgoingMessagesList;
OutgoingMessagesLock: TConnectionCriticalSectionList;
PendingTransactionsLock: TRTLCriticalSection;
PendingTransactionsPool: specialize TArray<TOrderData>;
PublicIPAddress: String = '';
SlotTextLines: TConnectionStringListArray;

Description

Functions and Procedures

procedure AddIncomingMessage(const SlotIndex: Integer; const IncomingMessage: String);

Adds an incoming message to the message queue for the given connection slot.

Parameters
SlotIndex
Index of the connection slot.
IncomingMessage
String The incoming message to be added.
procedure AddTextToSlot(const Slot: Integer; const Text: String);

Adds a text message to the outgoing message queue for the given slot.

Parameters
Slot
The slot index to which the text message will be added.
Text
The text message to add to the slot's outgoing message queue.
function AddTransactionToPool(const Order: TOrderData): Boolean;

Adds a new transaction to the pending pool in a thread-safe manner.

The function finds the correct insertion position based on timestamps and order IDs.

Parameters
Order
The transaction data to add to the pending pool.
Returns

True if the transaction was successfully added, otherwise False.

function BotExists(const BotIp: String): Boolean;

Checks if a bot with the given IP address exists in the bot list.

Parameters
BotIP
The IP address of the bot to check.
Returns

True if the bot exists, False otherwise.

procedure ClearAllPendingTransactions();

Clears all pending transactions.

procedure ClearElements();

This item has no description.

procedure ClearIncomingMessages(SlotIndex: Integer);

Clears all incoming messages from the message queue for the given connection slot.

Parameters
SlotIndex
Index of the connection slot.
procedure ClearOutgoingTextForSlot(const Slot: Integer);

Clears all outgoing text messages for the given slot.

Parameters
Slot
The slot index for which the outgoing messages will be cleared.
procedure CloseConnectionSlot(const Slot: Integer);

Closes the connection for the specified slot.

Parameters
Slot
The index of the connection slot.
procedure DecrementClientReadThreadCount();

Decrements the active client read thread count.

function GenerateMasternodeVerificationLine(const MasternodeIP: String): String;

Generates a masternode verification line for a given masternode IP. The verification includes synchronization status and other relevant data.

Parameters
MasternodeIP
The IP address of the target masternode.
Returns

A string representing the verification line.

function GetActiveClientReadThreadCount(): Integer;

Retrieves the current number of active client read threads.

Returns

Number of active client read threads.

function GetClientCount: Integer;

Retrieves the current number of active client connections to the node server.

Returns

The number of active client connections.

function GetConnectionData(const Slot: Integer): TConnectionData;

Retrieves the connection data for the given slot.

Parameters
Slot
The index of the connection slot.
Returns

The connection data for the slot, or a default value if the slot is invalid.

function GetIncomingMessage(const SlotIndex: Integer): String;

Retrieves and removes the first incoming message from the message queue for the given connection slot.

Parameters
SlotIndex
Index of the connection slot.
Returns

String The incoming message. If no messages are available, returns an empty string.

function GetIncomingMessageLength(const SlotIndex: Integer): Integer;

Retrieves the number of incoming messages in the message queue for the given connection slot.

Parameters
SlotIndex
Index of the connection slot.
Returns

The number of incoming messages.

function GetNodeDataAtIndex(const Index: Integer): TNodeData;

Retrieves the node data at the specified index from the node list.

Parameters
Index
The index of the node data to retrieve.
Returns

The node data at the specified index, or a default value if the index is out of bounds.

function GetNodeListLength(): Integer;

Returns the length of the node list.

Returns

The length of the node list.

function GetOutgoingTextForSlot(const Slot: Integer): String;

Retrieves and removes the first outgoing text message for the given slot.

Parameters
Slot
The slot index from which to retrieve the outgoing message.
Returns

The first message for the slot, or an empty string if no messages exist.

function GetPendingTransactionCount(): Integer;

Return the number of pending transactions.

Returns

Return the number of pending transactions in the pool.

function GetPingString(): String;

Generates a ping string.

A ping string contains details about the current node's state, including connections, last block, and transaction information.

Returns

A formatted ping string.

function GetProtocolHeader(): String;

Returns the protocol header.

The protocol header is of the form "PSK P MN U", where P is the protocol version (currently 2), M is the Mainnet version (0.4.4), N is the node release (Ab7) and U is UTCTimeStr. For instance, a valid header is: "PSK 2 0.4.4Ab7 1726431338".

Returns

The protocol header in the given format.

function GetProtocolLineFromCode(const Code: Integer): String;

Generates a specific protocol line based on the provided code.

The protocol line varies according to the command type represented by the code.

Parameters
Code
The integer code representing a specific protocol command.
Returns

A formatted protocol line for the given command code.

function GetSynchronizationStatus(): String;

Retrieves the current synchronization status of the node as a formatted string. This status is a combination of the last block index, resumen hash, summary hash, and last block hash.

Returns

A string representing the synchronization status.

function GetTotalConnections(): Integer;

Retrieves the total number of active connections.

Returns

The count of active connections.

procedure IncrementClientReadThreadCount();

Increments the active client read thread count.

procedure InitializeElements();

This item has no description.

procedure InitializeNodeServer();

Initializes the node server with the necessary configurations and event handlers. This sets up the TCP server but does not activate it.

function IsAllSynchronized(): TSyncStatus;

Checks if the local node is fully synchronized with the consensus network.

Returns

A TSyncStatus representing the synchronization status:

function IsNodeValidator(const Ip: String): Boolean;

Checks if the given IP belongs to a node validator.

Parameters
Ip
The IP address of the node.
Returns

True if the IP is a seed node, otherwise False.

function IsSlotConnected(const Slot: Integer): Boolean;

Checks if the specified slot is currently connected.

Parameters
Slot
The index of the connection slot.
Returns

True if the slot is connected, otherwise False.

function IsValidProtocol(const Line: String): Boolean;

Checks if the current line is a valid protocol line (if it starts with PSK or NOS).

Parameters
Line
The line to validate.
Returns

True if Line is a valid protocol line, and False otherwise.

procedure PopulateNodeList();

Populates the node list by extracting nodes from configuration data and verificators text. Each node is parsed from a string and added to the list with its IP address and port.

procedure ProcessIncomingCommand(const Slot: Integer; const Line: String);

Processes an incoming command from the peer, such as ping, pong, or transaction requests.

If the protocol is invalid or the peer is not authenticated, the connection is closed.

Parameters
Slot
The connection slot of the peer.
Line
The incoming command line from the peer.
procedure ProcessPingCommand(const Line: String; const Slot: Integer; ShouldRespond: Boolean);

Processes a ping command received from a peer.

It extracts the peer's data from the line, authenticates the peer, and optionally sends a pong response if ShouldRespond is True.

Parameters
Line
The ping command line from the peer.
Slot
The connection slot of the peer.
ShouldRespond
Whether the server should respond with a pong command.
procedure RemoveAllBots();

Removes all bots from the bot list and resets the bot clear time.

procedure ReserveConnectionSlot(const Slot: Integer; IsReserved: Boolean);

Reserves or releases a connection slot by marking its type.

Parameters
Slot
The index of the connection slot.
IsReserved
Boolean indicating if the slot should be reserved.
function RetrieveStreamFromClient(AContext: TIdContext; out Stream: TMemoryStream): Boolean;

Retrieves a stream of data from the specified client context.

Parameters
AContext
The client context to read the stream from.
Stream
The memory stream to store the received data.
Returns

True if the stream was successfully retrieved, otherwise False.

procedure SafelyCloseClientConnection(AContext: TIdContext; CloseMessage: String = '');

Safely closes the connection with a client, optionally sending a final message before disconnecting.

Parameters
AContext
The client context to disconnect.
CloseMessage
An optional message to send to the client before closing the connection.
procedure SendMasternodeChecksToPeer(const PeerSlot: Integer);

Sends the list of masternode checks to the specified peer. Each check is sent as a separate message to the peer.

Parameters
PeerSlot
The identifier of the peer connection slot.
procedure SendMasternodeListToPeer(const PeerSlot: Integer);

Sends the current list of masternodes to the specified peer. Each masternode's data is sent as a separate message to the peer.

Parameters
PeerSlot
The identifier of the peer connection slot.
function SendMessageToClient(AContext: TIdContext; Message: String): Boolean;

Sends a message to the specified client context in a safe manner.

Parameters
AContext
The client context to send the message to.
Message
The message to be sent.
Returns

True if the message was successfully sent, otherwise False.

procedure SendPendingTransactionsToPeer(const Slot: Int64);

Sends pending transactions to the specified peer slot.

It copies the pending transaction pool safely, and then sends each transaction to the peer based on its type.

Parameters
Slot
The slot number of the peer to send transactions to.
procedure SetConnectionBusy(const Slot: Integer; Busy: Boolean);

Marks the connection slot as busy or not busy.

Parameters
Slot
The index of the connection slot.
Busy
Boolean indicating whether the slot is busy.
procedure SetConnectionData(const Slot: Integer; const Data: TConnectionData);

Sets the connection data for the given slot.

Parameters
Slot
The index of the connection slot.
Data
The connection data to be set for the slot.
procedure StartConnectionThread(const Slot: Integer);

Starts a read thread for the given connection slot.

Parameters
Slot
The index of the connection slot.
function TransactionAlreadyPending(const Hash: String): Boolean;

Checks if a transaction with the given hash already exists in the pending pool.

Note
The function is thread-safe and locks the critical section during the search.

Parameters
Hash
The transfer ID of the transaction to check.
Returns

True if the transaction is already pending, otherwise False.

function TransferExistsInLastBlock(const TransferHash: String): Boolean;

Checks if a transfer with the given hash exists in the last block.

Parameters
TransferHash
The transfer ID to check for.
Returns

True if the transfer exists in the last block, otherwise False.

procedure UpdateBotData(const BotIP: String);

Updates the bot information in the bot list if the bot exists. If the bot does not exist, it adds a new entry.

Parameters
BotIP
String The IP address of the bot to update.
procedure UpdateConnectionLastPing(const Slot: Integer; Value: String);

Updates the last ping time for the given connection slot.

Parameters
Slot
The index of the connection slot.
Value
The timestamp of the last ping.
procedure UpdateNodeData();

Updates the node data by recalculating hashes and block data. Also determines whether to force a headers download.

function ValidateMasternodeCheck(const Line: String): String;

Validates the provided masternode check report.

Verifies various aspects of the report including validator, block index, signature, and address consistency.

Verify if a validation report is correct

Parameters
Line
The masternode check report as a string.
Returns

The validated report information if successful, or an empty string if validation fails.

Types

TBlockNumber = String[15];

Type representing a 15-character block number.

TConnectionChannelList = array [1..MaxConnections] of TIdTCPClient;

A list of TCP client channels (connections) for each client slot.

TConnectionCriticalSectionList = array[1..MaxConnections] of TRTLCriticalSection;

A list of critical sections for synchronizing access to connection-specific resources.

TConnectionList = array [1..MaxConnections] of TConnectionData;

A list that holds connection data for each client connection slot.

TConnectionOutgoingMessagesList = array [1..MaxConnections] of TStringArray;

An array of outgoing message lists, one per connection slot.

TConnectionStringListArray = array [1..MaxConnections] of TStringList;

An array of TStringList objects for holding incoming messages for each connection slot.

THashIdentifier = String[5];

Type representing a short 5-character hash.

THashString = String[32];

Type representing a hash string (MD5, 32 chars, 128 bits).

TLongHashString = String[64];

Type representing a hash string (SHA256?, 64 chars, 256 bits).

TSyncStatus = (...);

An enum representing the synchronization status. Used in IsAllSynchronized.

Values
  • ssSynchronized: Fully synchronized (= 0)
  • ssBlockHeightMismatch: Block height mismatch (= 1)
  • ssBlockHashMismatch: Block hash mismatch (= 2)
  • ssSummaryHashMismatch: Summary hash mismatch (= 3)
  • ssResumenHashMismatch: Resumen hash mismatch (= 4)
TTimeStamp = String[15];

Type representing a UTC timestamp.

TTimestampInteger = Int64;

A type representing timestamps as integers. Used for tracking times in milliseconds since the epoch.

Constants

MainnetVersion = '0.4.4';

The main net version.

MaxConnections = 99;

Maximum number of connections allowed.

ProtocolVersion = 2;

The protocol version used in communication between clients and servers.

Variables

ActiveClientReadThreads: Integer = 0;

The count of active client read threads.

BotList: specialize TArray<TBotData>;

A list of bot-related data, representing known bot nodes.

BotListLock: TRTLCriticalSection;

Critical section for managing access to the bot list.

ClientChannels: TConnectionChannelList;

Holds the TCP client channels for each connection slot, indexed by connection slot.

ClientReadThreadsLock: TRTLCriticalSection;

Critical section for managing access to client read threads.

Connections: TConnectionList;

Holds the connection data for each client, indexed by connection slot.

ConnectionsLock: TRTLCriticalSection;

Critical section for managing access to the connections list.

DownloadingBlocks: Boolean = False;

Indicates whether the blocks are currently being downloaded.

DownloadingGVTs: Boolean = False;

Indicates whether the GVTs are currently being downloaded.

DownloadingHeaders: Boolean = False;

Indicates whether the cHeaders are currently being downloaded.

DownloadingPSOs: Boolean = False;

Indicates whether the PSOs are currently being downloaded.

DownloadingSummary: Boolean = False;

Indicates whether the summary is currently being downloaded.

ForceHeadersDownload: Boolean = False;

Indicates whether to force a download of the cHeaders.

IncomingMessagesLock: TConnectionCriticalSectionList;

Critical sections for synchronizing access to incoming messages for each connection slot.

LastAccountSummaryRequestTime: TTimestampInteger = 0;

Timestamp for the last time the account summary request was made.

LastBestHashRequestTime: TTimestampInteger = 0;

Timestamp for the last time the best hash request was made.

LastBlockData: BlockHeaderData;

Data for the last block processed by the node.

LastBlockHash: String = '';

The hash of the last processed block.

LastBlockIndex: Integer = 0;

The last block index that was processed.

LastBlockRequestTime: TTimestampInteger = 0;

Timestamp for the last time the block request was made.

LastBotClearTime: TTimestampInteger = 0;

Timestamp for the last time the bot list was cleared.

LastGVTsRequestTime: TTimestampInteger = 0;

Timestamp for the last time the GVTs request was made.

LastMasternodeCheckRequestTime: TTimestampInteger = 0;

Timestamp for the last time the masternode check request was made.

LastMasternodeHashRequestTime: TTimestampInteger = 0;

Timestamp for the last time the masternode hash request was made.

LastMasternodeListRequestTime: TTimestampInteger = 0;

Timestamp for the last time the masternode list request was made.

LastMasternodeVerificationTime: TTimestampInteger = 0;

Timestamp for the last time the masternode verification was performed.

LastPendingTransactionsRequestTime: TTimestampInteger = 0;

Timestamp for the last time pending transactions were requested.

LastPSOsRequestTime: TTimestampInteger = 0;

Timestamp for the last time the PSOs request was made.

LastSummaryRequestTime: TTimestampInteger = 0;

Timestamp for the last time the summary request was made.

MasternodeVerificationCount: Integer = 0;

Count of masternode verification processes completed.

MultiOrderTransactionsLock: TRTLCriticalSection;

Critical section for managing access to the multi-order transactions pool.

MultiOrderTransactionsPool: specialize TArray<TMultiOrderData>;

A pool of multi-order transactions awaiting processing.

NodeList: specialize TArray<TNodeData>;

A list of known nodes in the network.

NodeListLock: TRTLCriticalSection;

Critical section for managing access to the node list.

NodeServer: TIdTCPServer;

The TCP server instance for managing node-to-node communications.

OutgoingMessages: TConnectionOutgoingMessagesList;

Holds the outgoing messages for each connection slot, indexed by connection slot.

OutgoingMessagesLock: TConnectionCriticalSectionList;

Critical sections for synchronizing access to outgoing messages for each connection slot.

PendingTransactionsLock: TRTLCriticalSection;

Critical section for managing access to the pending transactions pool.

PendingTransactionsPool: specialize TArray<TOrderData>;

A pool of pending transactions awaiting processing.

PublicIPAddress: String = '';

The public IP address of the current node.

SlotTextLines: TConnectionStringListArray;

Holds the incoming text lines for each connection slot, indexed by connection slot.


Generated by PasDoc 0.16.0-snapshot.