*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 Hub Developer Team
+ * @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
const INDEX_PACKAGE_RECIPIENT = 1;
const INDEX_PACKAGE_CONTENT = 2;
const INDEX_PACKAGE_STATUS = 3;
- const INDEX_PACKAGE_SIGNATURE = 4;
+ const INDEX_PACKAGE_HASH = 4;
/**
- * Size of the decoded data array ('status' is not included)
+ * Size of the decoded data array
*/
- const DECODED_DATA_ARRAY_SIZE = 4;
+ const DECODED_DATA_ARRAY_SIZE = 5;
/**
* Named array elements for decoded package content
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';
/**
* Named array elements for package data
*/
const PACKAGE_DATA_SENDER = 'sender';
const PACKAGE_DATA_RECIPIENT = 'recipient';
- const PACKAGE_DATA_PROTOCOL = 'protocol';
const PACKAGE_DATA_CONTENT = 'content';
const PACKAGE_DATA_STATUS = 'status';
- const PACKAGE_DATA_SIGNATURE = 'signature';
+ const PACKAGE_DATA_HASH = 'hash';
/**
* All package status
$packageInstance->initStacks();
// Get a visitor instance for speeding up things and set it
- $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
+ $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class');
$packageInstance->setVisitorInstance($visitorInstance);
// Get crypto instance and set it, 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;
}
), $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::]);
+
+ // 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
+ assert(isset($decodedData[self::INDEX_PACKAGE_HASH]));
+
+ // There is no DHT entry so, accept the hash from decoded data
+ return $decodedData[self::INDEX_PACKAGE_HASH];
+ }
+
/**
* "Getter" for hash from given content
*
// Pop the entry (it should be it)
$nextData = $this->getStackInstance()->popNamed($stackerName);
- // Compare both signatures
- assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
+ // 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;
// 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();
$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]);
+ /* 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;
$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);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
// Skip to next entry
$iteratorInstance->next();
// 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($helperInstance, $socketResource))) {
+ 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($helperInstance, $socketResource, $packageData);
+ $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.');
$sentBytes = 0;
// Get the right connection instance
- $helperInstance = SocketRegistryFactory::createSocketRegistryInstance()->getHandlerInstanceFromPackageData($packageData);
+ $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()) {
}
/**
- * Generates a signature for given raw package content and sender id
+ * Generates a secure hash for given raw package content and sender id
*
* @param $content Raw package data
- * @param $senderId Sender id to generate a signature for
- * @return $signature Signature as BASE64-encoded string
- */
- private function generatePackageSignature ($content, $senderId) {
- // Hash content and sender id together, use md5() as last algo
- $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getPrivateKey(), FALSE));
-
- // Encrypt the content again with the hash as a key
- $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
-
- // Encode it with BASE64
- $signature = base64_encode($encryptedContent);
+ * @param $senderId Sender id to generate a hash for
+ * @return $hash Hash as hex-encoded string
+ */
+ private function generatePackageHash ($content, $senderId) {
+ // Fake array
+ $data = array(
+ self::INDEX_PACKAGE_SENDER => $senderId,
+ self::INDEX_PACKAGE_CONTENT => $content,
+ self::INDEX_PACKAGE_HASH => ''
+ );
+
+ // Hash content and sender id together, use scrypt
+ $hash = Scrypt::hashScrypt($senderId . ':' . $content . ':' . $this->determineSenderPrivateKeyHash($data));
// Return it
- return $signature;
+ return $hash;
}
/**
- * Checks whether the signature of given package data is 'valid', here that
+ * 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 $isSignatureValid Whether the signature is valid
- * @todo Unfinished area, signatures are currently NOT fully supported
+ * @return $isHashValid Whether the hash is valid
+ * @todo Unfinished area, hashes are currently NOT fully supported
*/
- private function isPackageSignatureValid (array $decodedArray) {
- // Generate the signature of comparing it
- $signature = $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER]);
+ private function isPackageHashValid (array $decodedArray) {
+ // Check validity
+ $isHashValid = Scrypt::checkScrypt($decodedArray[self::INDEX_PACKAGE_SENDER] . ':' . $decodedArray[self::INDEX_PACKAGE_CONTENT] . ':' . $this->determineSenderPrivateKeyHash($decodedArray);
- // Is it the same?
- //$isSignatureValid =
- exit(__METHOD__.': signature='.$signature.chr(10).',decodedArray='.print_r($decodedArray, TRUE));
+ // Return it
+ //* DEBUG-DIE: */ die(__METHOD__ . ': isHashValid=' . intval($isHashValid) . chr(10) . ',decodedArray=' . print_r($decodedArray, TRUE));
+ return $isHashValid;
}
/**
* from given helper's template instance and pushing it on the 'undeclared'
* stack.
*
- * @param $helperInstance An instance of a Helper class
+ * @param $helperInstance An instance of a HubHelper class
* @return void
*/
- public function enqueueRawDataFromTemplate (Helper $helperInstance) {
- // Get protocol instance for recipient
- $protocolInstance = ProtocolHandlerFactory::createProtocolFromRecipientHelper($helperInstance);
+ public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
+ // Debug message
+ //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
// Get the raw content ...
$content = $helperInstance->getTemplateInstance()->getRawTemplateData();
$this->getHashFromContent($content)
);
+ // 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_PROTOCOL => $protocolInstance->getProtocolName(),
self::PACKAGE_DATA_CONTENT => $packageContent,
self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
- self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($packageContent, $this->getSessionId())
+ self::PACKAGE_DATA_HASH => $this->generatePackageHash($packageContent, $this->getSessionId())
));
+
+ // Debug message
+ //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
}
/**
* @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
// Declare the raw package data for delivery
$this->declareRawPackageData($packageData);
+
+ // Debug message
+ //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
}
/**
* @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
// 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!');
}
/**
* @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
// 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!');
}
/**
* @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());
// Push array back in stack
$this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
+
+ // Debug message
+ //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
}
///////////////////////////////////////////////////////////////////////////
/**
* Checks whether new raw package data has arrived at a socket
*
- * @param $poolInstance An instance of a PoolableListener class
* @return $hasArrived Whether new raw package data has arrived for processing
*/
- public function isNewRawDataPending (PoolableListener $poolInstance) {
+ public function isNewRawDataPending () {
// Visit the pool. This monitors the pool for incoming raw data.
- $poolInstance->accept($this->getVisitorInstance());
+ $this->getListenerPoolInstance()->accept($this->getVisitorInstance());
// Check for new data arrival
$hasArrived = $this->isRawDataPending();
*/
public function accept (Visitor $visitorInstance) {
// Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - START');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
// Visit the package
$visitorInstance->visitNetworkPackage($this);
$this->getAssemblerInstance()->accept($visitorInstance);
// Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
}
/**
// Assert on count (should be always 3)
assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
- // Generate the signature of comparing it
- /*
- * @todo Unsupported feature of "signed" messages commented out
- if (!$this->isPackageSignatureValid($decodedArray)) {
+ // Generate the hash of comparing it
+ if (!$this->isPackageHashValid($decodedArray)) {
// Is not valid, so throw an exception here
- exit(__METHOD__ . ':INVALID SIG! UNDER CONSTRUCTION!' . chr(10));
+ exit(__METHOD__ . ':INVALID HASH! UNDER CONSTRUCTION!' . chr(10));
} // END - if
- */
/*
- * Create 'decodedData' array with all assoziative array elements,
- * except signature.
+ * 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_STATUS => self::PACKAGE_STATUS_DECODED,
+ self::PACKAGE_DATA_HASH => $decodedArray[self::INDEX_PACKAGE_HASH]
);
// And return it
// 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]
+ 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]
);
// Is the checksum valid?
* Process the message through all filters, note that all other
* elements from $decodedContent are no longer needed.
*/
- $chainInstance->processMessage($decodedContent[self::PACKAGE_CONTENT_MESSAGE], $this);
+ $chainInstance->processMessage($decodedContent, $this);
}
/**
// Handle message data
$handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $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 $decodedDataArray Array with decoded message
+ * @return void
+ * @todo ~10% done?
+ */
+ public function feedHashToMiner (array $decodedDataArray) {
+ // Make sure the required elements are there
+ assert(isset($decodedDataArray[self::PACKAGE_CONTENT_SENDER]));
+ assert(isset($decodedDataArray[self::PACKAGE_CONTENT_HASH]));
+ assert(isset($decodedDataArray[self::PACKAGE_CONTENT_TAGS]));
+
+ // Resolve session id ('sender' is a session id) into node id
+ $nodeId = HubTools::resolveNodeIdBySessionId($decodedDataArray[self::PACKAGE_CONTENT_SENDER]);
+
+ // Is 'claim_reward' the message type?
+ if (in_array('claim_reward', $decodedDataArray[self::PACKAGE_CONTENT_TAGS])) {
+ /*
+ * Then don't feed this message to the miner as this causes and
+ * endless loop of mining.
+ */
+ return;
+ } // END - if
+
+ $this->partialStub('@TODO nodeId=' . $nodeId . ',decodedDataArray=' . print_r($decodedDataArray, TRUE));
+ }
}
// [EOF]