]> git.mxchange.org Git - hub.git/blobdiff - application/hub/classes/package/class_NetworkPackage.php
Updated 'core' + renamed 'main' -> 'classes'.
[hub.git] / application / hub / classes / package / class_NetworkPackage.php
diff --git a/application/hub/classes/package/class_NetworkPackage.php b/application/hub/classes/package/class_NetworkPackage.php
new file mode 100644 (file)
index 0000000..4e4f384
--- /dev/null
@@ -0,0 +1,1479 @@
+<?php
+/**
+ * A NetworkPackage class. This class implements Deliverable and Receivable
+ * because all network packages should be deliverable to other nodes and
+ * receivable from other nodes. It further provides methods for reading raw
+ * content from template engines and feeding it to the stacker for undeclared
+ * packages.
+ *
+ * The factory method requires you to provide a compressor class (which must
+ * implement the Compressor interface). If you don't want any compression (not
+ * adviceable due to increased network load), please use the NullCompressor
+ * class and encode it with BASE64 for a more error-free transfer over the
+ * Internet.
+ *
+ * For performance reasons, this class should only be instanciated once and then
+ * used as a "pipe-through" class.
+ *
+ * @author             Roland Haeder <webmaster@shipsimu.org>
+ * @version            0.0.0
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Hub Developer Team
+ * @license            GNU GPL 3.0 or any newer version
+ * @link               http://www.shipsimu.org
+ * @todo               Needs to add functionality for handling the object's type
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, Registerable, Visitable {
+       /**
+        * Package mask for compressing package data:
+        * 0: Compressor extension
+        * 1: Raw package data
+        * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
+        * 3: Checksum
+        *                     0  1  2  3
+        */
+       const PACKAGE_MASK = '%s%s%s%s%s%s%s';
+
+       /**
+        * Separator for the above mask
+        */
+       const PACKAGE_MASK_SEPARATOR = '^';
+
+       /**
+        * Size of an array created by invoking
+        * explode(NetworkPackage::PACKAGE_MASK_SEPARATOR, $content).
+        */
+       const PACKAGE_CONTENT_ARRAY_SIZE = 4;
+
+       /**
+        * Separator for checksum
+        */
+       const PACKAGE_CHECKSUM_SEPARATOR = '_';
+
+       /**
+        * Array indexes for above mask, start with zero
+        */
+       const INDEX_COMPRESSOR_EXTENSION = 0;
+       const INDEX_PACKAGE_DATA         = 1;
+       const INDEX_TAGS                 = 2;
+       const INDEX_CHECKSUM             = 3;
+
+       /**
+        * Array indexes for raw package array
+        */
+       const INDEX_PACKAGE_SENDER           = 0;
+       const INDEX_PACKAGE_RECIPIENT        = 1;
+       const INDEX_PACKAGE_CONTENT          = 2;
+       const INDEX_PACKAGE_STATUS           = 3;
+       const INDEX_PACKAGE_HASH             = 4;
+       const INDEX_PACKAGE_PRIVATE_KEY_HASH = 5;
+
+       /**
+        * Size of the decoded data array
+        */
+       const DECODED_DATA_ARRAY_SIZE = 6;
+
+       /**
+        * Named array elements for decoded package content
+        */
+       const PACKAGE_CONTENT_EXTENSION        = 'compressor';
+       const PACKAGE_CONTENT_MESSAGE          = 'message';
+       const PACKAGE_CONTENT_TAGS             = 'tags';
+       const PACKAGE_CONTENT_CHECKSUM         = 'checksum';
+       const PACKAGE_CONTENT_SENDER           = 'sender';
+       const PACKAGE_CONTENT_HASH             = 'hash';
+       const PACKAGE_CONTENT_PRIVATE_KEY_HASH = 'pkhash';
+
+       /**
+        * Named array elements for package data
+        */
+       const PACKAGE_DATA_SENDER           = 'sender';
+       const PACKAGE_DATA_RECIPIENT        = 'recipient';
+       const PACKAGE_DATA_CONTENT          = 'content';
+       const PACKAGE_DATA_STATUS           = 'status';
+       const PACKAGE_DATA_HASH             = 'hash';
+       const PACKAGE_DATA_PRIVATE_KEY_HASH = 'pkhash';
+
+       /**
+        * All package status
+        */
+       const PACKAGE_STATUS_NEW     = 'new';
+       const PACKAGE_STATUS_FAILED  = 'failed';
+       const PACKAGE_STATUS_DECODED = 'decoded';
+       const PACKAGE_STATUS_FAKED   = 'faked';
+
+       /**
+        * Constants for message data array
+        */
+       const MESSAGE_ARRAY_DATA   = 'message_data';
+       const MESSAGE_ARRAY_TYPE   = 'message_type';
+       const MESSAGE_ARRAY_SENDER = 'message_sender';
+       const MESSAGE_ARRAY_HASH   = 'message_hash';
+       const MESSAGE_ARRAY_TAGS   = 'message_tags';
+
+       /**
+        * Generic answer status field
+        */
+
+       /**
+        * Tags separator
+        */
+       const PACKAGE_TAGS_SEPARATOR = ';';
+
+       /**
+        * Raw package data separator
+        */
+       const PACKAGE_DATA_SEPARATOR = '#';
+
+       /**
+        * Separator for more than one recipient
+        */
+       const PACKAGE_RECIPIENT_SEPARATOR = ':';
+
+       /**
+        * Network target (alias): 'upper nodes'
+        */
+       const NETWORK_TARGET_UPPER = 'upper';
+
+       /**
+        * Network target (alias): 'self'
+        */
+       const NETWORK_TARGET_SELF = 'self';
+
+       /**
+        * Network target (alias): 'dht'
+        */
+       const NETWORK_TARGET_DHT = 'dht';
+
+       /**
+        * TCP package size in bytes
+        */
+       const TCP_PACKAGE_SIZE = 512;
+
+       /**************************************************************************
+        *                    Stacker for out-going packages                      *
+        **************************************************************************/
+
+       /**
+        * Stacker name for "undeclared" packages
+        */
+       const STACKER_NAME_UNDECLARED = 'package_undeclared';
+
+       /**
+        * Stacker name for "declared" packages (which are ready to send out)
+        */
+       const STACKER_NAME_DECLARED = 'package_declared';
+
+       /**
+        * Stacker name for "out-going" packages
+        */
+       const STACKER_NAME_OUTGOING = 'package_outgoing';
+
+       /**************************************************************************
+        *                     Stacker for incoming packages                      *
+        **************************************************************************/
+
+       /**
+        * Stacker name for "incoming" decoded raw data
+        */
+       const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
+
+       /**
+        * Stacker name for handled decoded raw data
+        */
+       const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
+
+       /**
+        * Stacker name for "chunked" decoded raw data
+        */
+       const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
+
+       /**************************************************************************
+        *                     Stacker for incoming messages                      *
+        **************************************************************************/
+
+       /**
+        * Stacker name for new messages
+        */
+       const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
+
+       /**
+        * Stacker name for processed messages
+        */
+       const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
+
+       /**************************************************************************
+        *                      Stacker for raw data handling                     *
+        **************************************************************************/
+
+       /**
+        * Stacker for outgoing data stream
+        */
+       const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream';
+
+       /**
+        * Array index for final hash
+        */
+       const RAW_FINAL_HASH_INDEX = 'hash';
+
+       /**
+        * Array index for encoded data
+        */
+       const RAW_ENCODED_DATA_INDEX = 'data';
+
+       /**
+        * Array index for sent bytes
+        */
+       const RAW_SENT_BYTES_INDEX = 'sent';
+
+       /**
+        * Array index for socket resource
+        */
+       const RAW_SOCKET_INDEX = 'socket';
+
+       /**
+        * Array index for buffer size
+        */
+       const RAW_BUFFER_SIZE_INDEX = 'buffer';
+
+       /**
+        * Array index for diff between buffer and sent bytes
+        */
+       const RAW_DIFF_INDEX = 'diff';
+
+       /**************************************************************************
+        *                            Protocol names                              *
+        **************************************************************************/
+       const PROTOCOL_TCP = 'TCP';
+       const PROTOCOL_UDP = 'UDP';
+
+       /**
+        * Protected constructor
+        *
+        * @return      void
+        */
+       protected function __construct () {
+               // Call parent constructor
+               parent::__construct(__CLASS__);
+       }
+
+       /**
+        * Creates an instance of this class
+        *
+        * @param       $compressorInstance             A Compressor instance for compressing the content
+        * @return      $packageInstance                An instance of a Deliverable class
+        */
+       public static final function createNetworkPackage (Compressor $compressorInstance) {
+               // Get new instance
+               $packageInstance = new NetworkPackage();
+
+               // Now set the compressor instance
+               $packageInstance->setCompressorInstance($compressorInstance);
+
+               /*
+                * We need to initialize a stack here for our packages even for those
+                * which have no recipient address and stamp... ;-) This stacker will
+                * also be used for incoming raw data to handle it.
+                */
+               $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
+
+               // At last, set it in this class
+               $packageInstance->setStackInstance($stackInstance);
+
+               // Init all stacker
+               $packageInstance->initStacks();
+
+               // Get a visitor instance for speeding up things and set it
+               $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class');
+               $packageInstance->setVisitorInstance($visitorInstance);
+
+               // Get crypto instance and set it, too
+               $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
+               $packageInstance->setCryptoInstance($cryptoInstance);
+
+               // Get a singleton package assembler instance from factory and set it here, too
+               $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
+               $packageInstance->setAssemblerInstance($assemblerInstance);
+
+               // Get node instance
+               $nodeInstance = NodeObjectFactory::createNodeInstance();
+
+               // Get pool instance from node
+               $poolInstance = $nodeInstance->getListenerPoolInstance();
+
+               // And set it here
+               $packageInstance->setListenerPoolInstance($poolInstance);
+
+               // Return the prepared instance
+               return $packageInstance;
+       }
+
+       /**
+        * Initialize all stackers
+        *
+        * @param       $forceReInit    Whether to force reinitialization of all stacks
+        * @return      void
+        */
+       protected function initStacks ($forceReInit = FALSE) {
+               // Initialize all
+               $this->getStackInstance()->initStacks(array(
+                       self::STACKER_NAME_UNDECLARED,
+                       self::STACKER_NAME_DECLARED,
+                       self::STACKER_NAME_OUTGOING,
+                       self::STACKER_NAME_DECODED_INCOMING,
+                       self::STACKER_NAME_DECODED_HANDLED,
+                       self::STACKER_NAME_DECODED_CHUNKED,
+                       self::STACKER_NAME_NEW_MESSAGE,
+                       self::STACKER_NAME_PROCESSED_MESSAGE,
+                       self::STACKER_NAME_OUTGOING_STREAM
+               ), $forceReInit);
+       }
+
+       /**
+        * Determines private key hash from given session id
+        *
+        * @param       $decodedData    Array with decoded data
+        * @return      $hash                   Private key's hash
+        */
+       private function determineSenderPrivateKeyHash (array $decodedData) {
+               // Get DHT instance
+               $dhtInstance = DhtObjectFactory::createDhtInstance('node');
+
+               // Ask DHT for session id
+               $senderData = $dhtInstance->findNodeLocalBySessionId($decodedData[self::PACKAGE_CONTENT_SENDER]);
+
+               // Is an entry found?
+               if (count($senderData) > 0) {
+                       // Make sure the element 'private_key_hash' is there
+                       //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderData=' . print_r($senderData, TRUE));
+                       assert(isset($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH]));
+
+                       // Return it
+                       return $senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH];
+               } // END - if
+
+               // Make sure the requested element is there
+               //* DEBUG-DIE */ die('decodedData=' . print_r($decodedData, TRUE));
+               assert(isset($decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH]));
+
+               // There is no DHT entry so, accept the hash from decoded data
+               return $decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH];
+       }
+
+       /**
+        * "Getter" for hash from given content
+        *
+        * @param       $content        Raw package content
+        * @return      $hash           Hash for given package content
+        */
+       private function getHashFromContent ($content) {
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
+
+               // Create the hash
+               // @TODO md5() is very weak, but it needs to be fast
+               $hash = md5(
+                       $content .
+                       self::PACKAGE_CHECKSUM_SEPARATOR .
+                       $this->getSessionId() .
+                       self::PACKAGE_CHECKSUM_SEPARATOR .
+                       $this->getCompressorInstance()->getCompressorExtension()
+               );
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
+
+               // And return it
+               return $hash;
+       }
+
+       /**
+        * Checks whether the checksum (sometimes called "hash") is the same
+        *
+        * @param       $decodedContent         Package raw content
+        * @param       $decodedData            Whole raw package data array
+        * @return      $isChecksumValid        Whether the checksum is the same
+        */
+       private function isChecksumValid (array $decodedContent, array $decodedData) {
+               // Get checksum
+               $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
+
+               // Is it the same?
+               $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
+
+               // Return it
+               return $isChecksumValid;
+       }
+
+       /**
+        * Change the package with given status in given stack
+        *
+        * @param       $packageData    Raw package data in an array
+        * @param       $stackerName    Name of the stacker
+        * @param       $newStatus              New status to set
+        * @return      void
+        */
+       private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
+               // Skip this for empty stacks
+               if ($this->getStackInstance()->isStackEmpty($stackerName)) {
+                       // This avoids an exception after all packages has failed
+                       return;
+               } // END - if
+
+               // Pop the entry (it should be it)
+               $nextData = $this->getStackInstance()->popNamed($stackerName);
+
+               // Compare both hashes
+               assert($nextData[self::PACKAGE_DATA_HASH] == $packageData[self::PACKAGE_DATA_HASH]);
+
+               // Temporary set the new status
+               $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
+
+               // And push it again
+               $this->getStackInstance()->pushNamed($stackerName, $packageData);
+       }
+
+       /**
+        * "Getter" for hash from given content and sender's session id
+        *
+        * @param       $decodedContent         Raw package content
+        * @param       $sessionId                      Session id of the sender
+        * @return      $hash                           Hash for given package content
+        */
+       public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
+
+               // Create the hash
+               // @TODO md5() is very weak, but it needs to be fast
+               $hash = md5(
+                       $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
+                       self::PACKAGE_CHECKSUM_SEPARATOR .
+                       $sessionId .
+                       self::PACKAGE_CHECKSUM_SEPARATOR .
+                       $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
+               );
+
+               // And return it
+               return $hash;
+       }
+
+       ///////////////////////////////////////////////////////////////////////////
+       //                   Delivering packages / raw data
+       ///////////////////////////////////////////////////////////////////////////
+
+       /**
+        * Declares the given raw package data by discovering recipients
+        *
+        * @param       $packageData    Raw package data in an array
+        * @return      void
+        */
+       private function declareRawPackageData (array $packageData) {
+               // Make sure the required field is there
+               assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
+
+               /*
+                * We need to disover every recipient, just in case we have a
+                * multi-recipient entry like 'upper' is. 'all' may be a not so good
+                * target because it causes an overload on the network and may be
+                * abused for attacking the network with large packages.
+                */
+               $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
+
+               // Discover all recipients, this may throw an exception
+               $discoveryInstance->discoverRecipients($packageData);
+
+               // Now get an iterator
+               $iteratorInstance = $discoveryInstance->getIterator();
+
+               // Make sure the iterator instance is valid
+               assert($iteratorInstance instanceof Iterator);
+
+               // Rewind back to the beginning
+               $iteratorInstance->rewind();
+
+               // ... and begin iteration
+               while ($iteratorInstance->valid()) {
+                       // Get current entry
+                       $currentRecipient = $iteratorInstance->current();
+
+                       // Debug message
+                       /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
+
+                       // Set the recipient
+                       $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
+
+                       // Push the declared package to the next stack.
+                       $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
+
+                       // Debug message
+                       /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
+
+                       // Skip to next entry
+                       $iteratorInstance->next();
+               } // END - while
+
+               /*
+                * The recipient list can be cleaned up here because the package which
+                * shall be delivered has already been added for all entries from the
+                * list.
+                */
+               $discoveryInstance->clearRecipients();
+       }
+
+       /**
+        * Delivers raw package data. In short, this will discover the raw socket
+        * resource through a discovery class (which will analyse the receipient of
+        * the package), register the socket with the connection (handler/helper?)
+        * instance and finally push the raw data on our outgoing queue.
+        *
+        * @param       $packageData    Raw package data in an array
+        * @return      void
+        */
+       private function deliverRawPackageData (array $packageData) {
+               /*
+                * This package may become big, depending on the shared object size or
+                * delivered message size which shouldn't be so long (to save
+                * bandwidth). Because of the nature of the used protocol (TCP) we need
+                * to split it up into smaller pieces to fit it into a TCP frame.
+                *
+                * So first we need (again) a discovery class but now a protocol
+                * discovery to choose the right socket resource. The discovery class
+                * should take a look at the raw package data itself and then decide
+                * which (configurable!) protocol should be used for that type of
+                * package.
+                */
+               $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
+
+               // Now discover the right protocol
+               $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
+
+               // The socket needs to be put in a special registry that can handle such data
+               $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
+
+               // Get the connection helper from registry
+               $helperInstance = Registry::getRegistry()->getInstance('connection');
+
+               // And make sure it is valid
+               assert($helperInstance instanceof ConnectionHelper);
+
+               // Get connection info class
+               $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($helperInstance->getProtocolName(), 'helper');
+
+               // Will the info instance with connection helper data
+               $infoInstance->fillWithConnectionHelperInformation($helperInstance);
+
+               // Is it not there?
+               if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($infoInstance, $socketResource))) {
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
+
+                       // Then register it
+                       $registryInstance->registerSocket($infoInstance, $socketResource, $packageData);
+               } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
+                       // Is not connected, then we cannot send
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
+
+                       // Shutdown the socket
+                       $this->shutdownSocket($socketResource);
+               }
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
+
+               // Make sure the connection is up
+               $helperInstance->getStateInstance()->validatePeerStateConnected();
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
+
+               // Enqueue it again on the out-going queue, the connection is up and working at this point
+               $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
+       }
+
+       /**
+        * Sends waiting packages
+        *
+        * @param       $packageData    Raw package data
+        * @return      void
+        */
+       private function sendOutgoingRawPackageData (array $packageData) {
+               // Init sent bytes
+               $sentBytes = 0;
+
+               // Get the right connection instance
+               $infoInstance = SocketRegistryFactory::createSocketRegistryInstance()->getInfoInstanceFromPackageData($packageData);
+
+               // Test helper instance
+               assert($infoInstance instanceof ShareableInfo);
+
+               // Get helper instance
+               $helperInstance = $infoInstance->getHelperInstance();
+
+               // Some sanity-checks on the object
+               //* DEBUG-DIE: */ die('[' . __METHOD__ . ':' . __LINE__ . ']: p1=' . $infoInstance->getProtocolName() . ',p2=' . $helperInstance->getProtocolName() . ',infoInstance=' . print_r($infoInstance, TRUE));
+               assert($helperInstance instanceof ConnectionHelper);
+               assert($infoInstance->getProtocolName() == $helperInstance->getProtocolName());
+
+               // Is this connection still alive?
+               if ($helperInstance->isShuttedDown()) {
+                       // This connection is shutting down
+                       // @TODO We may want to do somthing more here?
+                       return;
+               } // END - if
+
+               // Sent out package data
+               $helperInstance->sendRawPackageData($packageData);
+       }
+
+       /**
+        * Generates a secure hash for given raw package content and sender id
+        *
+        * @param       $content        Raw package data
+        * @param       $senderId       Sender id to generate a hash for
+        * @return      $hash           Hash as hex-encoded string
+        */
+       private function generatePackageHash ($content, $senderId) {
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content()=' . strlen($content) . ',senderId=' . $senderId . ' - CALLED!');
+
+               // Is the feature enabled?
+               if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
+                       // Feature is not enabled
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Feature "hubcoin_reward" not available, not generating package hash. Returning NULL ...');
+                       return NULL;
+               } // END - if
+
+               // Fake array
+               $data = array(
+                       self::PACKAGE_CONTENT_SENDER           => $senderId,
+                       self::PACKAGE_CONTENT_MESSAGE          => $content,
+                       self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => ''
+               );
+       
+               // Hash content and sender id together, use scrypt
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $senderId . ',content()=' . strlen($content));
+               $hash = FrameworkFeature::callFeature('hubcoin_reward', 'generateHash', array($senderId . ':' . $content . ':' . $this->determineSenderPrivateKeyHash($data)));
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash . ' - EXIT!');
+
+               // Return it
+               return $hash;
+       }
+
+       /**
+        * Checks whether the hash of given package data is 'valid', here that
+        * means it is the same or not.
+        *
+        * @param       $decodedArray           An array with 'decoded' (explode() was mostly called) data
+        * @return      $isHashValid    Whether the hash is valid
+        * @todo        Unfinished area, hashes are currently NOT fully supported
+        */
+       private function isPackageHashValid (array $decodedArray) {
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedArray=' . print_r($decodedArray, TRUE) . ' - CALLED!');
+
+               // Make sure the required array elements are there
+               assert(isset($decodedArray[self::PACKAGE_CONTENT_SENDER]));
+               assert(isset($decodedArray[self::PACKAGE_CONTENT_MESSAGE]));
+               assert(isset($decodedArray[self::PACKAGE_CONTENT_HASH]));
+
+               // Is the feature enabled?
+               if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
+                       // Feature is not enabled, so hashes are always valid
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Feature "hubcoin_reward" not available, not checking hash. Returning TRUE ...');
+                       return TRUE;
+               } // END - if
+
+               // Check validity
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $decodedArray[self::PACKAGE_CONTENT_SENDER] . ',message()=' . strlen($decodedArray[self::PACKAGE_CONTENT_MESSAGE]) . '),hash=' . $decodedArray[self::PACKAGE_CONTENT_HASH]);
+               //* DEBUG-DIE: */ die(__METHOD__ . ': decodedArray=' . print_r($decodedArray, TRUE));
+               $isHashValid = FrameworkFeature::callFeature('hubcoin_reward', 'checkHash', array($decodedArray[self::PACKAGE_CONTENT_SENDER] . ':' . $decodedArray[self::PACKAGE_CONTENT_MESSAGE] . ':' . $this->determineSenderPrivateKeyHash($decodedArray), $decodedArray[self::PACKAGE_CONTENT_HASH]));
+
+               // Return it
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: isHashValid=' . intval($isHashValid) . ' - EXIT!');
+               return $isHashValid;
+       }
+
+       /**
+        * "Enqueues" raw content into this delivery class by reading the raw content
+        * from given helper's template instance and pushing it on the 'undeclared'
+        * stack.
+        *
+        * @param       $helperInstance         An instance of a HubHelper class
+        * @return      void
+        */
+       public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
+
+               // Get the raw content ...
+               $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
+
+               // ... and compress it
+               $compressed = $this->getCompressorInstance()->compressStream($content);
+
+               // Add magic in front of it and hash behind it, including BASE64 encoding
+               $packageContent = sprintf(self::PACKAGE_MASK,
+                       // 1.) Compressor's extension
+                       $this->getCompressorInstance()->getCompressorExtension(),
+                       // - separator
+                       self::PACKAGE_MASK_SEPARATOR,
+                       // 2.) Compressed raw package content, encoded with BASE64
+                       base64_encode($compressed),
+                       // - separator
+                       self::PACKAGE_MASK_SEPARATOR,
+                       // 3.) Tags
+                       implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
+                       // - separator
+                       self::PACKAGE_MASK_SEPARATOR,
+                       // 4.) Checksum
+                       $this->getHashFromContent($compressed)
+               );
+
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...');
+
+               // Now prepare the temporary array and push it on the 'undeclared' stack
+               $this->getStackInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
+                       self::PACKAGE_DATA_SENDER           => $this->getSessionId(),
+                       self::PACKAGE_DATA_RECIPIENT        => $helperInstance->getRecipientType(),
+                       self::PACKAGE_DATA_CONTENT          => $packageContent,
+                       self::PACKAGE_DATA_STATUS           => self::PACKAGE_STATUS_NEW,
+                       self::PACKAGE_DATA_HASH             => $this->generatePackageHash($content, $this->getSessionId()),
+                       self::PACKAGE_DATA_PRIVATE_KEY_HASH => $this->getPrivateKeyHash(),
+               ));
+
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
+       }
+
+       /**
+        * Checks whether a package has been enqueued for delivery.
+        *
+        * @return      $isEnqueued             Whether a package is enqueued
+        */
+       public function isPackageEnqueued () {
+               // Check whether the stacker is not empty
+               $isEnqueued = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
+
+               // Return the result
+               return $isEnqueued;
+       }
+
+       /**
+        * Checks whether a package has been declared
+        *
+        * @return      $isDeclared             Whether a package is declared
+        */
+       public function isPackageDeclared () {
+               // Check whether the stacker is not empty
+               $isDeclared = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
+
+               // Return the result
+               return $isDeclared;
+       }
+
+       /**
+        * Checks whether a package should be sent out
+        *
+        * @return      $isWaitingDelivery      Whether a package is waiting for delivery
+        */
+       public function isPackageWaitingForDelivery () {
+               // Check whether the stacker is not empty
+               $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
+
+               // Return the result
+               return $isWaitingDelivery;
+       }
+
+       /**
+        * Checks whether encoded (raw) data is pending
+        *
+        * @return      $isPending              Whether encoded data is pending
+        */
+       public function isEncodedDataPending () {
+               // Check whether the stacker is not empty
+               $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM)));
+
+               // Return the result
+               return $isPending;
+       }
+
+       /**
+        * Delivers an enqueued package to the stated destination. If a non-session
+        * id is provided, recipient resolver is being asked (and instanced once).
+        * This allows that a single package is being delivered to multiple targets
+        * without enqueueing it for every target. If no target is provided or it
+        * can't be determined a NoTargetException is being thrown.
+        *
+        * @return      void
+        * @throws      NoTargetException       If no target can't be determined
+        */
+       public function declareEnqueuedPackage () {
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
+
+               // Make sure this method isn't working if there is no package enqueued
+               if (!$this->isPackageEnqueued()) {
+                       // This is not fatal but should be avoided
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!');
+                       return;
+               } // END - if
+
+               /*
+                * Now there are for sure packages to deliver, so start with the first
+                * one.
+                */
+               $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
+
+               // Declare the raw package data for delivery
+               $this->declareRawPackageData($packageData);
+
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
+       }
+
+       /**
+        * Delivers the next declared package. Only one package per time will be sent
+        * because this may take time and slows down the whole delivery
+        * infrastructure.
+        *
+        * @return      void
+        */
+       public function processDeclaredPackage () {
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
+
+               // Sanity check if we have packages declared
+               if (!$this->isPackageDeclared()) {
+                       // This is not fatal but should be avoided
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
+                       return;
+               } // END - if
+
+               // Get the package
+               $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
+
+               // Assert on it
+               assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
+
+               // Try to deliver the package
+               try {
+                       // And try to send it
+                       $this->deliverRawPackageData($packageData);
+
+                       // And remove it finally
+                       $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
+               } catch (UnexpectedStateException $e) {
+                       // The state is not excepected (shall be 'connected')
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
+
+                       // Mark the package with status failed
+                       $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
+               }
+
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
+       }
+
+       /**
+        * Sends waiting packages out for delivery
+        *
+        * @return      void
+        */
+       public function sendWaitingPackage () {
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
+
+               // Sanity check if we have packages waiting for delivery
+               if (!$this->isPackageWaitingForDelivery()) {
+                       // This is not fatal but should be avoided
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
+                       return;
+               } // END - if
+
+               // Get the package
+               $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING);
+
+               try {
+                       // Now try to send it
+                       $this->sendOutgoingRawPackageData($packageData);
+
+                       // And remove it finally
+                       $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING);
+               } catch (InvalidSocketException $e) {
+                       // Output exception message
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
+
+                       // Mark package as failed
+                       $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
+               }
+
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
+       }
+
+       /**
+        * Sends out encoded data to a socket
+        *
+        * @return      void
+        */
+       public function sendEncodedData () {
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
+
+               // Make sure there is pending encoded data
+               assert($this->isEncodedDataPending());
+
+               // Pop current data from stack
+               $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM);
+
+               // Init in this round sent bytes
+               $sentBytes = 0;
+
+               // Assert on socket
+               assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX]));
+
+               // And deliver it
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sending out ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes,rawBufferSize=' . $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] . ',diff=' . $encodedDataArray[self::RAW_DIFF_INDEX]);
+               if ($encodedDataArray[self::RAW_DIFF_INDEX] >= 0) {
+                       // Send all out (encodedData is smaller than or equal buffer size)
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], 0, ($encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - $encodedDataArray[self::RAW_DIFF_INDEX]))));
+                       $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], ($encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - $encodedDataArray[self::RAW_DIFF_INDEX]));
+               } else {
+                       // Send buffer size out
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], 0, $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX])));
+                       $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]);
+               }
+
+               // If there was an error, we don't continue here
+               if ($sentBytes === FALSE) {
+                       // Handle the error with a faked recipientData array
+                       $this->handleSocketError(__METHOD__, __LINE__, $encodedDataArray[self::RAW_SOCKET_INDEX], array('0.0.0.0', '0'));
+
+                       // And throw it
+                       throw new InvalidSocketException(array($this, $encodedDataArray[self::RAW_SOCKET_INDEX], $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+               } elseif (($sentBytes === 0) && (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) > 0)) {
+                       // Nothing sent means we are done
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
+                       return;
+               } else {
+                       // The difference between sent bytes and length of raw data should not go below zero
+                       assert((strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) - $sentBytes) >= 0);
+
+                       // Add total sent bytes
+                       $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes;
+
+                       // Cut out the last unsent bytes
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes ...');
+                       $encodedDataArray[self::RAW_ENCODED_DATA_INDEX] = substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $sentBytes);
+
+                       // Calculate difference again
+                       $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]);
+
+                       // Can we abort?
+                       if (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) <= 0) {
+                               // Abort here, all sent!
+                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
+                               return;
+                       } // END - if
+               }
+
+               // Push array back in stack
+               $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
+
+               // Debug message
+               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
+       }
+
+       ///////////////////////////////////////////////////////////////////////////
+       //                   Receiving packages / raw data
+       ///////////////////////////////////////////////////////////////////////////
+
+       /**
+        * Checks whether decoded raw data is pending
+        *
+        * @return      $isPending      Whether decoded raw data is pending
+        */
+       private function isRawDataPending () {
+               // Just return whether the stack is not empty
+               $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
+
+               // Return the status
+               return $isPending;
+       }
+
+       /**
+        * Checks whether new raw package data has arrived at a socket
+        *
+        * @return      $hasArrived             Whether new raw package data has arrived for processing
+        */
+       public function isNewRawDataPending () {
+               // Visit the pool. This monitors the pool for incoming raw data.
+               $this->getListenerPoolInstance()->accept($this->getVisitorInstance());
+
+               // Check for new data arrival
+               $hasArrived = $this->isRawDataPending();
+
+               // Return the status
+               return $hasArrived;
+       }
+
+       /**
+        * Handles the incoming decoded raw data. This method does not "convert" the
+        * decoded data back into a package array, it just "handles" it and pushs it
+        * on the next stack.
+        *
+        * @return      void
+        */
+       public function handleIncomingDecodedData () {
+               /*
+                * This method should only be called if decoded raw data is pending,
+                * so check it again.
+                */
+               if (!$this->isRawDataPending()) {
+                       // This is not fatal but should be avoided
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!');
+                       return;
+               } // END - if
+
+               // Very noisy debug message:
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
+
+               // "Pop" the next entry (the same array again) from the stack
+               $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
+
+               // Make sure both array elements are there
+               assert(
+                       (is_array($decodedData)) &&
+                       (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
+                       (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
+               );
+
+               /*
+                * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
+                * only want to handle unhandled packages here.
+                */
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
+               assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
+
+               // Remove the last chunk SEPARATOR (because there is no need for it)
+               if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
+                       // It is there and should be removed
+                       $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
+               } // END - if
+
+               // This package is "handled" and can be pushed on the next stack
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Pushing ' . strlen($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes to stack ' . self::STACKER_NAME_DECODED_HANDLED . ' ...');
+               $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
+       }
+
+       /**
+        * Adds raw decoded data from the given handler instance to this receiver
+        *
+        * @param       $handlerInstance        An instance of a Networkable class
+        * @return      void
+        */
+       public function addRawDataToIncomingStack (Networkable $handlerInstance) {
+               /*
+                * Get the decoded data from the handler, this is an array with
+                * 'raw_data' and 'error_code' as elements.
+                */
+               $decodedData = $handlerInstance->getNextRawData();
+
+               // Very noisy debug message:
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
+
+               // And push it on our stack
+               $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
+       }
+
+       /**
+        * Checks whether incoming decoded data is handled.
+        *
+        * @return      $isHandled      Whether incoming decoded data is handled
+        */
+       public function isIncomingRawDataHandled () {
+               // Determine if the stack is not empty
+               $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
+
+               // Return it
+               return $isHandled;
+       }
+
+       /**
+        * Checks whether the assembler has pending data left
+        *
+        * @return      $isHandled      Whether the assembler has pending data left
+        */
+       public function ifAssemblerHasPendingDataLeft () {
+               // Determine if the stack is not empty
+               $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
+
+               // Return it
+               return $isHandled;
+       }
+
+       /**
+        * Checks whether the assembler has multiple packages pending
+        *
+        * @return      $isPending      Whether the assembler has multiple packages pending
+        */
+       public function ifMultipleMessagesPending () {
+               // Determine if the stack is not empty
+               $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
+
+               // Return it
+               return $isPending;
+       }
+
+       /**
+        * Handles the attached assemler's pending data queue to be finally
+        * assembled to the raw package data back.
+        *
+        * @return      void
+        */
+       public function handleAssemblerPendingData () {
+               // Handle it
+               $this->getAssemblerInstance()->handlePendingData();
+       }
+
+       /**
+        * Handles multiple messages.
+        *
+        * @return      void
+        */
+       public function handleMultipleMessages () {
+               // Handle it
+               $this->getAssemblerInstance()->handleMultipleMessages();
+       }
+
+       /**
+        * Assembles incoming decoded data so it will become an abstract network
+        * package again. The assembler does later do it's job by an other task,
+        * not this one to keep best speed possible.
+        *
+        * @return      void
+        */
+       public function assembleDecodedDataToPackage () {
+               // Make sure the raw decoded package data is handled
+               assert($this->isIncomingRawDataHandled());
+
+               // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
+               $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
+
+               // Assert on some elements
+               assert(
+                       (is_array($packageContent)) &&
+                       (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
+                       (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
+               );
+
+               // Start assembling the raw package data array by chunking it
+               $this->getAssemblerInstance()->chunkPackageContent($packageContent);
+
+               // Remove the package from 'handled_decoded' stack ...
+               $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
+
+               // ... and push it on the 'chunked' stacker
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Pushing ' . strlen($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes on stack ' . self::STACKER_NAME_DECODED_CHUNKED . ',packageContent=' . print_r($packageContent, TRUE));
+               $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
+       }
+
+       /**
+        * Accepts the visitor to process the visit "request"
+        *
+        * @param       $visitorInstance        An instance of a Visitor class
+        * @return      void
+        */
+       public function accept (Visitor $visitorInstance) {
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
+
+               // Visit the package
+               $visitorInstance->visitNetworkPackage($this);
+
+               // Then visit the assembler to handle multiple packages
+               $this->getAssemblerInstance()->accept($visitorInstance);
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
+       }
+
+       /**
+        * Clears all stacks
+        *
+        * @return      void
+        */
+       public function clearAllStacks () {
+               // Call the init method to force re-initialization
+               $this->initStacks(TRUE);
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
+       }
+
+       /**
+        * Removes the first failed outoging package from the stack to continue
+        * with next one (it will never work until the issue is fixed by you).
+        *
+        * @return      void
+        * @throws      UnexpectedPackageStatusException        If the package status is not 'failed'
+        * @todo        This may be enchanced for outgoing packages?
+        */
+       public function removeFirstFailedPackage () {
+               // Get the package again
+               $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
+
+               // Is the package status 'failed'?
+               if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
+                       // Not failed!
+                       throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
+               } // END - if
+
+               // Remove this entry
+               $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
+       }
+
+       /**
+        * "Decode" the package content into the same array when it was sent.
+        *
+        * @param       $rawPackageContent      The raw package content to be "decoded"
+        * @return      $decodedData            An array with 'sender', 'recipient', 'content' and 'status' elements
+        */
+       public function decodeRawContent ($rawPackageContent) {
+               // Use the separator '#' to "decode" it
+               $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
+
+               // Assert on count (should be always 3)
+               assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
+
+               /*
+                * Create 'decodedData' array with all assoziative array elements.
+                */
+               $decodedData = array(
+                       self::PACKAGE_DATA_SENDER           => $decodedArray[self::INDEX_PACKAGE_SENDER],
+                       self::PACKAGE_DATA_RECIPIENT        => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
+                       self::PACKAGE_DATA_CONTENT          => $decodedArray[self::INDEX_PACKAGE_CONTENT],
+                       self::PACKAGE_DATA_STATUS           => self::PACKAGE_STATUS_DECODED,
+                       self::PACKAGE_DATA_HASH             => $decodedArray[self::INDEX_PACKAGE_HASH],
+                       self::PACKAGE_DATA_PRIVATE_KEY_HASH => $decodedArray[self::INDEX_PACKAGE_PRIVATE_KEY_HASH]
+               );
+
+               // And return it
+               return $decodedData;
+       }
+
+       /**
+        * Handles decoded data for this node by "decoding" the 'content' part of
+        * it. Again this method uses explode() for the "decoding" process.
+        *
+        * @param       $decodedData    An array with decoded raw package data
+        * @return      void
+        * @throws      InvalidDataChecksumException    If the checksum doesn't match
+        */
+       public function handleRawData (array $decodedData) {
+               /*
+                * "Decode" the package's content by a simple explode() call, for
+                * details of the array elements, see comments for constant
+                * PACKAGE_MASK.
+                */
+               $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
+
+               // Assert on array count for a very basic validation
+               assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
+
+               /*
+                * Convert the indexed array into an associative array. This is much
+                * better to remember than plain numbers, isn't it?
+                */
+               $decodedContent = array(
+                       // Compressor's extension used to compress the data
+                       self::PACKAGE_CONTENT_EXTENSION        => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
+                       // Package data (aka "message") in BASE64-decoded form but still compressed
+                       self::PACKAGE_CONTENT_MESSAGE          => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
+                       // Tags as an indexed array for "tagging" the message
+                       self::PACKAGE_CONTENT_TAGS             => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
+                       // Checksum of the _decoded_ data
+                       self::PACKAGE_CONTENT_CHECKSUM         => $decodedContent[self::INDEX_CHECKSUM],
+                       // Sender's id
+                       self::PACKAGE_CONTENT_SENDER           => $decodedData[self::PACKAGE_DATA_SENDER],
+                       // Hash from decoded raw data
+                       self::PACKAGE_CONTENT_HASH             => $decodedData[self::PACKAGE_DATA_HASH],
+                       // Hash of private key
+                       self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => $decodedData[self::PACKAGE_DATA_PRIVATE_KEY_HASH]
+               );
+
+               // Is the checksum valid?
+               if (!$this->isChecksumValid($decodedContent, $decodedData)) {
+                       // Is not the same, so throw an exception here
+                       throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
+               } // END - if
+
+               /*
+                * The checksum is the same, then it can be decompressed safely. The
+                * original message is at this point fully decoded.
+                */
+               $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
+
+               // And push it on the next stack
+               $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
+       }
+
+       /**
+        * Checks whether a new message has arrived
+        *
+        * @return      $hasArrived             Whether a new message has arrived for processing
+        */
+       public function isNewMessageArrived () {
+               // Determine if the stack is not empty
+               $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
+
+               // Return it
+               return $hasArrived;
+       }
+
+       /**
+        * Handles newly arrived messages
+        *
+        * @return      void
+        * @todo        Implement verification of all sent tags here?
+        */
+       public function handleNewlyArrivedMessage () {
+               // Make sure there is at least one message
+               assert($this->isNewMessageArrived());
+
+               // Get it from the stacker, it is the full array with the decoded message
+               $decodedContent = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
+
+               // Generate the hash of comparing it
+               if (!$this->isPackageHashValid($decodedContent)) {
+                       // Is not valid, so throw an exception here
+                       exit(__METHOD__ . ':INVALID HASH! UNDER CONSTRUCTION!' . chr(10));
+               } // END - if
+
+               // Now get a filter chain back from factory with given tags array
+               $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
+
+               /*
+                * Process the message through all filters, note that all other
+                * elements from $decodedContent are no longer needed.
+                */
+               $chainInstance->processMessage($decodedContent, $this);
+
+               /*
+                * Post-processing of message data (this won't remote the message from
+                * the stack).
+                */
+               $chainInstance->postProcessMessage($this);
+       }
+
+       /**
+        * Checks whether a processed message is pending for "interpretation"
+        *
+        * @return      $isPending      Whether a processed message is pending
+        */
+       public function isProcessedMessagePending () {
+               // Check it
+               $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
+
+               // Return it
+               return $isPending;
+       }
+
+       /**
+        * Handle processed messages by "interpreting" the 'message_type' element
+        *
+        * @return      void
+        */
+       public function handleProcessedMessage () {
+               // Get it from the stacker, it is the full array with the processed message
+               $messageArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
+
+               // Add type for later easier handling
+               $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
+
+               // Create a handler instance from given message type
+               $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
+
+               // Handle message data
+               $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
+
+               // Post-handling of message data
+               $handlerInstance->postHandleMessageData($messageArray, $this);
+       }
+
+       /**
+        * Feeds the hash and sender (as recipient for the 'sender' reward) to the
+        * miner's queue, unless the message is not a "reward claim" message as this
+        * leads to an endless loop. You may wish to run the miner to get some
+        * reward ("Hubcoins") for "mining" this hash.
+        *
+        * @param       $messageData    Array with message data
+        * @return      void
+        * @todo        ~10% done?
+        */
+       public function feedHashToMiner (array $messageData) {
+               // Is the feature enabled?
+               if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
+                       /*
+                        * Feature is not enabled, don't feed the hash to the miner as it
+                        *may be invalid.
+                        */
+                       return;
+               } // END - if
+
+               // Make sure the required elements are there
+               assert(isset($messageData[self::MESSAGE_ARRAY_SENDER]));
+               assert(isset($messageData[self::MESSAGE_ARRAY_HASH]));
+               assert(isset($messageData[self::MESSAGE_ARRAY_TAGS]));
+
+               // Debug message
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageData=' . print_r($messageData, TRUE));
+
+               // Resolve session id ('sender' is a session id) into node id
+               $nodeId = HubTools::resolveNodeIdBySessionId($messageData[self::MESSAGE_ARRAY_SENDER]);
+
+               // Is 'claim_reward' the message type?
+               if (in_array('claim_reward', $messageData[self::MESSAGE_ARRAY_TAGS])) {
+                       /*
+                        * Then don't feed this message to the miner as this causes an
+                        * endless loop of mining.
+                        */
+                       return;
+               } // END - if
+
+               $this->partialStub('@TODO nodeId=' . $nodeId . ',messageData=' . print_r($messageData, TRUE));
+       }
+}
+
+// [EOF]
+?>