diff --git a/community_server/src/Controller/Component/JsonRpcRequestClientComponent.php b/community_server/src/Controller/Component/JsonRpcRequestClientComponent.php index 579eafb22..78d274144 100644 --- a/community_server/src/Controller/Component/JsonRpcRequestClientComponent.php +++ b/community_server/src/Controller/Component/JsonRpcRequestClientComponent.php @@ -1,83 +1,83 @@ -rpcClient = new JsonRpcClient(); - } - - // @param id: if id = 0 call rand for it - public function request($method, $params = [], $id = 0) - { - - if(0 == $id) { - $id = random_int(1, 12000); - } - $this->rpcClient->query($id, $method, $params); - - $message = $this->rpcClient->encode(); - return $this->sendRequest($message); - // message: {"jsonrpc":"2.0","method":"add","params":[1,2],"id":1} - } - - public function sendRequest($message) { - $http = new Client(); - - try { - $url = $this->pickGradidoNodeUrl(); - if(is_array($url)) { - return $url; - } - $response = $http->post($url, $message, ['type' => 'json']); - } catch(Exception $e) { - return ['state' => 'error', 'type' => 'http exception', 'details' => $e->getMessage()]; - } - $responseStatus = $response->getStatusCode(); - if($responseStatus != 200) { - return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response status code isn\'t 200', 'details' => $responseStatus]; - } - //$responseType = $response->getType(); - //if($responseType != 'application/json') { -// return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t json', 'details' => $responseType]; -// } - $json = $response->getJson(); - if($json == null) { - //$responseType = $response->getType(); - return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t valid json']; - } - return $json['result']; - //return ['state' => 'success', 'data' => $json]; - } - - static public function pickGradidoNodeUrl() - { - $gradidoNodes = Configure::read('GradidoNode'); - if(count($gradidoNodes) == 0) { - return ['state' => 'error', 'msg' => 'no gradido nodes in config']; - } - $i = rand(0, count($gradidoNodes)-1); - return $gradidoNodes[$i]['host'] . ':' . $gradidoNodes[$i]['port']; - } - - -} - - +rpcClient = new JsonRpcClient(); + } + + // @param id: if id = 0 call rand for it + public function request($method, $params = [], $id = 0) + { + + if(0 == $id) { + $id = random_int(1, 12000); + } + $this->rpcClient->query($id, $method, $params); + + $message = $this->rpcClient->encode(); + return $this->sendRequest($message); + // message: {"jsonrpc":"2.0","method":"add","params":[1,2],"id":1} + } + + public function sendRequest($message) { + $http = new Client(); + + try { + $url = $this->pickGradidoNodeUrl(); + if(is_array($url)) { + return $url; + } + $response = $http->post($url, $message, ['type' => 'json']); + } catch(Exception $e) { + return ['state' => 'error', 'type' => 'http exception', 'details' => $e->getMessage()]; + } + $responseStatus = $response->getStatusCode(); + if($responseStatus != 200) { + return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response status code isn\'t 200', 'details' => $responseStatus]; + } + //$responseType = $response->getType(); + //if($responseType != 'application/json') { +// return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t json', 'details' => $responseType]; +// } + $json = $response->getJson(); + if($json == null) { + //$responseType = $response->getType(); + return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t valid json']; + } + return $json['result']; + //return ['state' => 'success', 'data' => $json]; + } + + static public function pickGradidoNodeUrl() + { + $gradidoNodes = Configure::read('GradidoNode'); + if(count($gradidoNodes) == 0) { + return ['state' => 'error', 'msg' => 'no gradido nodes in config']; + } + $i = rand(0, count($gradidoNodes)-1); + return $gradidoNodes[$i]['host'] . ':' . $gradidoNodes[$i]['port']; + } + + +} + + diff --git a/community_server/src/Model/Messages/Gradido/Key.php b/community_server/src/Model/Messages/Gradido/Key.php index ace440729..b6190304c 100644 --- a/community_server/src/Model/Messages/Gradido/Key.php +++ b/community_server/src/Model/Messages/Gradido/Key.php @@ -22,9 +22,9 @@ class Key extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type string $ed25519 - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * @type string $ed25519_ref10 - * ed25519 ref10 signature + * ed25519 ref10 signature * } */ public function __construct($data = NULL) { @@ -33,7 +33,7 @@ class Key extends \Google\Protobuf\Internal\Message } /** - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * * Generated from protobuf field bytes ed25519 = 2; * @return string @@ -44,7 +44,7 @@ class Key extends \Google\Protobuf\Internal\Message } /** - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * * Generated from protobuf field bytes ed25519 = 2; * @param string $var @@ -59,7 +59,7 @@ class Key extends \Google\Protobuf\Internal\Message } /** - * ed25519 ref10 signature + * ed25519 ref10 signature * * Generated from protobuf field bytes ed25519_ref10 = 3; * @return string @@ -70,7 +70,7 @@ class Key extends \Google\Protobuf\Internal\Message } /** - * ed25519 ref10 signature + * ed25519 ref10 signature * * Generated from protobuf field bytes ed25519_ref10 = 3; * @param string $var diff --git a/community_server/src/Model/Messages/Gradido/SenderAmount.php b/community_server/src/Model/Messages/Gradido/SenderAmount.php index 9b423947e..52a41f71f 100644 --- a/community_server/src/Model/Messages/Gradido/SenderAmount.php +++ b/community_server/src/Model/Messages/Gradido/SenderAmount.php @@ -22,7 +22,7 @@ class SenderAmount extends \Google\Protobuf\Internal\Message */ private $amount = 0; /** - * sender balance after transaction, including perishability + * sender balance after transaction, including perishability * * Generated from protobuf field sint64 senderFinalBalance = 3; */ @@ -37,7 +37,7 @@ class SenderAmount extends \Google\Protobuf\Internal\Message * @type string $ed25519_sender_pubkey * @type int|string $amount * @type int|string $senderFinalBalance - * sender balance after transaction, including perishability + * sender balance after transaction, including perishability * } */ public function __construct($data = NULL) { @@ -90,7 +90,7 @@ class SenderAmount extends \Google\Protobuf\Internal\Message } /** - * sender balance after transaction, including perishability + * sender balance after transaction, including perishability * * Generated from protobuf field sint64 senderFinalBalance = 3; * @return int|string @@ -101,7 +101,7 @@ class SenderAmount extends \Google\Protobuf\Internal\Message } /** - * sender balance after transaction, including perishability + * sender balance after transaction, including perishability * * Generated from protobuf field sint64 senderFinalBalance = 3; * @param int|string $var diff --git a/community_server/src/Model/Messages/Gradido/SignatureMap.php b/community_server/src/Model/Messages/Gradido/SignatureMap.php index ea6f16150..228282747 100644 --- a/community_server/src/Model/Messages/Gradido/SignatureMap.php +++ b/community_server/src/Model/Messages/Gradido/SignatureMap.php @@ -14,7 +14,7 @@ use Google\Protobuf\Internal\GPBUtil; class SignatureMap extends \Google\Protobuf\Internal\Message { /** - * Each signature pair corresponds to a unique Key required to sign the transaction. + * Each signature pair corresponds to a unique Key required to sign the transaction. * * Generated from protobuf field repeated .model.messages.gradido.SignaturePair sigPair = 1; */ @@ -27,7 +27,7 @@ class SignatureMap extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type \Model\Messages\Gradido\SignaturePair[]|\Google\Protobuf\Internal\RepeatedField $sigPair - * Each signature pair corresponds to a unique Key required to sign the transaction. + * Each signature pair corresponds to a unique Key required to sign the transaction. * } */ public function __construct($data = NULL) { @@ -36,7 +36,7 @@ class SignatureMap extends \Google\Protobuf\Internal\Message } /** - * Each signature pair corresponds to a unique Key required to sign the transaction. + * Each signature pair corresponds to a unique Key required to sign the transaction. * * Generated from protobuf field repeated .model.messages.gradido.SignaturePair sigPair = 1; * @return \Google\Protobuf\Internal\RepeatedField @@ -47,7 +47,7 @@ class SignatureMap extends \Google\Protobuf\Internal\Message } /** - * Each signature pair corresponds to a unique Key required to sign the transaction. + * Each signature pair corresponds to a unique Key required to sign the transaction. * * Generated from protobuf field repeated .model.messages.gradido.SignaturePair sigPair = 1; * @param \Model\Messages\Gradido\SignaturePair[]|\Google\Protobuf\Internal\RepeatedField $var diff --git a/community_server/src/Model/Messages/Gradido/SignaturePair.php b/community_server/src/Model/Messages/Gradido/SignaturePair.php index 4575a7d38..203eb5677 100644 --- a/community_server/src/Model/Messages/Gradido/SignaturePair.php +++ b/community_server/src/Model/Messages/Gradido/SignaturePair.php @@ -27,9 +27,9 @@ class SignaturePair extends \Google\Protobuf\Internal\Message * * @type string $pubKey * @type string $ed25519 - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * @type string $ed25519_ref10 - * ed25519 ref10 signature + * ed25519 ref10 signature * } */ public function __construct($data = NULL) { @@ -60,7 +60,7 @@ class SignaturePair extends \Google\Protobuf\Internal\Message } /** - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * * Generated from protobuf field bytes ed25519 = 2; * @return string @@ -71,7 +71,7 @@ class SignaturePair extends \Google\Protobuf\Internal\Message } /** - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * * Generated from protobuf field bytes ed25519 = 2; * @param string $var @@ -86,7 +86,7 @@ class SignaturePair extends \Google\Protobuf\Internal\Message } /** - * ed25519 ref10 signature + * ed25519 ref10 signature * * Generated from protobuf field bytes ed25519_ref10 = 3; * @return string @@ -97,7 +97,7 @@ class SignaturePair extends \Google\Protobuf\Internal\Message } /** - * ed25519 ref10 signature + * ed25519 ref10 signature * * Generated from protobuf field bytes ed25519_ref10 = 3; * @param string $var diff --git a/community_server/src/Model/Messages/Gradido/StateCreateGroup.php b/community_server/src/Model/Messages/Gradido/StateCreateGroup.php index dad246745..4273ef93d 100644 --- a/community_server/src/Model/Messages/Gradido/StateCreateGroup.php +++ b/community_server/src/Model/Messages/Gradido/StateCreateGroup.php @@ -9,7 +9,7 @@ use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** - * need signature from this group and from parent (if it isn't zero) + * need signature from this group and from parent (if it isn't zero) * * Generated from protobuf message model.messages.gradido.StateCreateGroup */ diff --git a/community_server/src/Model/Messages/Gradido/StateGroupChangeParent.php b/community_server/src/Model/Messages/Gradido/StateGroupChangeParent.php index 9cd15175a..c5371d76c 100644 --- a/community_server/src/Model/Messages/Gradido/StateGroupChangeParent.php +++ b/community_server/src/Model/Messages/Gradido/StateGroupChangeParent.php @@ -9,7 +9,7 @@ use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** - * need signature from this group and from both parents (if it isn't zero) + * need signature from this group and from both parents (if it isn't zero) * * Generated from protobuf message model.messages.gradido.StateGroupChangeParent */ diff --git a/community_server/src/Model/Messages/Gradido/Timestamp.php b/community_server/src/Model/Messages/Gradido/Timestamp.php index 7b2316720..19721729b 100644 --- a/community_server/src/Model/Messages/Gradido/Timestamp.php +++ b/community_server/src/Model/Messages/Gradido/Timestamp.php @@ -16,13 +16,13 @@ use Google\Protobuf\Internal\GPBUtil; class Timestamp extends \Google\Protobuf\Internal\Message { /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; */ private $seconds = 0; /** - * Number of nanoseconds since the start of the last second + * Number of nanoseconds since the start of the last second * * Generated from protobuf field int32 nanos = 2; */ @@ -35,9 +35,9 @@ class Timestamp extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type int|string $seconds - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * @type int $nanos - * Number of nanoseconds since the start of the last second + * Number of nanoseconds since the start of the last second * } */ public function __construct($data = NULL) { @@ -46,7 +46,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message } /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; * @return int|string @@ -57,7 +57,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message } /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; * @param int|string $var @@ -72,7 +72,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message } /** - * Number of nanoseconds since the start of the last second + * Number of nanoseconds since the start of the last second * * Generated from protobuf field int32 nanos = 2; * @return int @@ -83,7 +83,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message } /** - * Number of nanoseconds since the start of the last second + * Number of nanoseconds since the start of the last second * * Generated from protobuf field int32 nanos = 2; * @param int $var diff --git a/community_server/src/Model/Messages/Gradido/TimestampSeconds.php b/community_server/src/Model/Messages/Gradido/TimestampSeconds.php index 2646a06c9..2a588a312 100644 --- a/community_server/src/Model/Messages/Gradido/TimestampSeconds.php +++ b/community_server/src/Model/Messages/Gradido/TimestampSeconds.php @@ -16,7 +16,7 @@ use Google\Protobuf\Internal\GPBUtil; class TimestampSeconds extends \Google\Protobuf\Internal\Message { /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; */ @@ -29,7 +29,7 @@ class TimestampSeconds extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type int|string $seconds - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * } */ public function __construct($data = NULL) { @@ -38,7 +38,7 @@ class TimestampSeconds extends \Google\Protobuf\Internal\Message } /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; * @return int|string @@ -49,7 +49,7 @@ class TimestampSeconds extends \Google\Protobuf\Internal\Message } /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; * @param int|string $var diff --git a/community_server/src/Model/Messages/Gradido/TransactionCreation.php b/community_server/src/Model/Messages/Gradido/TransactionCreation.php index 1c8f33dba..ae5f86e07 100644 --- a/community_server/src/Model/Messages/Gradido/TransactionCreation.php +++ b/community_server/src/Model/Messages/Gradido/TransactionCreation.php @@ -9,27 +9,27 @@ use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** - * need signature from group admin or - * percent of group users another than the receiver + * need signature from group admin or + * percent of group users another than the receiver * * Generated from protobuf message model.messages.gradido.TransactionCreation */ class TransactionCreation extends \Google\Protobuf\Internal\Message { /** - * 40 Byte + * 40 Byte * * Generated from protobuf field .model.messages.gradido.ReceiverAmount receiverAmount = 1; */ private $receiverAmount = null; /** - * 4 Byte + * 4 Byte * * Generated from protobuf field sint32 ident_hash = 2; */ private $ident_hash = 0; /** - * 8 Byte + * 8 Byte * * Generated from protobuf field .model.messages.gradido.TimestampSeconds target_date = 3; */ @@ -42,11 +42,11 @@ class TransactionCreation extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type \Model\Messages\Gradido\ReceiverAmount $receiverAmount - * 40 Byte + * 40 Byte * @type int $ident_hash - * 4 Byte + * 4 Byte * @type \Model\Messages\Gradido\TimestampSeconds $target_date - * 8 Byte + * 8 Byte * } */ public function __construct($data = NULL) { @@ -55,7 +55,7 @@ class TransactionCreation extends \Google\Protobuf\Internal\Message } /** - * 40 Byte + * 40 Byte * * Generated from protobuf field .model.messages.gradido.ReceiverAmount receiverAmount = 1; * @return \Model\Messages\Gradido\ReceiverAmount @@ -66,7 +66,7 @@ class TransactionCreation extends \Google\Protobuf\Internal\Message } /** - * 40 Byte + * 40 Byte * * Generated from protobuf field .model.messages.gradido.ReceiverAmount receiverAmount = 1; * @param \Model\Messages\Gradido\ReceiverAmount $var @@ -81,7 +81,7 @@ class TransactionCreation extends \Google\Protobuf\Internal\Message } /** - * 4 Byte + * 4 Byte * * Generated from protobuf field sint32 ident_hash = 2; * @return int @@ -92,7 +92,7 @@ class TransactionCreation extends \Google\Protobuf\Internal\Message } /** - * 4 Byte + * 4 Byte * * Generated from protobuf field sint32 ident_hash = 2; * @param int $var @@ -107,7 +107,7 @@ class TransactionCreation extends \Google\Protobuf\Internal\Message } /** - * 8 Byte + * 8 Byte * * Generated from protobuf field .model.messages.gradido.TimestampSeconds target_date = 3; * @return \Model\Messages\Gradido\TimestampSeconds @@ -118,7 +118,7 @@ class TransactionCreation extends \Google\Protobuf\Internal\Message } /** - * 8 Byte + * 8 Byte * * Generated from protobuf field .model.messages.gradido.TimestampSeconds target_date = 3; * @param \Model\Messages\Gradido\TimestampSeconds $var diff --git a/community_server/src/Model/Messages/Proto/Gradido/Key.php b/community_server/src/Model/Messages/Proto/Gradido/Key.php index 4c32e0083..f18b49a27 100644 --- a/community_server/src/Model/Messages/Proto/Gradido/Key.php +++ b/community_server/src/Model/Messages/Proto/Gradido/Key.php @@ -22,9 +22,9 @@ class Key extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type string $ed25519 - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * @type string $ed25519_ref10 - * ed25519 ref10 signature + * ed25519 ref10 signature * } */ public function __construct($data = NULL) { @@ -33,7 +33,7 @@ class Key extends \Google\Protobuf\Internal\Message } /** - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * * Generated from protobuf field bytes ed25519 = 2; * @return string @@ -44,7 +44,7 @@ class Key extends \Google\Protobuf\Internal\Message } /** - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * * Generated from protobuf field bytes ed25519 = 2; * @param string $var @@ -59,7 +59,7 @@ class Key extends \Google\Protobuf\Internal\Message } /** - * ed25519 ref10 signature + * ed25519 ref10 signature * * Generated from protobuf field bytes ed25519_ref10 = 3; * @return string @@ -70,7 +70,7 @@ class Key extends \Google\Protobuf\Internal\Message } /** - * ed25519 ref10 signature + * ed25519 ref10 signature * * Generated from protobuf field bytes ed25519_ref10 = 3; * @param string $var diff --git a/community_server/src/Model/Messages/Proto/Gradido/SignatureMap.php b/community_server/src/Model/Messages/Proto/Gradido/SignatureMap.php index 0977169d7..59b7d7549 100644 --- a/community_server/src/Model/Messages/Proto/Gradido/SignatureMap.php +++ b/community_server/src/Model/Messages/Proto/Gradido/SignatureMap.php @@ -14,7 +14,7 @@ use Google\Protobuf\Internal\GPBUtil; class SignatureMap extends \Google\Protobuf\Internal\Message { /** - * Each signature pair corresponds to a unique Key required to sign the transaction. + * Each signature pair corresponds to a unique Key required to sign the transaction. * * Generated from protobuf field repeated .proto.gradido.SignaturePair sigPair = 1; */ @@ -27,7 +27,7 @@ class SignatureMap extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type \Proto\Gradido\SignaturePair[]|\Google\Protobuf\Internal\RepeatedField $sigPair - * Each signature pair corresponds to a unique Key required to sign the transaction. + * Each signature pair corresponds to a unique Key required to sign the transaction. * } */ public function __construct($data = NULL) { @@ -36,7 +36,7 @@ class SignatureMap extends \Google\Protobuf\Internal\Message } /** - * Each signature pair corresponds to a unique Key required to sign the transaction. + * Each signature pair corresponds to a unique Key required to sign the transaction. * * Generated from protobuf field repeated .proto.gradido.SignaturePair sigPair = 1; * @return \Google\Protobuf\Internal\RepeatedField @@ -47,7 +47,7 @@ class SignatureMap extends \Google\Protobuf\Internal\Message } /** - * Each signature pair corresponds to a unique Key required to sign the transaction. + * Each signature pair corresponds to a unique Key required to sign the transaction. * * Generated from protobuf field repeated .proto.gradido.SignaturePair sigPair = 1; * @param \Proto\Gradido\SignaturePair[]|\Google\Protobuf\Internal\RepeatedField $var diff --git a/community_server/src/Model/Messages/Proto/Gradido/SignaturePair.php b/community_server/src/Model/Messages/Proto/Gradido/SignaturePair.php index 2ef0e81c5..986596e3c 100644 --- a/community_server/src/Model/Messages/Proto/Gradido/SignaturePair.php +++ b/community_server/src/Model/Messages/Proto/Gradido/SignaturePair.php @@ -27,9 +27,9 @@ class SignaturePair extends \Google\Protobuf\Internal\Message * * @type string $pubKey * @type string $ed25519 - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * @type string $ed25519_ref10 - * ed25519 ref10 signature + * ed25519 ref10 signature * } */ public function __construct($data = NULL) { @@ -60,7 +60,7 @@ class SignaturePair extends \Google\Protobuf\Internal\Message } /** - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * * Generated from protobuf field bytes ed25519 = 2; * @return string @@ -71,7 +71,7 @@ class SignaturePair extends \Google\Protobuf\Internal\Message } /** - * ed25519 signature (libsodium default) + * ed25519 signature (libsodium default) * * Generated from protobuf field bytes ed25519 = 2; * @param string $var @@ -86,7 +86,7 @@ class SignaturePair extends \Google\Protobuf\Internal\Message } /** - * ed25519 ref10 signature + * ed25519 ref10 signature * * Generated from protobuf field bytes ed25519_ref10 = 3; * @return string @@ -97,7 +97,7 @@ class SignaturePair extends \Google\Protobuf\Internal\Message } /** - * ed25519 ref10 signature + * ed25519 ref10 signature * * Generated from protobuf field bytes ed25519_ref10 = 3; * @param string $var diff --git a/community_server/src/Model/Messages/Proto/Gradido/Timestamp.php b/community_server/src/Model/Messages/Proto/Gradido/Timestamp.php index ae3ecea0e..3d8d2ed7a 100644 --- a/community_server/src/Model/Messages/Proto/Gradido/Timestamp.php +++ b/community_server/src/Model/Messages/Proto/Gradido/Timestamp.php @@ -16,13 +16,13 @@ use Google\Protobuf\Internal\GPBUtil; class Timestamp extends \Google\Protobuf\Internal\Message { /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; */ private $seconds = 0; /** - * Number of nanoseconds since the start of the last second + * Number of nanoseconds since the start of the last second * * Generated from protobuf field int32 nanos = 2; */ @@ -35,9 +35,9 @@ class Timestamp extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type int|string $seconds - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * @type int $nanos - * Number of nanoseconds since the start of the last second + * Number of nanoseconds since the start of the last second * } */ public function __construct($data = NULL) { @@ -46,7 +46,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message } /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; * @return int|string @@ -57,7 +57,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message } /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; * @param int|string $var @@ -72,7 +72,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message } /** - * Number of nanoseconds since the start of the last second + * Number of nanoseconds since the start of the last second * * Generated from protobuf field int32 nanos = 2; * @return int @@ -83,7 +83,7 @@ class Timestamp extends \Google\Protobuf\Internal\Message } /** - * Number of nanoseconds since the start of the last second + * Number of nanoseconds since the start of the last second * * Generated from protobuf field int32 nanos = 2; * @param int $var diff --git a/community_server/src/Model/Messages/Proto/Gradido/TimestampSeconds.php b/community_server/src/Model/Messages/Proto/Gradido/TimestampSeconds.php index d31aa40d2..dda39a858 100644 --- a/community_server/src/Model/Messages/Proto/Gradido/TimestampSeconds.php +++ b/community_server/src/Model/Messages/Proto/Gradido/TimestampSeconds.php @@ -16,7 +16,7 @@ use Google\Protobuf\Internal\GPBUtil; class TimestampSeconds extends \Google\Protobuf\Internal\Message { /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; */ @@ -29,7 +29,7 @@ class TimestampSeconds extends \Google\Protobuf\Internal\Message * Optional. Data for populating the Message object. * * @type int|string $seconds - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * } */ public function __construct($data = NULL) { @@ -38,7 +38,7 @@ class TimestampSeconds extends \Google\Protobuf\Internal\Message } /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; * @return int|string @@ -49,7 +49,7 @@ class TimestampSeconds extends \Google\Protobuf\Internal\Message } /** - * Number of complete seconds since the start of the epoch + * Number of complete seconds since the start of the epoch * * Generated from protobuf field int64 seconds = 1; * @param int|string $var diff --git a/community_server/src/Model/Transactions/Record.php b/community_server/src/Model/Transactions/Record.php index 862399af5..5572730ef 100644 --- a/community_server/src/Model/Transactions/Record.php +++ b/community_server/src/Model/Transactions/Record.php @@ -1,575 +1,575 @@ -signature = $signature; - $this->publicKey = $pubkey; - } - - public function finalize($transactionId) - { - $signaturesTable = TableRegistry::getTableLocator()->get('TransactionSignatures'); - $entity = $signaturesTable->newEntity(); - $entity->transaction_id = $transactionId; - if(strlen($this->signature) != 128) { - return ['state' => 'error', 'msg' => 'invalid signature size', 'details' => strlen($this->signature)]; - } - if(strlen($this->publicKey) != 64) { - return ['state' => 'error', 'msg' => 'invalid pubkey size', 'details' => strlen($this->publicKey)]; - } - if(!preg_match('/^[0-9a-fA-F]*$/', $this->signature)) { - return ['state' => 'error', 'msg' => 'signature isn\'t in hex format']; - } - if(!preg_match('/^[0-9a-fA-F]*$/', $this->publicKey)) { - return ['state' => 'error', 'msg' => 'publicKey isn\'t in hex format']; - } - $entity->signature = hex2bin($this->signature); - $entity->pubkey = hex2bin($this->publicKey); - - if(!$signaturesTable->save($entity)) { - return ['state' => 'error', 'msg' => 'error saving signature', 'details' => $entity->getErrors()]; - } - return true; - } -} - - - -class GradidoModifieUserBalance -{ - private $state_users = []; - private $user_balances = []; - - public function getUserId($userPublicKey) - { - $stateUsersTable = TableRegistry::getTableLocator()->get('StateUsers'); - - $stateUser = $stateUsersTable->find('all')->where(['public_key' => hex2bin($userPublicKey)]); - if($stateUser->isEmpty()) { - return ['state' => 'error', 'msg' => '[GradidoModifieUserBalance::getUserId] couldn\'t find user via public key']; - } - $id = $stateUser->first()->id; - if($id && is_int($id) && (int)$id > 0 && !in_array((int)$id, $this->state_users)) { - array_push($this->state_users, (int)$id); - } - return $id; - } - - public function updateBalance($newBalance, $recordDate, $userId) - { - $stateBalancesTable = TableRegistry::getTableLocator()->get('StateBalances'); - $state_balance_query = $stateBalancesTable->find()->where(['state_user_id' => $userId])->order(['record_date ASC']); - $state_balance = null; - if($state_balance_query->count() > 0) { - $state_balance = $state_balance_query->last(); - } else { - $state_balance = $stateBalancesTable->newEntity(); - $state_balance->state_user_id = $userId; - } - $state_balance->amount = $newBalance; - $state_balance->record_date = $recordDate; - $this->user_balances[$userId] = $state_balance; - $stateBalancesTable->save($state_balance); - return true; - //$this->user_balances[$userId] = ['balance' => $newBalance, ''] - // - //return $stateBalancesTable->updateBalanceWithTransaction($newBalance, $recordDate, $userId); - - /*$first_of_month = new Time("$year-$month-01 00:00"); - $stateBalanceQuery = $stateBalancesTable - ->find('all') - ->where(['state_user_id' => $userId]) - ->order(['record_date' => 'DESC']) - ->limit(1); - $entity = null; - - if(!$stateBalanceQuery->isEmpty()) { - $entity = $stateBalanceQuery->first(); - if($entity->record_date != NULL && - ($entity->record_date > $recordDate || $entity->record_date->day == 1)) { - return false; - } - } else { - $entity = $stateBalancesTable->newEntity(); - $entity->state_user_id = $userId; - } - $entity->record_date = $recordDate; - $entity->amount = $newBalance; - /*if(!$stateBalancesTable->save($entity)) { - return ['state' => 'error', 'msg' => 'error saving state balance', 'details' => $entity->getErrors()]; - }*/ - //return true; - } - - public function getAllStateUsers() - { - return $this->state_users; - } - public function getAllStateUserBalances() - { - return $this->user_balances; - } -} - -class ManageNodeGroupAdd extends GradidoModifieUserBalance -{ - /* - "add_user": { - "user\": " << user << ", - }, - OR - - "move_user_inbound|move_user_outbound": { - "user": " << user << ", - "other_group": " << other_group << ", - "paired_transaction_id": { - "seconds": << ts.seconds <<, - "nanos": << ts.nanos - } - }, - - */ - - private $user_pubkey; - private $other_group = ''; - private $remove_from_group = false; - - public function __construct($data) - { - $this->user_pubkey = $data['user']; - if(isset($data['other_group'])) { - $this->other_group = $data['other_group']; - } - } - - public function finalize($transactionId, $received) - { - $transactionGroupAddadressTable = TableRegistry::getTableLocator()->get('TransactionGroupAddaddress'); - $stateGroupAddresses = TableRegistry::getTableLocator()->get('StateGroupAddresses'); - $transactionGroupEntity = $transactionGroupAddadressTable->newEntity(); - if(!is_int($transactionId)) { - return ['state' => 'error', 'msg' => '[ManageNodeGroupAdd::finalize] transaction id is not int', 'details' => $transactionId]; - } - $transactionGroupEntity->transaction_id = $transactionId; - $transactionGroupEntity->address_type_id = 1; - if(strlen($this->user_pubkey) != 64) { - return ['state' => 'error', 'msg' => 'invalid size user pubkey', 'details' => strlen($this->user_pubkey)]; - } - if(!preg_match('/^[0-9a-fA-F]*$/', $this->user_pubkey)) { - return ['state' => 'error', 'msg' => 'user_pubkey isn\'t in hex format']; - } - - $userPubkeyBin = hex2bin($this->user_pubkey); - - $transactionGroupEntity->public_key = $userPubkeyBin; - $user_id = $this->getUserId($this->user_pubkey); - if(!is_int($user_id)) { - return ['state' => 'error', 'msg' => '[ManageNodeGroupAdd::finalize] user id is not int', 'details' => $user_id]; - } - $transactionGroupEntity->state_user_id = $user_id; - $transactionGroupEntity->remove_from_group = $this->remove_from_group; - if(!$transactionGroupAddadressTable->save($transactionGroupEntity)) { - return ['state' => 'error', 'msg' => 'error saving TransactionGroupAddaddress Entity', 'details' => $transactionGroupEntity->getErrors()]; - } - - - if($this->remove_from_group) { - $stateGroup_query = $stateGroupAddresses->find('all')->where(['public_key' => hex2bin($this->user_pubkey)]); - if(!$stateGroup_query->isEmpty()) { - $stateGroupAddresses->delete($stateGroup_query->first()); - } - } else { - $stateGroupAddressesEntity = $stateGroupAddresses->newEntity(); - $stateGroupAddressesEntity->group_id = 1; - $stateGroupAddressesEntity->public_key = $userPubkeyBin; - $stateGroupAddressesEntity->address_type_id = 1; - if(!$stateGroupAddresses->save($stateGroupAddressesEntity)) { - return ['state' => 'error', 'msg' => 'error saving state group addresses entity', 'details' => $stateGroupAddressesEntity->getErrors()]; - } - } - - return true; - } - - public function setRemoveFromGroup($removeFromGroup) { - $this->remove_from_group = $removeFromGroup; - } -} - - -class GradidoCreation extends GradidoModifieUserBalance -{ - /* - * "gradido_creation": { - "user": " << user << ", - "new_balance": << v.new_balance << , - "prev_transfer_rec_num": << v.prev_transfer_rec_num <<, - "amount": << v.amount << - } - */ - private $userPubkey; - private $amount; - private $targetDate; // seems currently not in node server implementet, use hedera date until it is implemented - private $new_balance; - - - public function __construct($data) - { - $this->userPubkey = $data['user']; - $this->amount = $data['amount']['amount']; - $this->new_balance = $data['new_balance']['amount']; - //$this->targetDate = $received; - } - - public function finalize($transactionId, $received) - { - // TODO: don't use, after node server transmit correct date - $this->targetDate = $received; - - $transactionCreationTable = TableRegistry::getTableLocator()->get('TransactionCreations'); - - - $state_user_id = $this->getUserId($this->userPubkey); - if(!is_int($state_user_id)) { - return $state_user_id; - } - - $entity = $transactionCreationTable->newEntity(); - $entity->transaction_id = $transactionId; - $entity->amount = $this->amount; - $entity->target_date = $this->targetDate; - $entity->state_user_id = $state_user_id; - - if(!$transactionCreationTable->save($entity)) { - return ['state' => 'error', 'msg' => 'error saving create transaction', 'details' => $entity->getErrors()]; - } - - $balance_result = $this->updateBalance($this->new_balance, $received, $state_user_id); - if(is_array($balance_result)) { - return $balance_result; - } - - return true; - } - - - -} - -class GradidoTransfer extends GradidoModifieUserBalance -{ - /* - "local_transfer|inbound_transfer|outbound_transfer": { - "sender": { - "user": " << sender << ", - "new_balance": << tt.sender.new_balance << , - "prev_transfer_rec_num": << tt.sender.prev_transfer_rec_num << - }, - "receiver": { - "user": " << receiver << ", - "new_balance": << tt.receiver.new_balance << , - "prev_transfer_rec_num": << tt.receiver.prev_transfer_rec_num << - }, - "amount": << tt.amount << - }, - * */ - private $amount; - private $sender_new_balance = null; - private $sender_pubkey; - - private $receiver_pubkey; - private $receiver_new_balance = null; - - - public function __construct($data) - { - $this->amount = $data['amount']['amount']; - - $sender = $data['sender']; - $this->sender_pubkey = $sender['user']; - if(isset($sender['new_balance'])) { - $this->sender_new_balance = $sender['new_balance']['amount']; - } - - $receiver = $data['receiver']; - $this->receiver_pubkey = $receiver['user']; - if(isset($receiver['new_balance'])) { - $this->receiver_new_balance = $receiver['new_balance']['amount']; - } - - } - - public function finalize($transactionId, $received) - { - $transactionTransferTable = TableRegistry::getTableLocator()->get('TransactionSendCoins'); - if(strlen($this->sender_pubkey) != 64) { - return ['state' => 'error', 'msg' => 'invalid size sender pubkey', 'details' => strlen($this->user_pubkey)]; - } - if(!preg_match('/^[0-9a-fA-F]*$/', $this->sender_pubkey)) { - return ['state' => 'error', 'msg' => 'sender_pubkey isn\'t in hex format']; - } - if(strlen($this->receiver_pubkey) != 64) { - return ['state' => 'error', 'msg' => 'invalid size receiver pubkey', 'details' => strlen($this->user_pubkey)]; - } - if(!preg_match('/^[0-9a-fA-F]*$/', $this->receiver_pubkey)) { - return ['state' => 'error', 'msg' => 'receiver_pubkey isn\'t in hex format']; - } - - $sender_id = $this->getUserId($this->sender_pubkey); - $receiver_id = $this->getUserId($this->receiver_pubkey); - if(is_array($sender_id) && is_array($receiver_id)) { - return ['state' => 'error', 'msg' => 'neither sender or receiver known']; - } - $transferEntity = $transactionTransferTable->newEntity(); - $transferEntity->transaction_id = $transactionId; - $transferEntity->sender_public_key = hex2bin($this->sender_pubkey); - $transferEntity->receiver_public_key = hex2bin($this->receiver_pubkey); - $transferEntity->amount = $this->amount; - if($this->sender_new_balance != null) { - $transferEntity->sender_final_balance = $this->sender_new_balance; - - if(is_int($sender_id) && $sender_id > 0) { - $transferEntity->state_user_id = $sender_id; - $balance_result = $this->updateBalance($this->sender_new_balance, $received, $sender_id); - if(is_array($balance_result)) { - return $balance_result; - } - } - } - if($this->receiver_new_balance != null && is_int($receiver_id) && $receiver_id > 0) { - $transferEntity->receiver_user_id = $receiver_id; - $balance_result = $this->updateBalance($this->receiver_new_balance, $received, $receiver_id); - if(is_array($balance_result)) { - return $balance_result; - } - } - - if(!$transactionTransferTable->save($transferEntity)) { - return ['state' => 'error', 'msg' => 'error saving transaction send coins entity', 'details' => $transferEntity->getErrors()]; - } - - return true; - } - -} - - - - -class Record -{ - private $sequenceNumber = 0; - private $runningHash = null; - private $transactionType = ''; - private $memo = ''; - private $signatures = []; - private $received; - private $transactionObj = null; - private $result; - private $partCount = 0; - - public function __construct() - { - - } - - - public function parseRecord($json) { - if(!isset($json['record_type'])) { - return false; - } - //var_dump($json); - switch($json['record_type']) { - case 'GRADIDO_TRANSACTION': - return $this->parseTransaction($json['transaction']); - case 'MEMO': - $this->memo .= $json['memo']; - return true; - case 'SIGNATURES': - return $this->parseSignatures($json['signature']); - case 'STRUCTURALLY_BAD_MESSAGE': - case 'RAW_MESSAGE': - case 'BLANK': - return false; - } - } - - /*! - * \brief save data parts in db - */ - public function finalize() - { - $transactionTypesTable = TableRegistry::getTableLocator()->get('TransactionTypes'); - $transactionsTable = TableRegistry::getTableLocator()->get('Transactions'); - $stateUserTransactionsTable = TableRegistry::getTableLocator()->get('StateUserTransactions'); - - $transactionTypeName = $this->nodeTransactionTypeToDBTransactionType($this->transactionType); - $transactionTypeResults = $transactionTypesTable->find('all')->where(['name' => $transactionTypeName]); - if($transactionTypeResults->isEmpty()) { - return [ - 'state' => 'error', 'msg' => 'transaction type not found', - 'details' => ['nodeType' => $this->transactionType, 'dbType' => $transactionTypeName] - ]; - } - if(!$this->transactionObj) { - return ['state' => 'error', 'msg' => 'transaction obj is null']; - } - if($this->sequenceNumber <= 0) { - return ['state' => 'error', 'msg' => 'sequence number invalid', 'details' => $this->sequenceNumber]; - } - $transactionExistResult = $transactionsTable->find('all')->where(['id' => intval($this->sequenceNumber)]); - if(!$transactionExistResult->isEmpty()) { - return ['state' => 'warning', 'msg' => 'transaction already exist in db', 'details' => $this->sequenceNumber]; - } - $newTransaction = $transactionsTable->newEntity(); - $newTransaction->id = $this->sequenceNumber; - $newTransaction->transaction_type_id = $transactionTypeResults->first()->id; - $newTransaction->memo = $this->memo; - if($this->runningHash != '' && strlen($this->runningHash) % 2 == 0) { - $newTransaction->tx_hash = hex2bin($this->runningHash); - } - $newTransaction->received = $this->received; - - //! TODO change into transaction, if at least one fail, rollback - /* - // In a controller. - $articles->getConnection()->transactional(function () use ($articles, $entities) { - foreach ($entities as $entity) { - $articles->save($entity, ['atomic' => false]); - } - }); - */ - if(!$transactionsTable->save($newTransaction)) { - return ['state' => 'error', 'msg' => 'error saving transaction', 'details' => $newTransaction->getErrors()]; - } - - foreach($this->signatures as $sign) { - $sign_result = $sign->finalize($this->sequenceNumber); - if($sign_result !== true) { - return ['state' => 'error', 'msg', 'error finalizing signature', 'details' => $sign_result]; - } - } - $transaction_obj_result = $this->transactionObj->finalize($newTransaction->id, $this->received); - if($transaction_obj_result !== true) { - return ['state' => 'error', 'msg' => 'error finalizing transaction object', 'details' => $transaction_obj_result]; - } - $state_users = $this->transactionObj->getAllStateUsers(); - $sut_entities = []; - $state_user_balances = $this->transactionObj->getAllStateUserBalances(); - foreach($state_users as $state_user_id) { - $entity = $stateUserTransactionsTable->newEntity(); - $entity->state_user_id = $state_user_id; - $entity->transaction_id = $newTransaction->id; - $entity->transaction_type_id = $newTransaction->transaction_type_id; - $entity->balance = $state_user_balances[$state_user_id]->amount; - $entity->balance_date = $state_user_balances[$state_user_id]->record_date; - $sut_entities[] = $entity; - } - $sut_results = $stateUserTransactionsTable->saveMany($sut_entities); - foreach($sut_results as $i => $result) { - if(false == $result) { - return ['state' => 'error', 'msg' => 'error saving state_user_transaction', 'details' => $sut_entities[$i]->getErrors()]; - } - } - - return true; - - } - - private function nodeTransactionTypeToDBTransactionType($nodeTransactionType) - { - switch($nodeTransactionType) { - case 'GRADIDO_CREATION': - return 'creation'; - - case 'MOVE_USER_INBOUND': - case 'ADD_USER': - return 'group add member'; - - case 'MOVE_USER_OUTBOUND': - return 'group remove member'; - - case 'LOCAL_TRANSFER': - case 'INBOUND_TRANSFER': - case 'OUTBOUND_TRANSFER': - return 'transfer'; - } - return 'unknown'; - } - - private function parseSignatures($signaturesArray) - { - foreach($signaturesArray as $sign) { - $this->signatures[] = new Signature($sign['signature'], $sign['pubkey']); - } - return true; - } - - private function parseTransaction($data) - { - $this->transactionType = $data['transaction_type']; - $sign = $data['signature']; - $this->signatures[] = new Signature($sign['signature'], $sign['pubkey']); - - $hedera = $data['hedera_transaction']; - $this->sequenceNumber = $hedera['sequenceNumber']; - $this->runningHash = $hedera['runningHash']; - $this->received = Time::createFromTimestamp($hedera['consensusTimestamp']['seconds']); - - $field_index = ''; - $class_name = ''; - - $removeFromGroup = false; - switch($this->transactionType) - { - case 'GRADIDO_CREATION': $field_index = 'gradido_creation'; $class_name = 'GradidoCreation'; break; - case 'ADD_USER': $field_index = 'add_user'; $class_name = 'ManageNodeGroupAdd'; break; - case 'MOVE_USER_INBOUND': $field_index = 'move_user_inbound'; $class_name = 'ManageNodeGroupAdd'; break; - case 'MOVE_USER_OUTBOUND': $field_index = 'move_user_outbound'; $class_name = 'ManageNodeGroupAdd'; $removeFromGroup = true; break; - case 'LOCAL_TRANSFER': $field_index = 'local_transfer'; $class_name = 'GradidoTransfer'; break; - case 'INBOUND_TRANSFER': $field_index = 'inbound_transfer'; $class_name = 'GradidoTransfer'; break; - case 'OUTBOUND_TRANSFER': $field_index = 'outbound_transfer'; $class_name = 'GradidoTransfer'; break; - } - if($class_name == '' || $field_index == '') { - return ['state' => 'error', 'msg' => 'node transaction type unknown', 'details' => $this->transactionType]; - } - $class_name = 'Model\\Transactions\\' . $class_name; - $this->transactionObj = new $class_name($data[$field_index]); - if($class_name == 'ManageNodeGroupAdd') { - $this->transactionObj->setRemoveFromGroup($removeFromGroup); - } - - $this->result = $data['result']; - $this->partCount = intval($data['parts']); - $this->memo = $data['memo']; - return true; - } - - public function getSequenceNumber() { - return $this->sequenceNumber; - } - public function getPartCount() { - return $this->partCount; - } - +signature = $signature; + $this->publicKey = $pubkey; + } + + public function finalize($transactionId) + { + $signaturesTable = TableRegistry::getTableLocator()->get('TransactionSignatures'); + $entity = $signaturesTable->newEntity(); + $entity->transaction_id = $transactionId; + if(strlen($this->signature) != 128) { + return ['state' => 'error', 'msg' => 'invalid signature size', 'details' => strlen($this->signature)]; + } + if(strlen($this->publicKey) != 64) { + return ['state' => 'error', 'msg' => 'invalid pubkey size', 'details' => strlen($this->publicKey)]; + } + if(!preg_match('/^[0-9a-fA-F]*$/', $this->signature)) { + return ['state' => 'error', 'msg' => 'signature isn\'t in hex format']; + } + if(!preg_match('/^[0-9a-fA-F]*$/', $this->publicKey)) { + return ['state' => 'error', 'msg' => 'publicKey isn\'t in hex format']; + } + $entity->signature = hex2bin($this->signature); + $entity->pubkey = hex2bin($this->publicKey); + + if(!$signaturesTable->save($entity)) { + return ['state' => 'error', 'msg' => 'error saving signature', 'details' => $entity->getErrors()]; + } + return true; + } +} + + + +class GradidoModifieUserBalance +{ + private $state_users = []; + private $user_balances = []; + + public function getUserId($userPublicKey) + { + $stateUsersTable = TableRegistry::getTableLocator()->get('StateUsers'); + + $stateUser = $stateUsersTable->find('all')->where(['public_key' => hex2bin($userPublicKey)]); + if($stateUser->isEmpty()) { + return ['state' => 'error', 'msg' => '[GradidoModifieUserBalance::getUserId] couldn\'t find user via public key']; + } + $id = $stateUser->first()->id; + if($id && is_int($id) && (int)$id > 0 && !in_array((int)$id, $this->state_users)) { + array_push($this->state_users, (int)$id); + } + return $id; + } + + public function updateBalance($newBalance, $recordDate, $userId) + { + $stateBalancesTable = TableRegistry::getTableLocator()->get('StateBalances'); + $state_balance_query = $stateBalancesTable->find()->where(['state_user_id' => $userId])->order(['record_date ASC']); + $state_balance = null; + if($state_balance_query->count() > 0) { + $state_balance = $state_balance_query->last(); + } else { + $state_balance = $stateBalancesTable->newEntity(); + $state_balance->state_user_id = $userId; + } + $state_balance->amount = $newBalance; + $state_balance->record_date = $recordDate; + $this->user_balances[$userId] = $state_balance; + $stateBalancesTable->save($state_balance); + return true; + //$this->user_balances[$userId] = ['balance' => $newBalance, ''] + // + //return $stateBalancesTable->updateBalanceWithTransaction($newBalance, $recordDate, $userId); + + /*$first_of_month = new Time("$year-$month-01 00:00"); + $stateBalanceQuery = $stateBalancesTable + ->find('all') + ->where(['state_user_id' => $userId]) + ->order(['record_date' => 'DESC']) + ->limit(1); + $entity = null; + + if(!$stateBalanceQuery->isEmpty()) { + $entity = $stateBalanceQuery->first(); + if($entity->record_date != NULL && + ($entity->record_date > $recordDate || $entity->record_date->day == 1)) { + return false; + } + } else { + $entity = $stateBalancesTable->newEntity(); + $entity->state_user_id = $userId; + } + $entity->record_date = $recordDate; + $entity->amount = $newBalance; + /*if(!$stateBalancesTable->save($entity)) { + return ['state' => 'error', 'msg' => 'error saving state balance', 'details' => $entity->getErrors()]; + }*/ + //return true; + } + + public function getAllStateUsers() + { + return $this->state_users; + } + public function getAllStateUserBalances() + { + return $this->user_balances; + } +} + +class ManageNodeGroupAdd extends GradidoModifieUserBalance +{ + /* + "add_user": { + "user\": " << user << ", + }, + OR + + "move_user_inbound|move_user_outbound": { + "user": " << user << ", + "other_group": " << other_group << ", + "paired_transaction_id": { + "seconds": << ts.seconds <<, + "nanos": << ts.nanos + } + }, + + */ + + private $user_pubkey; + private $other_group = ''; + private $remove_from_group = false; + + public function __construct($data) + { + $this->user_pubkey = $data['user']; + if(isset($data['other_group'])) { + $this->other_group = $data['other_group']; + } + } + + public function finalize($transactionId, $received) + { + $transactionGroupAddadressTable = TableRegistry::getTableLocator()->get('TransactionGroupAddaddress'); + $stateGroupAddresses = TableRegistry::getTableLocator()->get('StateGroupAddresses'); + $transactionGroupEntity = $transactionGroupAddadressTable->newEntity(); + if(!is_int($transactionId)) { + return ['state' => 'error', 'msg' => '[ManageNodeGroupAdd::finalize] transaction id is not int', 'details' => $transactionId]; + } + $transactionGroupEntity->transaction_id = $transactionId; + $transactionGroupEntity->address_type_id = 1; + if(strlen($this->user_pubkey) != 64) { + return ['state' => 'error', 'msg' => 'invalid size user pubkey', 'details' => strlen($this->user_pubkey)]; + } + if(!preg_match('/^[0-9a-fA-F]*$/', $this->user_pubkey)) { + return ['state' => 'error', 'msg' => 'user_pubkey isn\'t in hex format']; + } + + $userPubkeyBin = hex2bin($this->user_pubkey); + + $transactionGroupEntity->public_key = $userPubkeyBin; + $user_id = $this->getUserId($this->user_pubkey); + if(!is_int($user_id)) { + return ['state' => 'error', 'msg' => '[ManageNodeGroupAdd::finalize] user id is not int', 'details' => $user_id]; + } + $transactionGroupEntity->state_user_id = $user_id; + $transactionGroupEntity->remove_from_group = $this->remove_from_group; + if(!$transactionGroupAddadressTable->save($transactionGroupEntity)) { + return ['state' => 'error', 'msg' => 'error saving TransactionGroupAddaddress Entity', 'details' => $transactionGroupEntity->getErrors()]; + } + + + if($this->remove_from_group) { + $stateGroup_query = $stateGroupAddresses->find('all')->where(['public_key' => hex2bin($this->user_pubkey)]); + if(!$stateGroup_query->isEmpty()) { + $stateGroupAddresses->delete($stateGroup_query->first()); + } + } else { + $stateGroupAddressesEntity = $stateGroupAddresses->newEntity(); + $stateGroupAddressesEntity->group_id = 1; + $stateGroupAddressesEntity->public_key = $userPubkeyBin; + $stateGroupAddressesEntity->address_type_id = 1; + if(!$stateGroupAddresses->save($stateGroupAddressesEntity)) { + return ['state' => 'error', 'msg' => 'error saving state group addresses entity', 'details' => $stateGroupAddressesEntity->getErrors()]; + } + } + + return true; + } + + public function setRemoveFromGroup($removeFromGroup) { + $this->remove_from_group = $removeFromGroup; + } +} + + +class GradidoCreation extends GradidoModifieUserBalance +{ + /* + * "gradido_creation": { + "user": " << user << ", + "new_balance": << v.new_balance << , + "prev_transfer_rec_num": << v.prev_transfer_rec_num <<, + "amount": << v.amount << + } + */ + private $userPubkey; + private $amount; + private $targetDate; // seems currently not in node server implementet, use hedera date until it is implemented + private $new_balance; + + + public function __construct($data) + { + $this->userPubkey = $data['user']; + $this->amount = $data['amount']['amount']; + $this->new_balance = $data['new_balance']['amount']; + //$this->targetDate = $received; + } + + public function finalize($transactionId, $received) + { + // TODO: don't use, after node server transmit correct date + $this->targetDate = $received; + + $transactionCreationTable = TableRegistry::getTableLocator()->get('TransactionCreations'); + + + $state_user_id = $this->getUserId($this->userPubkey); + if(!is_int($state_user_id)) { + return $state_user_id; + } + + $entity = $transactionCreationTable->newEntity(); + $entity->transaction_id = $transactionId; + $entity->amount = $this->amount; + $entity->target_date = $this->targetDate; + $entity->state_user_id = $state_user_id; + + if(!$transactionCreationTable->save($entity)) { + return ['state' => 'error', 'msg' => 'error saving create transaction', 'details' => $entity->getErrors()]; + } + + $balance_result = $this->updateBalance($this->new_balance, $received, $state_user_id); + if(is_array($balance_result)) { + return $balance_result; + } + + return true; + } + + + +} + +class GradidoTransfer extends GradidoModifieUserBalance +{ + /* + "local_transfer|inbound_transfer|outbound_transfer": { + "sender": { + "user": " << sender << ", + "new_balance": << tt.sender.new_balance << , + "prev_transfer_rec_num": << tt.sender.prev_transfer_rec_num << + }, + "receiver": { + "user": " << receiver << ", + "new_balance": << tt.receiver.new_balance << , + "prev_transfer_rec_num": << tt.receiver.prev_transfer_rec_num << + }, + "amount": << tt.amount << + }, + * */ + private $amount; + private $sender_new_balance = null; + private $sender_pubkey; + + private $receiver_pubkey; + private $receiver_new_balance = null; + + + public function __construct($data) + { + $this->amount = $data['amount']['amount']; + + $sender = $data['sender']; + $this->sender_pubkey = $sender['user']; + if(isset($sender['new_balance'])) { + $this->sender_new_balance = $sender['new_balance']['amount']; + } + + $receiver = $data['receiver']; + $this->receiver_pubkey = $receiver['user']; + if(isset($receiver['new_balance'])) { + $this->receiver_new_balance = $receiver['new_balance']['amount']; + } + + } + + public function finalize($transactionId, $received) + { + $transactionTransferTable = TableRegistry::getTableLocator()->get('TransactionSendCoins'); + if(strlen($this->sender_pubkey) != 64) { + return ['state' => 'error', 'msg' => 'invalid size sender pubkey', 'details' => strlen($this->user_pubkey)]; + } + if(!preg_match('/^[0-9a-fA-F]*$/', $this->sender_pubkey)) { + return ['state' => 'error', 'msg' => 'sender_pubkey isn\'t in hex format']; + } + if(strlen($this->receiver_pubkey) != 64) { + return ['state' => 'error', 'msg' => 'invalid size receiver pubkey', 'details' => strlen($this->user_pubkey)]; + } + if(!preg_match('/^[0-9a-fA-F]*$/', $this->receiver_pubkey)) { + return ['state' => 'error', 'msg' => 'receiver_pubkey isn\'t in hex format']; + } + + $sender_id = $this->getUserId($this->sender_pubkey); + $receiver_id = $this->getUserId($this->receiver_pubkey); + if(is_array($sender_id) && is_array($receiver_id)) { + return ['state' => 'error', 'msg' => 'neither sender or receiver known']; + } + $transferEntity = $transactionTransferTable->newEntity(); + $transferEntity->transaction_id = $transactionId; + $transferEntity->sender_public_key = hex2bin($this->sender_pubkey); + $transferEntity->receiver_public_key = hex2bin($this->receiver_pubkey); + $transferEntity->amount = $this->amount; + if($this->sender_new_balance != null) { + $transferEntity->sender_final_balance = $this->sender_new_balance; + + if(is_int($sender_id) && $sender_id > 0) { + $transferEntity->state_user_id = $sender_id; + $balance_result = $this->updateBalance($this->sender_new_balance, $received, $sender_id); + if(is_array($balance_result)) { + return $balance_result; + } + } + } + if($this->receiver_new_balance != null && is_int($receiver_id) && $receiver_id > 0) { + $transferEntity->receiver_user_id = $receiver_id; + $balance_result = $this->updateBalance($this->receiver_new_balance, $received, $receiver_id); + if(is_array($balance_result)) { + return $balance_result; + } + } + + if(!$transactionTransferTable->save($transferEntity)) { + return ['state' => 'error', 'msg' => 'error saving transaction send coins entity', 'details' => $transferEntity->getErrors()]; + } + + return true; + } + +} + + + + +class Record +{ + private $sequenceNumber = 0; + private $runningHash = null; + private $transactionType = ''; + private $memo = ''; + private $signatures = []; + private $received; + private $transactionObj = null; + private $result; + private $partCount = 0; + + public function __construct() + { + + } + + + public function parseRecord($json) { + if(!isset($json['record_type'])) { + return false; + } + //var_dump($json); + switch($json['record_type']) { + case 'GRADIDO_TRANSACTION': + return $this->parseTransaction($json['transaction']); + case 'MEMO': + $this->memo .= $json['memo']; + return true; + case 'SIGNATURES': + return $this->parseSignatures($json['signature']); + case 'STRUCTURALLY_BAD_MESSAGE': + case 'RAW_MESSAGE': + case 'BLANK': + return false; + } + } + + /*! + * \brief save data parts in db + */ + public function finalize() + { + $transactionTypesTable = TableRegistry::getTableLocator()->get('TransactionTypes'); + $transactionsTable = TableRegistry::getTableLocator()->get('Transactions'); + $stateUserTransactionsTable = TableRegistry::getTableLocator()->get('StateUserTransactions'); + + $transactionTypeName = $this->nodeTransactionTypeToDBTransactionType($this->transactionType); + $transactionTypeResults = $transactionTypesTable->find('all')->where(['name' => $transactionTypeName]); + if($transactionTypeResults->isEmpty()) { + return [ + 'state' => 'error', 'msg' => 'transaction type not found', + 'details' => ['nodeType' => $this->transactionType, 'dbType' => $transactionTypeName] + ]; + } + if(!$this->transactionObj) { + return ['state' => 'error', 'msg' => 'transaction obj is null']; + } + if($this->sequenceNumber <= 0) { + return ['state' => 'error', 'msg' => 'sequence number invalid', 'details' => $this->sequenceNumber]; + } + $transactionExistResult = $transactionsTable->find('all')->where(['id' => intval($this->sequenceNumber)]); + if(!$transactionExistResult->isEmpty()) { + return ['state' => 'warning', 'msg' => 'transaction already exist in db', 'details' => $this->sequenceNumber]; + } + $newTransaction = $transactionsTable->newEntity(); + $newTransaction->id = $this->sequenceNumber; + $newTransaction->transaction_type_id = $transactionTypeResults->first()->id; + $newTransaction->memo = $this->memo; + if($this->runningHash != '' && strlen($this->runningHash) % 2 == 0) { + $newTransaction->tx_hash = hex2bin($this->runningHash); + } + $newTransaction->received = $this->received; + + //! TODO change into transaction, if at least one fail, rollback + /* + // In a controller. + $articles->getConnection()->transactional(function () use ($articles, $entities) { + foreach ($entities as $entity) { + $articles->save($entity, ['atomic' => false]); + } + }); + */ + if(!$transactionsTable->save($newTransaction)) { + return ['state' => 'error', 'msg' => 'error saving transaction', 'details' => $newTransaction->getErrors()]; + } + + foreach($this->signatures as $sign) { + $sign_result = $sign->finalize($this->sequenceNumber); + if($sign_result !== true) { + return ['state' => 'error', 'msg', 'error finalizing signature', 'details' => $sign_result]; + } + } + $transaction_obj_result = $this->transactionObj->finalize($newTransaction->id, $this->received); + if($transaction_obj_result !== true) { + return ['state' => 'error', 'msg' => 'error finalizing transaction object', 'details' => $transaction_obj_result]; + } + $state_users = $this->transactionObj->getAllStateUsers(); + $sut_entities = []; + $state_user_balances = $this->transactionObj->getAllStateUserBalances(); + foreach($state_users as $state_user_id) { + $entity = $stateUserTransactionsTable->newEntity(); + $entity->state_user_id = $state_user_id; + $entity->transaction_id = $newTransaction->id; + $entity->transaction_type_id = $newTransaction->transaction_type_id; + $entity->balance = $state_user_balances[$state_user_id]->amount; + $entity->balance_date = $state_user_balances[$state_user_id]->record_date; + $sut_entities[] = $entity; + } + $sut_results = $stateUserTransactionsTable->saveMany($sut_entities); + foreach($sut_results as $i => $result) { + if(false == $result) { + return ['state' => 'error', 'msg' => 'error saving state_user_transaction', 'details' => $sut_entities[$i]->getErrors()]; + } + } + + return true; + + } + + private function nodeTransactionTypeToDBTransactionType($nodeTransactionType) + { + switch($nodeTransactionType) { + case 'GRADIDO_CREATION': + return 'creation'; + + case 'MOVE_USER_INBOUND': + case 'ADD_USER': + return 'group add member'; + + case 'MOVE_USER_OUTBOUND': + return 'group remove member'; + + case 'LOCAL_TRANSFER': + case 'INBOUND_TRANSFER': + case 'OUTBOUND_TRANSFER': + return 'transfer'; + } + return 'unknown'; + } + + private function parseSignatures($signaturesArray) + { + foreach($signaturesArray as $sign) { + $this->signatures[] = new Signature($sign['signature'], $sign['pubkey']); + } + return true; + } + + private function parseTransaction($data) + { + $this->transactionType = $data['transaction_type']; + $sign = $data['signature']; + $this->signatures[] = new Signature($sign['signature'], $sign['pubkey']); + + $hedera = $data['hedera_transaction']; + $this->sequenceNumber = $hedera['sequenceNumber']; + $this->runningHash = $hedera['runningHash']; + $this->received = Time::createFromTimestamp($hedera['consensusTimestamp']['seconds']); + + $field_index = ''; + $class_name = ''; + + $removeFromGroup = false; + switch($this->transactionType) + { + case 'GRADIDO_CREATION': $field_index = 'gradido_creation'; $class_name = 'GradidoCreation'; break; + case 'ADD_USER': $field_index = 'add_user'; $class_name = 'ManageNodeGroupAdd'; break; + case 'MOVE_USER_INBOUND': $field_index = 'move_user_inbound'; $class_name = 'ManageNodeGroupAdd'; break; + case 'MOVE_USER_OUTBOUND': $field_index = 'move_user_outbound'; $class_name = 'ManageNodeGroupAdd'; $removeFromGroup = true; break; + case 'LOCAL_TRANSFER': $field_index = 'local_transfer'; $class_name = 'GradidoTransfer'; break; + case 'INBOUND_TRANSFER': $field_index = 'inbound_transfer'; $class_name = 'GradidoTransfer'; break; + case 'OUTBOUND_TRANSFER': $field_index = 'outbound_transfer'; $class_name = 'GradidoTransfer'; break; + } + if($class_name == '' || $field_index == '') { + return ['state' => 'error', 'msg' => 'node transaction type unknown', 'details' => $this->transactionType]; + } + $class_name = 'Model\\Transactions\\' . $class_name; + $this->transactionObj = new $class_name($data[$field_index]); + if($class_name == 'ManageNodeGroupAdd') { + $this->transactionObj->setRemoveFromGroup($removeFromGroup); + } + + $this->result = $data['result']; + $this->partCount = intval($data['parts']); + $this->memo = $data['memo']; + return true; + } + + public function getSequenceNumber() { + return $this->sequenceNumber; + } + public function getPartCount() { + return $this->partCount; + } + } \ No newline at end of file diff --git a/community_server/src/Model/Transactions/Transaction.php b/community_server/src/Model/Transactions/Transaction.php index 76353595a..99bd5fae7 100644 --- a/community_server/src/Model/Transactions/Transaction.php +++ b/community_server/src/Model/Transactions/Transaction.php @@ -1,269 +1,269 @@ -mProtoTransaction = $base64Data; - $this->mTransactionBody = new TransactionBody($this->mProtoTransaction->getBodyBytes()); - return; - } - - try { - $transactionBin = sodium_base642bin($base64Data, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING); - } catch(\SodiumException $e) { - //$this->addError('Transaction', $e->getMessage());// . ' ' . $base64Data); - //return; - $transactionBin = base64_decode($base64Data, true); - if($transactionBin == false) { - $this->addError('Transaction', $e->getMessage());// . ' ' . $base64Data); - return; - } - } - //*/} - - if($transactionBin == false) { - //$this->addError('base64 decode failed'); - $this->addError('Transaction', 'base64 decode error: ' . $base64Data); - } else { - //var_dump($transactionBin); - $this->mProtoTransaction = new \Model\Messages\Gradido\Transaction(); - try { - $this->mProtoTransaction->mergeFromString($transactionBin); - //var_dump($this->mProtoTransaction); - // cannot catch Exception with cakePHP, I don't know why - } catch(\Google\Protobuf\Internal\GPBDecodeException $e) { - //var_dump($e); - $this->addError('Transaction', $e->getMessage()); - return; - }//*/ - - //echo 'serialize to json:
'; - //echo $this->mProtoTransaction->serializeToJsonString(); - //echo "body bytes:
"; - //var_dump($this->mProtoTransaction->getBodyBytes()); - //echo "
end body bytes
"; - $this->mTransactionBody = new TransactionBody($this->mProtoTransaction->getBodyBytes()); - } - } - - static public function build(\Model\Messages\Gradido\TransactionBody $transactionBody, $senderKeyPair) - { - $protoTransaction = new \Model\Messages\Gradido\Transaction(); - - $recevied = new \Model\Messages\Gradido\TimestampSeconds(); - $recevied->setSeconds(time()); - $protoTransaction->setReceived($recevied); - - $bodyBytes = $transactionBody->serializeToString(); - - $sigMap = SignatureMap::build($bodyBytes, [$senderKeyPair]); - $protoTransaction->setSigMap($sigMap->getProto()); - - $protoTransaction->setBodyBytes($bodyBytes); - - return $protoTransaction; - - } - - public function getTransactionBody() { - return $this->mTransactionBody; - } - - public function getFirstPublic() { - $sigPairs = $this->mProtoTransaction->getSigMap()->getSigPair(); - return $sigPairs[0]->getPubKey(); - } - - public function getId() { - return $this->mProtoTransaction->getId(); - } - - public function validate() { - $sigMap = $this->mProtoTransaction->getSigMap(); - if(!$sigMap) { - $this->addError('Transaction', 'signature map is zero'); - return false; - } - //var_dump($sigMap); - //die(); - $sigPairs = $sigMap->getSigPair(); - $bodyBytes = $this->mProtoTransaction->getBodyBytes(); - - - if(!$sigPairs || count($sigPairs) < 1) { - $this->addError('Transaction::validate', 'no signature found'); - return false; - } - - // check signature(s) - foreach($sigPairs as $sigPair) { - //echo 'sig Pair: '; var_dump($sigPair); echo "
"; - $pubkey = $sigPair->getPubKey(); - $signature = $sigPair->getEd25519(); - //echo "verify bodybytes:
" . bin2hex($bodyBytes) . '
'; - if (!\Sodium\crypto_sign_verify_detached($signature, $bodyBytes, $pubkey)) { - $this->addError('Transaction::validate', 'signature for key ' . bin2hex($pubkey) . ' isn\'t valid ' ); - return false; - } - } - - if(!$this->mTransactionBody->validate($sigPairs)) { - $this->addErrors($this->mTransactionBody->getErrors()); - return false; - } - - return true; - } - - public function save() - { - $connection = ConnectionManager::get('default'); - $connection->begin(); - //id transaction_id signature pubkey - - if (!$this->mTransactionBody->save($this->getFirstPublic(), $this->mProtoTransaction->getSigMap())) { - $this->addErrors($this->mTransactionBody->getErrors()); - $connection->rollback(); - return false; - } - - // save transaction signatures - $transactionsSignaturesTable = TableRegistry::getTableLocator()->get('transaction_signatures'); - $transactionId = $this->mTransactionBody->getTransactionID(); - //signature pubkey - - $sigPairs = $this->mProtoTransaction->getSigMap()->getSigPair(); - //echo "sigPairs: "; var_dump($sigPairs); - $signatureEntitys = []; - foreach($sigPairs as $sigPair) { - $signatureEntity = $transactionsSignaturesTable->newEntity(); - $signatureEntity->transaction_id = $transactionId; - $signatureEntity->signature = $sigPair->getEd25519(); - $signatureEntity->pubkey = $sigPair->getPubKey(); - array_push($signatureEntitys, $signatureEntity); - } - //debug($signatureEntitys); - if(!$transactionsSignaturesTable->saveMany($signatureEntitys)) { - foreach($signatureEntitys as $entity) { - $errors = $entity->getErrors(); - if(!$errors && count($errors) > 0) { - $pubkeyHex = bin2hex($entity->pubkey); - $this->addError('Transaction::save', 'error saving signature for pubkey: ' . $pubkeyHex . ', with errors: ' . json_encode($errors) ); - } - } - $connection->rollback(); - return false; - } - - $connection->commit(); - - $this->mTransactionBody->getSpecificTransaction()->sendNotificationEmail($this->mTransactionBody->getMemo()); - - return true; - } - - static public function fromTable($id) - { - $transactionsTable = TableRegistry::getTableLocator()->get('transactions'); - $transactionEntry = $transactionsTable - ->find('all') - ->where(['id' => $id]) - ->contain([ - 'TransactionCreations', - 'TransactionSendCoins', - 'TransactionSignatures']) - ->first(); - //var_dump($transactionEntry->toArray()); - $protoTransaction = new \Model\Messages\Gradido\Transaction(); - - - - $protoTransaction->setId($transactionEntry->id); - - - $recevied = new \Model\Messages\Gradido\TimestampSeconds(); - $recevied->setSeconds($transactionEntry->received->getTimestamp()); - $protoTransaction->setReceived($recevied); - - - $sigMap = SignatureMap::fromEntity($transactionEntry->transaction_signatures); - $protoTransaction->setSigMap($sigMap->getProto()); - - //echo "sig map: check
"; - $protoTransaction->setTxHash(stream_get_contents($transactionEntry->tx_hash)); - - $body = TransactionBody::fromEntity($transactionEntry->memo, $transactionEntry); - if(is_array($body)) { - return ['state' => 'error', 'msg' => 'error creating body transaction', 'details' => $body]; - } - - // validate signatures - $sigPairs = $sigMap->getProto()->getSigPair(); - - if(!$sigPairs || count($sigPairs) < 1) { - return ['state' => 'error', 'msg' => 'error no signatures found']; - } - - //echo "verify bodybytes:
" . bin2hex($bodyBytes) . '
'; - $created = new \Model\Messages\Gradido\TimestampSeconds(); - $created->setSeconds($recevied->getSeconds()); - $body->setCreated($created); - $bodyBytes = $body->serializeToString(); - $createTrys = 0; - $createRight = false; - // check signature(s) and - // try to get created field of TransactionBody right, because it wasn't saved - foreach($sigPairs as $sigPair) { - //echo 'sig Pair: '; var_dump($sigPair); echo "
"; - $pubkey = $sigPair->getPubKey(); - $signature = $sigPair->getEd25519(); - if(!$createRight) { - while($createTrys < 500) { - if(\Sodium\crypto_sign_verify_detached($signature, $bodyBytes, $pubkey)) { - $createRight = true; - break; - } else { - $createTrys++; - $created->setSeconds($created->getSeconds() - 1); - //$body->setCreated($created); - $bodyBytes = $body->serializeToString(); - } - } - } - - if (!\Sodium\crypto_sign_verify_detached($signature, $bodyBytes, $pubkey)) { - return ['state' => 'error', 'msg' => 'signature for key ' . bin2hex($pubkey) . ' isn\'t valid ']; - } - } - - $protoTransaction->setBodyBytes($bodyBytes); - - - - return $protoTransaction; - } - +mProtoTransaction = $base64Data; + $this->mTransactionBody = new TransactionBody($this->mProtoTransaction->getBodyBytes()); + return; + } + + try { + $transactionBin = sodium_base642bin($base64Data, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING); + } catch(\SodiumException $e) { + //$this->addError('Transaction', $e->getMessage());// . ' ' . $base64Data); + //return; + $transactionBin = base64_decode($base64Data, true); + if($transactionBin == false) { + $this->addError('Transaction', $e->getMessage());// . ' ' . $base64Data); + return; + } + } + //*/} + + if($transactionBin == false) { + //$this->addError('base64 decode failed'); + $this->addError('Transaction', 'base64 decode error: ' . $base64Data); + } else { + //var_dump($transactionBin); + $this->mProtoTransaction = new \Model\Messages\Gradido\Transaction(); + try { + $this->mProtoTransaction->mergeFromString($transactionBin); + //var_dump($this->mProtoTransaction); + // cannot catch Exception with cakePHP, I don't know why + } catch(\Google\Protobuf\Internal\GPBDecodeException $e) { + //var_dump($e); + $this->addError('Transaction', $e->getMessage()); + return; + }//*/ + + //echo 'serialize to json:
'; + //echo $this->mProtoTransaction->serializeToJsonString(); + //echo "body bytes:
"; + //var_dump($this->mProtoTransaction->getBodyBytes()); + //echo "
end body bytes
"; + $this->mTransactionBody = new TransactionBody($this->mProtoTransaction->getBodyBytes()); + } + } + + static public function build(\Model\Messages\Gradido\TransactionBody $transactionBody, $senderKeyPair) + { + $protoTransaction = new \Model\Messages\Gradido\Transaction(); + + $recevied = new \Model\Messages\Gradido\TimestampSeconds(); + $recevied->setSeconds(time()); + $protoTransaction->setReceived($recevied); + + $bodyBytes = $transactionBody->serializeToString(); + + $sigMap = SignatureMap::build($bodyBytes, [$senderKeyPair]); + $protoTransaction->setSigMap($sigMap->getProto()); + + $protoTransaction->setBodyBytes($bodyBytes); + + return $protoTransaction; + + } + + public function getTransactionBody() { + return $this->mTransactionBody; + } + + public function getFirstPublic() { + $sigPairs = $this->mProtoTransaction->getSigMap()->getSigPair(); + return $sigPairs[0]->getPubKey(); + } + + public function getId() { + return $this->mProtoTransaction->getId(); + } + + public function validate() { + $sigMap = $this->mProtoTransaction->getSigMap(); + if(!$sigMap) { + $this->addError('Transaction', 'signature map is zero'); + return false; + } + //var_dump($sigMap); + //die(); + $sigPairs = $sigMap->getSigPair(); + $bodyBytes = $this->mProtoTransaction->getBodyBytes(); + + + if(!$sigPairs || count($sigPairs) < 1) { + $this->addError('Transaction::validate', 'no signature found'); + return false; + } + + // check signature(s) + foreach($sigPairs as $sigPair) { + //echo 'sig Pair: '; var_dump($sigPair); echo "
"; + $pubkey = $sigPair->getPubKey(); + $signature = $sigPair->getEd25519(); + //echo "verify bodybytes:
" . bin2hex($bodyBytes) . '
'; + if (!\Sodium\crypto_sign_verify_detached($signature, $bodyBytes, $pubkey)) { + $this->addError('Transaction::validate', 'signature for key ' . bin2hex($pubkey) . ' isn\'t valid ' ); + return false; + } + } + + if(!$this->mTransactionBody->validate($sigPairs)) { + $this->addErrors($this->mTransactionBody->getErrors()); + return false; + } + + return true; + } + + public function save() + { + $connection = ConnectionManager::get('default'); + $connection->begin(); + //id transaction_id signature pubkey + + if (!$this->mTransactionBody->save($this->getFirstPublic(), $this->mProtoTransaction->getSigMap())) { + $this->addErrors($this->mTransactionBody->getErrors()); + $connection->rollback(); + return false; + } + + // save transaction signatures + $transactionsSignaturesTable = TableRegistry::getTableLocator()->get('transaction_signatures'); + $transactionId = $this->mTransactionBody->getTransactionID(); + //signature pubkey + + $sigPairs = $this->mProtoTransaction->getSigMap()->getSigPair(); + //echo "sigPairs: "; var_dump($sigPairs); + $signatureEntitys = []; + foreach($sigPairs as $sigPair) { + $signatureEntity = $transactionsSignaturesTable->newEntity(); + $signatureEntity->transaction_id = $transactionId; + $signatureEntity->signature = $sigPair->getEd25519(); + $signatureEntity->pubkey = $sigPair->getPubKey(); + array_push($signatureEntitys, $signatureEntity); + } + //debug($signatureEntitys); + if(!$transactionsSignaturesTable->saveMany($signatureEntitys)) { + foreach($signatureEntitys as $entity) { + $errors = $entity->getErrors(); + if(!$errors && count($errors) > 0) { + $pubkeyHex = bin2hex($entity->pubkey); + $this->addError('Transaction::save', 'error saving signature for pubkey: ' . $pubkeyHex . ', with errors: ' . json_encode($errors) ); + } + } + $connection->rollback(); + return false; + } + + $connection->commit(); + + $this->mTransactionBody->getSpecificTransaction()->sendNotificationEmail($this->mTransactionBody->getMemo()); + + return true; + } + + static public function fromTable($id) + { + $transactionsTable = TableRegistry::getTableLocator()->get('transactions'); + $transactionEntry = $transactionsTable + ->find('all') + ->where(['id' => $id]) + ->contain([ + 'TransactionCreations', + 'TransactionSendCoins', + 'TransactionSignatures']) + ->first(); + //var_dump($transactionEntry->toArray()); + $protoTransaction = new \Model\Messages\Gradido\Transaction(); + + + + $protoTransaction->setId($transactionEntry->id); + + + $recevied = new \Model\Messages\Gradido\TimestampSeconds(); + $recevied->setSeconds($transactionEntry->received->getTimestamp()); + $protoTransaction->setReceived($recevied); + + + $sigMap = SignatureMap::fromEntity($transactionEntry->transaction_signatures); + $protoTransaction->setSigMap($sigMap->getProto()); + + //echo "sig map: check
"; + $protoTransaction->setTxHash(stream_get_contents($transactionEntry->tx_hash)); + + $body = TransactionBody::fromEntity($transactionEntry->memo, $transactionEntry); + if(is_array($body)) { + return ['state' => 'error', 'msg' => 'error creating body transaction', 'details' => $body]; + } + + // validate signatures + $sigPairs = $sigMap->getProto()->getSigPair(); + + if(!$sigPairs || count($sigPairs) < 1) { + return ['state' => 'error', 'msg' => 'error no signatures found']; + } + + //echo "verify bodybytes:
" . bin2hex($bodyBytes) . '
'; + $created = new \Model\Messages\Gradido\TimestampSeconds(); + $created->setSeconds($recevied->getSeconds()); + $body->setCreated($created); + $bodyBytes = $body->serializeToString(); + $createTrys = 0; + $createRight = false; + // check signature(s) and + // try to get created field of TransactionBody right, because it wasn't saved + foreach($sigPairs as $sigPair) { + //echo 'sig Pair: '; var_dump($sigPair); echo "
"; + $pubkey = $sigPair->getPubKey(); + $signature = $sigPair->getEd25519(); + if(!$createRight) { + while($createTrys < 500) { + if(\Sodium\crypto_sign_verify_detached($signature, $bodyBytes, $pubkey)) { + $createRight = true; + break; + } else { + $createTrys++; + $created->setSeconds($created->getSeconds() - 1); + //$body->setCreated($created); + $bodyBytes = $body->serializeToString(); + } + } + } + + if (!\Sodium\crypto_sign_verify_detached($signature, $bodyBytes, $pubkey)) { + return ['state' => 'error', 'msg' => 'signature for key ' . bin2hex($pubkey) . ' isn\'t valid ']; + } + } + + $protoTransaction->setBodyBytes($bodyBytes); + + + + return $protoTransaction; + } + } \ No newline at end of file diff --git a/community_server/src/Model/Transactions/TransactionBase.php b/community_server/src/Model/Transactions/TransactionBase.php index 80ce8ef5d..31a26f2ee 100644 --- a/community_server/src/Model/Transactions/TransactionBase.php +++ b/community_server/src/Model/Transactions/TransactionBase.php @@ -1,122 +1,122 @@ -errors; - } - - public function addError($functionName, $errorName) { - array_push($this->errors, [$functionName => $errorName]); - } - - public function addErrors($errors) { - $this->errors = array_merge($this->errors, $errors); - } - - public function hasErrors() { - return count($this->errors) > 0; - } - - public static function getTable($tableName) { - if(!isset(self::$tables[$tableName])) { - self::$tables[$tableName] = TableRegistry::getTableLocator()->get($tableName); - } - return self::$tables[$tableName]; - } - - - protected function getStateUserId($publicKey) { - - $stateUsersTable = self::getTable('state_users'); - $stateUser = $stateUsersTable->find('all')->select(['id'])->where(['public_key' => $publicKey])->first(); - if($stateUser) { - return $stateUser->id; - } - // create new entry - $stateUserEntity = $stateUsersTable->newEntity(); - $stateUserEntity->public_key = $publicKey; - if($stateUsersTable->save($stateUserEntity)) { - return $stateUserEntity->id; - } else { - $this->addError('TransactionBase::getStateUserId', 'error saving new state user with error: ' . json_encode($stateUserEntity->getErrors())); - } - - return NULL; - } - - protected function getStateUser($id) { - $stateUsersTable = self::getTable('state_users'); - $stateUser = $stateUsersTable->get($id); - if($stateUser) { - return $stateUser; - } - - return NULL; - } - - - protected function updateStateBalance($stateUserId, $addAmountCent, $recordDate) { - $finalBalance = 0; - $stateBalancesTable = self::getTable('stateBalances'); - $stateBalanceQuery = $stateBalancesTable - ->find('all') - ->select(['amount', 'id']) - ->contain(false) - ->where(['state_user_id' => $stateUserId]);//->first(); - //debug($stateBalanceQuery); - - if($stateBalanceQuery->count() > 0) { - $stateBalanceEntry = $stateBalanceQuery->first(); - $stateBalanceEntry->amount = $stateBalanceEntry->partDecay($recordDate) + $addAmountCent; - $stateBalanceEntry->amount += $addAmountCent; - } else { - $stateBalanceEntry = $stateBalancesTable->newEntity(); - $stateBalanceEntry->state_user_id = $stateUserId; - $stateBalanceEntry->amount = $addAmountCent; - } - $stateBalanceEntry->record_date = $recordDate; - $finalBalance = $stateBalanceEntry->amount; - //echo "\ntry to save: "; var_dump($stateBalanceEntry); echo "\n"; - if(!$stateBalancesTable->save($stateBalanceEntry)) { - $errors = $stateBalanceEntry->getErrors(); - $this->addError('TransactionBase::updateStateBalance', 'error saving state balance with: ' . json_encode($errors)); - return false; - } - return $finalBalance; - } - - protected function addStateUserTransaction($stateUserId, $transactionId, $transactionTypeId, $balance) { - $stateUserTransactionTable = self::getTable('state_user_transactions'); - $stateUserTransactions = $stateUserTransactionTable - ->find('all') - ->where(['state_user_id' => $stateUserId]) - ->order(['transaction_id DESC']); - - if($stateUserTransactions->count() > 0) { - $stateBalanceTable = self::getTable('state_balances'); - $balance_entity = $stateBalanceTable->newEntity(); - $balance_entity->amount = $stateUserTransactions->first()->balance; - $balance_entity->record_date = $stateUserTransactions->first()->balance_date; - $balance = $balance_entity->decay + $balance; - } - $entity = $stateUserTransactionTable->newEntity(); - $entity->state_user_id = $stateUserId; - $entity->transaction_id = $transactionId; - $entity->transaction_type_id = $transactionTypeId; - $entity->balance = $balance; - - if(!$stateUserTransactionTable->save($entity)) { - $errors = $entity->getErrors(); - $this->addError('TransactionBase::addStateUserTransaction', 'error saving state user balance with: ' . json_encode($errors)); - return false; - } - return true; - } +errors; + } + + public function addError($functionName, $errorName) { + array_push($this->errors, [$functionName => $errorName]); + } + + public function addErrors($errors) { + $this->errors = array_merge($this->errors, $errors); + } + + public function hasErrors() { + return count($this->errors) > 0; + } + + public static function getTable($tableName) { + if(!isset(self::$tables[$tableName])) { + self::$tables[$tableName] = TableRegistry::getTableLocator()->get($tableName); + } + return self::$tables[$tableName]; + } + + + protected function getStateUserId($publicKey) { + + $stateUsersTable = self::getTable('state_users'); + $stateUser = $stateUsersTable->find('all')->select(['id'])->where(['public_key' => $publicKey])->first(); + if($stateUser) { + return $stateUser->id; + } + // create new entry + $stateUserEntity = $stateUsersTable->newEntity(); + $stateUserEntity->public_key = $publicKey; + if($stateUsersTable->save($stateUserEntity)) { + return $stateUserEntity->id; + } else { + $this->addError('TransactionBase::getStateUserId', 'error saving new state user with error: ' . json_encode($stateUserEntity->getErrors())); + } + + return NULL; + } + + protected function getStateUser($id) { + $stateUsersTable = self::getTable('state_users'); + $stateUser = $stateUsersTable->get($id); + if($stateUser) { + return $stateUser; + } + + return NULL; + } + + + protected function updateStateBalance($stateUserId, $addAmountCent, $recordDate) { + $finalBalance = 0; + $stateBalancesTable = self::getTable('stateBalances'); + $stateBalanceQuery = $stateBalancesTable + ->find('all') + ->select(['amount', 'id']) + ->contain(false) + ->where(['state_user_id' => $stateUserId]);//->first(); + //debug($stateBalanceQuery); + + if($stateBalanceQuery->count() > 0) { + $stateBalanceEntry = $stateBalanceQuery->first(); + $stateBalanceEntry->amount = $stateBalanceEntry->partDecay($recordDate) + $addAmountCent; + $stateBalanceEntry->amount += $addAmountCent; + } else { + $stateBalanceEntry = $stateBalancesTable->newEntity(); + $stateBalanceEntry->state_user_id = $stateUserId; + $stateBalanceEntry->amount = $addAmountCent; + } + $stateBalanceEntry->record_date = $recordDate; + $finalBalance = $stateBalanceEntry->amount; + //echo "\ntry to save: "; var_dump($stateBalanceEntry); echo "\n"; + if(!$stateBalancesTable->save($stateBalanceEntry)) { + $errors = $stateBalanceEntry->getErrors(); + $this->addError('TransactionBase::updateStateBalance', 'error saving state balance with: ' . json_encode($errors)); + return false; + } + return $finalBalance; + } + + protected function addStateUserTransaction($stateUserId, $transactionId, $transactionTypeId, $balance) { + $stateUserTransactionTable = self::getTable('state_user_transactions'); + $stateUserTransactions = $stateUserTransactionTable + ->find('all') + ->where(['state_user_id' => $stateUserId]) + ->order(['transaction_id DESC']); + + if($stateUserTransactions->count() > 0) { + $stateBalanceTable = self::getTable('state_balances'); + $balance_entity = $stateBalanceTable->newEntity(); + $balance_entity->amount = $stateUserTransactions->first()->balance; + $balance_entity->record_date = $stateUserTransactions->first()->balance_date; + $balance = $balance_entity->decay + $balance; + } + $entity = $stateUserTransactionTable->newEntity(); + $entity->state_user_id = $stateUserId; + $entity->transaction_id = $transactionId; + $entity->transaction_type_id = $transactionTypeId; + $entity->balance = $balance; + + if(!$stateUserTransactionTable->save($entity)) { + $errors = $entity->getErrors(); + $this->addError('TransactionBase::addStateUserTransaction', 'error saving state user balance with: ' . json_encode($errors)); + return false; + } + return true; + } } \ No newline at end of file diff --git a/community_server/tests/TestCase/Controller/AppControllerTest.php b/community_server/tests/TestCase/Controller/AppControllerTest.php index 79294cbe0..502ed46da 100644 --- a/community_server/tests/TestCase/Controller/AppControllerTest.php +++ b/community_server/tests/TestCase/Controller/AppControllerTest.php @@ -1,46 +1,46 @@ -session(['StateUser.id' => 1]); - $this->get('/'); - $this->assertSession(1200, 'StateUser.balance'); - //$this->markTestIncomplete('Not implemented yet.'); - } - - -} +session(['StateUser.id' => 1]); + $this->get('/'); + $this->assertSession(1200, 'StateUser.balance'); + //$this->markTestIncomplete('Not implemented yet.'); + } + + +} diff --git a/gn b/gn index a61871987..5437e2f88 160000 --- a/gn +++ b/gn @@ -1 +1 @@ -Subproject commit a61871987261614102b11ed58791081be1954d3c +Subproject commit 5437e2f882c54efe4f501f7cd0d97f53806d0b74 diff --git a/login_server/src/cpp/Gradido_LoginServer.h b/login_server/src/cpp/Gradido_LoginServer.h index 98c3c882c..0a14d9000 100644 --- a/login_server/src/cpp/Gradido_LoginServer.h +++ b/login_server/src/cpp/Gradido_LoginServer.h @@ -1,42 +1,42 @@ -#ifndef Gradido_LoginServer_INCLUDED -#define Gradido_LoginServer_INCLUDED - -#include "Poco/Util/ServerApplication.h" - -class Gradido_LoginServer : public Poco::Util::ServerApplication -{ - - /// The main application class. - /// - /// This class handles command-line arguments and - /// configuration files. - /// Start the Gradido_LoginServer executable with the help - /// option (/help on Windows, --help on Unix) for - /// the available command line options. - /// - - -public: - Gradido_LoginServer(); - ~Gradido_LoginServer(); - -protected: - void initialize(Application& self); - - void uninitialize(); - - void defineOptions(Poco::Util::OptionSet& options); - - void handleOption(const std::string& name, const std::string& value); - void displayHelp(); - - int main(const std::vector& args); - - void createConsoleFileAsyncLogger(std::string name, std::string filePath); - -private: - bool _helpRequested; - std::string mConfigPath; -}; - -#endif //Gradido_LoginServer_INCLUDED +#ifndef Gradido_LoginServer_INCLUDED +#define Gradido_LoginServer_INCLUDED + +#include "Poco/Util/ServerApplication.h" + +class Gradido_LoginServer : public Poco::Util::ServerApplication +{ + + /// The main application class. + /// + /// This class handles command-line arguments and + /// configuration files. + /// Start the Gradido_LoginServer executable with the help + /// option (/help on Windows, --help on Unix) for + /// the available command line options. + /// + + +public: + Gradido_LoginServer(); + ~Gradido_LoginServer(); + +protected: + void initialize(Application& self); + + void uninitialize(); + + void defineOptions(Poco::Util::OptionSet& options); + + void handleOption(const std::string& name, const std::string& value); + void displayHelp(); + + int main(const std::vector& args); + + void createConsoleFileAsyncLogger(std::string name, std::string filePath); + +private: + bool _helpRequested; + std::string mConfigPath; +}; + +#endif //Gradido_LoginServer_INCLUDED diff --git a/login_server/src/cpp/HTTPInterface/AdminNodeServerTestPage.cpp b/login_server/src/cpp/HTTPInterface/AdminNodeServerTestPage.cpp index 84c63a508..b5d943d6a 100644 --- a/login_server/src/cpp/HTTPInterface/AdminNodeServerTestPage.cpp +++ b/login_server/src/cpp/HTTPInterface/AdminNodeServerTestPage.cpp @@ -1,866 +1,866 @@ -#include "AdminNodeServerTestPage.h" -#include "Poco/Net/HTTPServerRequest.h" -#include "Poco/Net/HTTPServerResponse.h" -#include "Poco/Net/HTMLForm.h" -#include "Poco/DeflatingStream.h" - - -#line 6 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - -#include "../controller/NodeServer.h" -#include "../controller/User.h" -#include "../controller/HederaTopic.h" -#include "../lib/DataTypeConverter.h" -#include "../lib/Profiler.h" -#include "../lib/JsonRPCRequest.h" -#include "../model/gradido/Transaction.h" - -#include "Poco/Thread.h" -#include "Poco/DateTime.h" -#include "Poco/JSON/Stringifier.h" - -enum PageType -{ - PAGE_CHOOSE_TEST, - PAGE_RUN_4_SET_TEST, - PAGE_GET_TRANSACTION_RPC_CALL -}; - -#line 1 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" - -#include "../ServerConfig.h" - - -void AdminNodeServerTestPage::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) -{ - response.setChunkedTransferEncoding(true); - response.setContentType("text/html"); - bool _compressResponse(request.hasToken("Accept-Encoding", "gzip")); - if (_compressResponse) response.set("Content-Encoding", "gzip"); - - Poco::Net::HTMLForm form(request, request.stream()); -#line 28 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - const char* pageName = "Node Server Test"; - PageType page = PAGE_CHOOSE_TEST; - Poco::AutoPtr node_server; - Poco::AutoPtr node_server2; - Poco::AutoPtr user; - Poco::AutoPtr hedera_topic; - Poco::AutoPtr hedera_topic2; - int hedera_timeout = 4; - int sleep_ms_between_transactions = 1000; - - bool steps[8]; memset(steps, 1, 8 * sizeof(bool)); - - - if(!form.empty()) - { - auto node_server_id_string = form.get("test-node-servers", ""); - if(node_server_id_string != "") { - int node_server_id = 0; - if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(node_server_id_string, node_server_id )) { - node_server = controller::NodeServer::load(node_server_id); - } - } - node_server_id_string = form.get("test-node-servers2", ""); - if(node_server_id_string != "") { - int node_server_id = 0; - if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(node_server_id_string, node_server_id )) { - node_server2 = controller::NodeServer::load(node_server_id); - } - } - auto topic_id_string = form.get("test-hedera-topic", ""); - if(topic_id_string != "") { - int topic_id = 0; - if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(topic_id_string, topic_id)) { - hedera_topic = controller::HederaTopic::load(topic_id); - } - } - topic_id_string = form.get("test-hedera-topic2", ""); - if(topic_id_string != "") { - int topic_id = 0; - if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(topic_id_string, topic_id)) { - hedera_topic2 = controller::HederaTopic::load(topic_id); - } - } - auto test_timeout_string = form.get("test-timeout", ""); - if(test_timeout_string != "") { - DataTypeConverter::strToInt(test_timeout_string, hedera_timeout); - } - auto test_part_timeout_string = form.get("test-part-timeout", ""); - if(test_part_timeout_string != "") { - DataTypeConverter::strToInt(test_part_timeout_string, sleep_ms_between_transactions); - } - auto submit = form.get("submit", ""); - if(submit == "Run 6-Test") { - page = PAGE_RUN_4_SET_TEST; - } else if(submit == "json-rpc getTransactions") { - page = PAGE_GET_TRANSACTION_RPC_CALL; - } - std::string step_temp; - for(int i = 0; i < 8; i++) { - std::string name = "step-"; - name += std::to_string(i+2); - step_temp = form.get(name, ""); - if(step_temp == "1") { - steps[i] = true; - } else { - steps[i] = false; - } - } - } - - auto node_servers = controller::NodeServer::load(model::table::NODE_SERVER_GRADIDO_NODE); - auto hedera_topics = controller::HederaTopic::listAll(); - -#line 3 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" - - bool withMaterialIcons = false; - std::ostream& _responseStream = response.send(); - Poco::DeflatingOutputStream _gzipStream(_responseStream, Poco::DeflatingStreamBuf::STREAM_GZIP, 1); - std::ostream& responseStream = _compressResponse ? _gzipStream : _responseStream; - responseStream << "\n"; - // begin include header_large.cpsp - responseStream << "\n"; - responseStream << "\n"; - responseStream << "\n"; - responseStream << "\n"; - responseStream << "\n"; - responseStream << "\n"; - responseStream << "Gradido Login Server: "; -#line 11 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" - responseStream << ( pageName ); - responseStream << "\n"; - responseStream << "\n"; -#line 13 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" - if(withMaterialIcons) { responseStream << "\n"; - responseStream << "\n"; -#line 15 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" - } responseStream << "\n"; - responseStream << "\n"; - responseStream << "\n"; - responseStream << "
\n"; - responseStream << "\t\t
\n"; - responseStream << "\t\t\t
\n"; - responseStream << "\t\t\t\t
    \n"; - responseStream << "\t\t\t\t\t"; -#line 22 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" - if(!user.isNull()) { responseStream << "\n"; - responseStream << "\t\t\t\t\t\t
  • getGroupBaseUrl() ); - responseStream << "/\">Startseite
  • \n"; - responseStream << "\t\t\t\t\t"; -#line 24 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t\t\t
  • Gruppen
  • \n"; - responseStream << "\t\t\t\t\t
  • Node Server
  • \n"; - responseStream << "\t\t\t\t\t
  • Hedera Accounts
  • \n"; - responseStream << "\t\t\t\t\t
  • Hedera Topics
  • \n"; - responseStream << "\t\t\t\t
\n"; - responseStream << "\t\t\t
\n"; - responseStream << "\t\t
\n"; - responseStream << "\t\t
"; - // end include header_large.cpsp - responseStream << "\n"; -#line 103 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( getErrorsHtml() ); - responseStream << "\n"; - responseStream << "
\n"; - responseStream << "\t\n"; - responseStream << "\t
\n"; - responseStream << "\t \n"; - responseStream << "\t \n"; - responseStream << "\t
\n"; - responseStream << "\t
\n"; - responseStream << "\t\t
\n"; - responseStream << "\t\t\t

Test 6-Set (3 AddMember, Creation, 2 Transfer)\n"; - responseStream << "\t\t

\n"; - responseStream << "\t\t
\n"; - responseStream << "\t\t\t
\n"; - responseStream << "\t\t\t\t

1. Create three new accounts and show user public keys for comparisation

\n"; - responseStream << "\t\t\t\t

2. Send a add-member transaction to hedera topic with one signature (first user)

\n"; - responseStream << "\t\t\t\t

3. Send a add-member transaction to hedera topic with two signatures (first user and second user)

\n"; - responseStream << "\t\t\t\t

4. Send a creation transaction to second user, signed by first user

\n"; - responseStream << "\t\t\t\t

5. Send a transfer transaction from second user to first user signed by second user

\n"; - responseStream << "\t\t\t\t

6. Send a add-member transaction to hedera topic 2 with one signature (third user)

\n"; - responseStream << "\t\t\t\t

7. Send a cross group transfer from second user to third user signed by second user

\n"; - responseStream << "\t\t\t\t

8. Wait x seconds to give hedera time to process transactions

\n"; - responseStream << "\t\t\t\t

9. Ask choosen node for transaction and print result

\n"; - responseStream << "\t\t\t\t
\n"; - responseStream << "\t\t\t\t\tGroup 1 \n"; - responseStream << "\t\t\t\t\t\n"; - responseStream << "\t\t\t\t\t"; -#line 128 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - if(node_servers.size() == 0) { responseStream << "\n"; - responseStream << "\t\t\t\t\t\tEdit Node-Servers\n"; - responseStream << "\t\t\t\t\t"; -#line 130 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t\t\t\n"; - responseStream << "\t\t\t\t\t\n"; - responseStream << "\t\t\t\t\t"; -#line 139 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - if(hedera_topics.size() == 0) { responseStream << "\n"; - responseStream << "\t\t\t\t\t\tEdit Hedera-Topics\n"; - responseStream << "\t\t\t\t\t"; -#line 141 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t\t\t\n"; - responseStream << "\t\t\t\t
\n"; - responseStream << "\t\t\t\t
\n"; - responseStream << "\t\t\t\t\tGroup 2 \n"; - responseStream << "\t\t\t\t\t\n"; - responseStream << "\t\t\t\t\t"; -#line 157 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - if(node_servers.size() == 0) { responseStream << "\n"; - responseStream << "\t\t\t\t\t\tEdit Node-Servers\n"; - responseStream << "\t\t\t\t\t"; -#line 159 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t\t\t\n"; - responseStream << "\t\t\t\t\t\n"; - responseStream << "\t\t\t\t\t"; -#line 168 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - if(hedera_topics.size() == 0) { responseStream << "\n"; - responseStream << "\t\t\t\t\t\tEdit Hedera-Topics\n"; - responseStream << "\t\t\t\t\t"; -#line 170 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t\t\t\n"; - responseStream << "\t\t\t\t
\n"; - responseStream << "\t\t\t\t\n"; - responseStream << "\t\t\t\t\n"; - responseStream << "\t\t\t\t seconds \n"; - responseStream << "\t\t\t\t\n"; - responseStream << "\t\t\t\t ms\n"; - responseStream << "\t\t\t\t\n"; - responseStream << "\t\t\t
\n"; - responseStream << "\t\t
\n"; - responseStream << "\t
\n"; - responseStream << "\t
\n"; - responseStream << "\t\t
\n"; - responseStream << "\t\t\t

Test 4-Set (2 AddMember, Creation, Transfer)\n"; - responseStream << "\t\t

\n"; - responseStream << "\t\t
\n"; - responseStream << "\t\t\t
\n"; - responseStream << "\t\t\t\t\n"; - responseStream << "\t\t\t\t"; -#line 199 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - if(node_servers.size() == 0) { responseStream << "\n"; - responseStream << "\t\t\t\t\tEdit Node-Servers\n"; - responseStream << "\t\t\t\t"; -#line 201 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t\t\n"; - responseStream << "\t\t\t\t\n"; - responseStream << "\t\t\t
\n"; - responseStream << "\t\t
\n"; - responseStream << "\t
\n"; - responseStream << "\t"; -#line 213 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - if(PAGE_RUN_4_SET_TEST == page && !hedera_topic.isNull() && !node_server.isNull()) { responseStream << "\n"; - responseStream << "\t
    \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    1. Create three new accounts and show user public keys for comparisation:

    \n"; - responseStream << "\t\t\t"; -#line 217 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - Profiler time2; - auto group_id = hedera_topic->getModel()->getGroupId(); - auto group_id2 = hedera_topic2->getModel()->getGroupId(); - auto user_group = controller::Group::load(group_id); - auto user_group2 = controller::Group::load(group_id2); - auto mnemonic_type = ServerConfig::MNEMONIC_BIP0039_SORTED_ORDER; - - std::string password1 = "hsaj(2askaslASlllak3wjjeudsaj"; - auto user_1 = controller::User::create("testEmail@google.de", "Max", "Mustermann", group_id); - auto passphrase_1 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); - auto gradido_key_pair_1 = KeyPairEd25519::create(passphrase_1); - user_1->setGradidoKeyPair(gradido_key_pair_1); - user_1->login(password1); - - std::string password2 = "uweia8saiSale,dsasA"; - auto user_2 = controller::User::create("testEmail2@google.de", "MJax", "Mustrermann", group_id); - auto passphrase_2 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); - auto gradido_key_pair_2 = KeyPairEd25519::create(passphrase_2); - user_2->setGradidoKeyPair(gradido_key_pair_2); - user_2->login(password2); - - std::string password3 = "jaue_skaiellasealaK"; - auto user_3 = controller::User::create("testEmail3@gmail.com", "Morpheus", "Miaufull", group_id2); - auto passphrase_3 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); - auto gradido_key_pair_3 = KeyPairEd25519::create(passphrase_3); - user_3->setGradidoKeyPair(gradido_key_pair_3); - user_3->login(password3); - responseStream << "\t\t\t\n"; - responseStream << "\t\t\t
    "; -#line 246 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( user_group->getModel()->getName() ); - responseStream << "\n"; - responseStream << "\t\t\t\t

    User 1: "; -#line 247 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( user_1->getPublicHex() ); - responseStream << "

    \n"; - responseStream << "\t\t\t\t

    User 2: "; -#line 248 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( user_2->getPublicHex() ); - responseStream << "

    \n"; - responseStream << "\t\t\t
    \n"; - responseStream << "\t\t\t
    "; -#line 250 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( user_group2->getModel()->getName() ); - responseStream << "\n"; - responseStream << "\t\t\t\t

    User 3: "; -#line 251 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( user_3->getPublicHex() ); - responseStream << "

    \n"; - responseStream << "\t\t\t
    \n"; - responseStream << "\t\t\t

    Time: "; -#line 253 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time2.string() ); - responseStream << "\n"; - responseStream << "\t\t

  • \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    2. Send a add-member transaction to hedera topic with one signature (first user)

    \n"; - responseStream << "\t\t\t"; -#line 257 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - time2.reset(); - if(!steps[0]) { responseStream << "\n"; - responseStream << "\t\t\t\t

    skipped

    \n"; - responseStream << "\t\t\t"; -#line 261 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else { - auto transaction1 = model::gradido::Transaction::createGroupMemberUpdate(user_1, user_group); - transaction1->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(1); - transaction1->sign(user_1); - auto transaction1_json = transaction1->getTransactionAsJson(true); - responseStream << "\n"; - responseStream << "\t\t\t

    "; -#line 267 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction1_json) ); - responseStream << "

    \n"; - responseStream << "\t\t\t"; -#line 268 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t

    Time: "; -#line 269 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time2.string() ); - responseStream << "\n"; - responseStream << "\t\t

  • \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    3. Send a add-member transaction to hedera topic with two signatures (first user and second user)

    \n"; - responseStream << "\t\t\t"; -#line 273 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - time2.reset(); - if(!steps[1]) { responseStream << "\n"; - responseStream << "\t\t\t\t

    skipped

    \n"; - responseStream << "\t\t\t"; -#line 277 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else { - auto transaction2 = model::gradido::Transaction::createGroupMemberUpdate(user_2, user_group); - transaction2->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(2); - transaction2->sign(user_2); - // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction2->sign(user_1); - auto transaction2_json = transaction2->getTransactionAsJson(true); - responseStream << "\n"; - responseStream << "\t\t\t

    "; -#line 286 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction2_json) ); - responseStream << "

    \n"; - responseStream << "\t\t\t"; -#line 287 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t

    Time: "; -#line 288 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time2.string() ); - responseStream << "\n"; - responseStream << "\t\t

  • \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    4. Send a creation transaction to second user, signed by first user

    \n"; - responseStream << "\t\t\t"; -#line 292 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - time2.reset(); - if(!steps[2]) { responseStream << "\n"; - responseStream << "\t\t\t\t

    skipped

    \n"; - responseStream << "\t\t\t"; -#line 296 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else { - auto transaction3 = model::gradido::Transaction::createCreation(user_2, 10000000, Poco::DateTime(), "Test Creation"); - // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction3->sign(user_1); - auto transaction3_json = transaction3->getTransactionAsJson(true); - responseStream << "\n"; - responseStream << "\t\t\t

    "; -#line 303 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction3_json) ); - responseStream << "

    \n"; - responseStream << "\t\t\t"; -#line 304 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t

    Time: "; -#line 305 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time2.string() ); - responseStream << "

    \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    5. Send a transfer transaction from second user to first user signed by second user

    \n"; - responseStream << "\t\t\t"; -#line 309 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - time2.reset(); - if(!steps[3]) { responseStream << "\n"; - responseStream << "\t\t\t\t

    skipped

    \n"; - responseStream << "\t\t\t"; -#line 313 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else { - auto user_1_pubkey = user_1->getModel()->getPublicKeyCopy(); - auto transaction4 = model::gradido::Transaction::createTransfer(user_2, user_1_pubkey, user_group, 5000000, "Test Transfer"); - // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction4[0]->sign(user_2); - auto transaction4_json = transaction4[0]->getTransactionAsJson(true); - responseStream << "\n"; - responseStream << "\t\t\t

    "; -#line 321 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction4_json) ); - responseStream << "

    \n"; - responseStream << "\t\t\t"; -#line 322 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t

    Time: "; -#line 323 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time2.string() ); - responseStream << "

    \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    6. Send a add-member transaction to hedera topic 2 with one signature (third user)

    \n"; - responseStream << "\t\t\t"; -#line 327 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - time2.reset(); - if(!steps[4]) { responseStream << "\n"; - responseStream << "\t\t\t\t

    skipped

    \n"; - responseStream << "\t\t\t"; -#line 331 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else { - auto transaction5 = model::gradido::Transaction::createGroupMemberUpdate(user_3, user_group2); - transaction5->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(1); - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction5->sign(user_3); - auto transaction5_json = transaction5->getTransactionAsJson(true); - responseStream << "\n"; - responseStream << "\t\t\t

    "; -#line 338 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction5_json) ); - responseStream << "

    \n"; - responseStream << "\t\t\t"; -#line 339 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t

    Time: "; -#line 340 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time2.string() ); - responseStream << "

    \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    7. Send a cross group transfer from second user to third user signed by second user

    \n"; - responseStream << "\t\t\t"; -#line 344 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - time2.reset(); - if(!steps[5]) { responseStream << "\n"; - responseStream << "\t\t\t\t

    skipped

    \n"; - responseStream << "\t\t\t"; -#line 348 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else { - auto user_3_pubkey = user_3->getModel()->getPublicKeyCopy(); - auto transaction6 = model::gradido::Transaction::createTransfer(user_2, user_3_pubkey, user_group2, 4000000, "Test Group Transfer", false); - if(!transaction6.size()) { - responseStream << "\n"; - responseStream << "\t\t\t\t
    \n"; - responseStream << "\t\t\t\t\treport_problem\n"; - responseStream << "\t\t\t\t\tError creating Transaction\n"; - responseStream << "\t\t\t\t
    \n"; - responseStream << "\t\t\t\t"; -#line 357 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - } else { - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction6[0]->sign(user_2); - auto transaction6_json = transaction6[0]->getTransactionAsJson(true); - auto paired_transaction = transaction6[0]->getPairedTransaction(); - responseStream << "\n"; - responseStream << "\t\t\t\t\t

    "; -#line 364 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction6_json) ); - responseStream << "

    \t\t\n"; - responseStream << "\t\t\t\t\t"; -#line 365 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - if(!paired_transaction.isNull()) { - auto transaction6_2_json = paired_transaction->getTransactionAsJson(true); - responseStream << "

    "; -#line 367 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction6_2_json) ); - responseStream << "

    \n"; - responseStream << "\t\t\t\t\t"; -#line 368 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t\t"; -#line 369 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\t\t"; -#line 370 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << " \n"; - responseStream << "\t\t\t

    Time: "; -#line 371 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time2.string() ); - responseStream << "

    \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    8. Wait "; -#line 374 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( hedera_timeout ); - responseStream << " seconds to give hedera time to process transactions

    \n"; - responseStream << "\t\t\t"; -#line 375 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - if(!steps[6]) { responseStream << "\n"; - responseStream << "\t\t\t\t

    skipped

    \n"; - responseStream << "\t\t\t"; -#line 377 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else { - Poco::Thread::sleep(hedera_timeout * 1000); - } responseStream << "\n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t\t\t

    9. Ask choosen node for transaction and print result

    \n"; - responseStream << "\t\t\t"; -#line 383 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - time2.reset(); - if(!steps[7] || node_server.isNull()) { - responseStream << "

    skipped

    \n"; - responseStream << "\t\t\t"; -#line 386 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else { - auto node_server_model = node_server->getModel(); - JsonRPCRequest jsonrpc(node_server_model->getUrl(), node_server_model->getPort()); - Poco::JSON::Object params; - params.set("groupAlias", user_group->getModel()->getAlias()); - params.set("lastKnownSequenceNumber", 0); - auto gn_answear = jsonrpc.request("getTransactions", params); - if(!gn_answear.isNull()) { - std::stringstream ss; - Poco::JSON::Stringifier::stringify(gn_answear, ss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER); - std::string answear_string = ss.str(); responseStream << "\n"; - responseStream << "\t\t\t\t\t"; -#line 397 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(answear_string) ); -#line 397 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - } - } responseStream << "\n"; - responseStream << "\t\t\t

    Time: "; -#line 400 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time2.string() ); - responseStream << "

    \n"; - responseStream << "\t\t
  • \n"; - responseStream << "\t
\n"; - responseStream << "\t"; -#line 403 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } else if(PAGE_GET_TRANSACTION_RPC_CALL == page && !node_server.isNull()) { - Profiler time3; - auto node_server_model = node_server->getModel(); - auto user_group = controller::Group::load(node_server_model->getGroupId()); - JsonRPCRequest jsonrpc(node_server_model->getUrl(), node_server_model->getPort()); - Poco::JSON::Object params; - params.set("groupAlias", user_group->getModel()->getAlias()); - params.set("lastKnownSequenceNumber", 0); - auto gn_answear = jsonrpc.request("getTransactions", params); - if(!gn_answear.isNull()) { - std::stringstream ss; - Poco::JSON::Stringifier::stringify(gn_answear, ss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER); - std::string answear_string = ss.str(); responseStream << "\n"; - responseStream << "\t\t\t"; -#line 416 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( DataTypeConverter::replaceNewLineWithBr(answear_string) ); -#line 416 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - - } - responseStream << "\n"; - responseStream << "\t\t

Time: "; -#line 419 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - responseStream << ( time3.string() ); - responseStream << "

\n"; - responseStream << "\t"; -#line 420 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" - } responseStream << "\n"; - responseStream << "\t\n"; - responseStream << "
\n"; - responseStream << "\n"; - // begin include footer.cpsp - responseStream << "
\n"; - responseStream << "

Copyright © Gradido 2020

\n"; - responseStream << "
\n"; - responseStream << "
\n"; - responseStream << "
\n"; - responseStream << " "; -#line 6 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\footer.cpsp" - responseStream << ( mTimeProfiler.string() ); - responseStream << "\n"; - responseStream << "
\n"; - responseStream << "
\n"; - responseStream << "

Login Server in Entwicklung

\n"; - responseStream << "

Alpha "; -#line 10 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\footer.cpsp" - responseStream << ( ServerConfig::g_versionString ); - responseStream << "

\n"; - responseStream << "
\n"; - responseStream << "
\n"; - responseStream << "\n"; - responseStream << "\n"; - responseStream << ""; - // end include footer.cpsp - responseStream << "\n"; - if (_compressResponse) _gzipStream.close(); -} +#include "AdminNodeServerTestPage.h" +#include "Poco/Net/HTTPServerRequest.h" +#include "Poco/Net/HTTPServerResponse.h" +#include "Poco/Net/HTMLForm.h" +#include "Poco/DeflatingStream.h" + + +#line 6 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + +#include "../controller/NodeServer.h" +#include "../controller/User.h" +#include "../controller/HederaTopic.h" +#include "../lib/DataTypeConverter.h" +#include "../lib/Profiler.h" +#include "../lib/JsonRPCRequest.h" +#include "../model/gradido/Transaction.h" + +#include "Poco/Thread.h" +#include "Poco/DateTime.h" +#include "Poco/JSON/Stringifier.h" + +enum PageType +{ + PAGE_CHOOSE_TEST, + PAGE_RUN_4_SET_TEST, + PAGE_GET_TRANSACTION_RPC_CALL +}; + +#line 1 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" + +#include "../ServerConfig.h" + + +void AdminNodeServerTestPage::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) +{ + response.setChunkedTransferEncoding(true); + response.setContentType("text/html"); + bool _compressResponse(request.hasToken("Accept-Encoding", "gzip")); + if (_compressResponse) response.set("Content-Encoding", "gzip"); + + Poco::Net::HTMLForm form(request, request.stream()); +#line 28 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + const char* pageName = "Node Server Test"; + PageType page = PAGE_CHOOSE_TEST; + Poco::AutoPtr node_server; + Poco::AutoPtr node_server2; + Poco::AutoPtr user; + Poco::AutoPtr hedera_topic; + Poco::AutoPtr hedera_topic2; + int hedera_timeout = 4; + int sleep_ms_between_transactions = 1000; + + bool steps[8]; memset(steps, 1, 8 * sizeof(bool)); + + + if(!form.empty()) + { + auto node_server_id_string = form.get("test-node-servers", ""); + if(node_server_id_string != "") { + int node_server_id = 0; + if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(node_server_id_string, node_server_id )) { + node_server = controller::NodeServer::load(node_server_id); + } + } + node_server_id_string = form.get("test-node-servers2", ""); + if(node_server_id_string != "") { + int node_server_id = 0; + if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(node_server_id_string, node_server_id )) { + node_server2 = controller::NodeServer::load(node_server_id); + } + } + auto topic_id_string = form.get("test-hedera-topic", ""); + if(topic_id_string != "") { + int topic_id = 0; + if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(topic_id_string, topic_id)) { + hedera_topic = controller::HederaTopic::load(topic_id); + } + } + topic_id_string = form.get("test-hedera-topic2", ""); + if(topic_id_string != "") { + int topic_id = 0; + if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(topic_id_string, topic_id)) { + hedera_topic2 = controller::HederaTopic::load(topic_id); + } + } + auto test_timeout_string = form.get("test-timeout", ""); + if(test_timeout_string != "") { + DataTypeConverter::strToInt(test_timeout_string, hedera_timeout); + } + auto test_part_timeout_string = form.get("test-part-timeout", ""); + if(test_part_timeout_string != "") { + DataTypeConverter::strToInt(test_part_timeout_string, sleep_ms_between_transactions); + } + auto submit = form.get("submit", ""); + if(submit == "Run 6-Test") { + page = PAGE_RUN_4_SET_TEST; + } else if(submit == "json-rpc getTransactions") { + page = PAGE_GET_TRANSACTION_RPC_CALL; + } + std::string step_temp; + for(int i = 0; i < 8; i++) { + std::string name = "step-"; + name += std::to_string(i+2); + step_temp = form.get(name, ""); + if(step_temp == "1") { + steps[i] = true; + } else { + steps[i] = false; + } + } + } + + auto node_servers = controller::NodeServer::load(model::table::NODE_SERVER_GRADIDO_NODE); + auto hedera_topics = controller::HederaTopic::listAll(); + +#line 3 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" + + bool withMaterialIcons = false; + std::ostream& _responseStream = response.send(); + Poco::DeflatingOutputStream _gzipStream(_responseStream, Poco::DeflatingStreamBuf::STREAM_GZIP, 1); + std::ostream& responseStream = _compressResponse ? _gzipStream : _responseStream; + responseStream << "\n"; + // begin include header_large.cpsp + responseStream << "\n"; + responseStream << "\n"; + responseStream << "\n"; + responseStream << "\n"; + responseStream << "\n"; + responseStream << "\n"; + responseStream << "Gradido Login Server: "; +#line 11 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" + responseStream << ( pageName ); + responseStream << "\n"; + responseStream << "\n"; +#line 13 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" + if(withMaterialIcons) { responseStream << "\n"; + responseStream << "\n"; +#line 15 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" + } responseStream << "\n"; + responseStream << "\n"; + responseStream << "\n"; + responseStream << "
\n"; + responseStream << "\t\t
\n"; + responseStream << "\t\t\t
\n"; + responseStream << "\t\t\t\t
    \n"; + responseStream << "\t\t\t\t\t"; +#line 22 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" + if(!user.isNull()) { responseStream << "\n"; + responseStream << "\t\t\t\t\t\t
  • getGroupBaseUrl() ); + responseStream << "/\">Startseite
  • \n"; + responseStream << "\t\t\t\t\t"; +#line 24 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\header_large.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t\t\t
  • Gruppen
  • \n"; + responseStream << "\t\t\t\t\t
  • Node Server
  • \n"; + responseStream << "\t\t\t\t\t
  • Hedera Accounts
  • \n"; + responseStream << "\t\t\t\t\t
  • Hedera Topics
  • \n"; + responseStream << "\t\t\t\t
\n"; + responseStream << "\t\t\t
\n"; + responseStream << "\t\t
\n"; + responseStream << "\t\t
"; + // end include header_large.cpsp + responseStream << "\n"; +#line 103 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( getErrorsHtml() ); + responseStream << "\n"; + responseStream << "
\n"; + responseStream << "\t\n"; + responseStream << "\t
\n"; + responseStream << "\t \n"; + responseStream << "\t \n"; + responseStream << "\t
\n"; + responseStream << "\t
\n"; + responseStream << "\t\t
\n"; + responseStream << "\t\t\t

Test 6-Set (3 AddMember, Creation, 2 Transfer)\n"; + responseStream << "\t\t

\n"; + responseStream << "\t\t
\n"; + responseStream << "\t\t\t
\n"; + responseStream << "\t\t\t\t

1. Create three new accounts and show user public keys for comparisation

\n"; + responseStream << "\t\t\t\t

2. Send a add-member transaction to hedera topic with one signature (first user)

\n"; + responseStream << "\t\t\t\t

3. Send a add-member transaction to hedera topic with two signatures (first user and second user)

\n"; + responseStream << "\t\t\t\t

4. Send a creation transaction to second user, signed by first user

\n"; + responseStream << "\t\t\t\t

5. Send a transfer transaction from second user to first user signed by second user

\n"; + responseStream << "\t\t\t\t

6. Send a add-member transaction to hedera topic 2 with one signature (third user)

\n"; + responseStream << "\t\t\t\t

7. Send a cross group transfer from second user to third user signed by second user

\n"; + responseStream << "\t\t\t\t

8. Wait x seconds to give hedera time to process transactions

\n"; + responseStream << "\t\t\t\t

9. Ask choosen node for transaction and print result

\n"; + responseStream << "\t\t\t\t
\n"; + responseStream << "\t\t\t\t\tGroup 1 \n"; + responseStream << "\t\t\t\t\t\n"; + responseStream << "\t\t\t\t\t"; +#line 128 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + if(node_servers.size() == 0) { responseStream << "\n"; + responseStream << "\t\t\t\t\t\tEdit Node-Servers\n"; + responseStream << "\t\t\t\t\t"; +#line 130 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t\t\t\n"; + responseStream << "\t\t\t\t\t\n"; + responseStream << "\t\t\t\t\t"; +#line 139 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + if(hedera_topics.size() == 0) { responseStream << "\n"; + responseStream << "\t\t\t\t\t\tEdit Hedera-Topics\n"; + responseStream << "\t\t\t\t\t"; +#line 141 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t\t\t\n"; + responseStream << "\t\t\t\t
\n"; + responseStream << "\t\t\t\t
\n"; + responseStream << "\t\t\t\t\tGroup 2 \n"; + responseStream << "\t\t\t\t\t\n"; + responseStream << "\t\t\t\t\t"; +#line 157 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + if(node_servers.size() == 0) { responseStream << "\n"; + responseStream << "\t\t\t\t\t\tEdit Node-Servers\n"; + responseStream << "\t\t\t\t\t"; +#line 159 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t\t\t\n"; + responseStream << "\t\t\t\t\t\n"; + responseStream << "\t\t\t\t\t"; +#line 168 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + if(hedera_topics.size() == 0) { responseStream << "\n"; + responseStream << "\t\t\t\t\t\tEdit Hedera-Topics\n"; + responseStream << "\t\t\t\t\t"; +#line 170 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t\t\t\n"; + responseStream << "\t\t\t\t
\n"; + responseStream << "\t\t\t\t\n"; + responseStream << "\t\t\t\t\n"; + responseStream << "\t\t\t\t seconds \n"; + responseStream << "\t\t\t\t\n"; + responseStream << "\t\t\t\t ms\n"; + responseStream << "\t\t\t\t\n"; + responseStream << "\t\t\t
\n"; + responseStream << "\t\t
\n"; + responseStream << "\t
\n"; + responseStream << "\t
\n"; + responseStream << "\t\t
\n"; + responseStream << "\t\t\t

Test 4-Set (2 AddMember, Creation, Transfer)\n"; + responseStream << "\t\t

\n"; + responseStream << "\t\t
\n"; + responseStream << "\t\t\t
\n"; + responseStream << "\t\t\t\t\n"; + responseStream << "\t\t\t\t"; +#line 199 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + if(node_servers.size() == 0) { responseStream << "\n"; + responseStream << "\t\t\t\t\tEdit Node-Servers\n"; + responseStream << "\t\t\t\t"; +#line 201 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t\t\n"; + responseStream << "\t\t\t\t\n"; + responseStream << "\t\t\t
\n"; + responseStream << "\t\t
\n"; + responseStream << "\t
\n"; + responseStream << "\t"; +#line 213 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + if(PAGE_RUN_4_SET_TEST == page && !hedera_topic.isNull() && !node_server.isNull()) { responseStream << "\n"; + responseStream << "\t
    \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    1. Create three new accounts and show user public keys for comparisation:

    \n"; + responseStream << "\t\t\t"; +#line 217 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + Profiler time2; + auto group_id = hedera_topic->getModel()->getGroupId(); + auto group_id2 = hedera_topic2->getModel()->getGroupId(); + auto user_group = controller::Group::load(group_id); + auto user_group2 = controller::Group::load(group_id2); + auto mnemonic_type = ServerConfig::MNEMONIC_BIP0039_SORTED_ORDER; + + std::string password1 = "hsaj(2askaslASlllak3wjjeudsaj"; + auto user_1 = controller::User::create("testEmail@google.de", "Max", "Mustermann", group_id); + auto passphrase_1 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); + auto gradido_key_pair_1 = KeyPairEd25519::create(passphrase_1); + user_1->setGradidoKeyPair(gradido_key_pair_1); + user_1->login(password1); + + std::string password2 = "uweia8saiSale,dsasA"; + auto user_2 = controller::User::create("testEmail2@google.de", "MJax", "Mustrermann", group_id); + auto passphrase_2 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); + auto gradido_key_pair_2 = KeyPairEd25519::create(passphrase_2); + user_2->setGradidoKeyPair(gradido_key_pair_2); + user_2->login(password2); + + std::string password3 = "jaue_skaiellasealaK"; + auto user_3 = controller::User::create("testEmail3@gmail.com", "Morpheus", "Miaufull", group_id2); + auto passphrase_3 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); + auto gradido_key_pair_3 = KeyPairEd25519::create(passphrase_3); + user_3->setGradidoKeyPair(gradido_key_pair_3); + user_3->login(password3); + responseStream << "\t\t\t\n"; + responseStream << "\t\t\t
    "; +#line 246 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( user_group->getModel()->getName() ); + responseStream << "\n"; + responseStream << "\t\t\t\t

    User 1: "; +#line 247 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( user_1->getPublicHex() ); + responseStream << "

    \n"; + responseStream << "\t\t\t\t

    User 2: "; +#line 248 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( user_2->getPublicHex() ); + responseStream << "

    \n"; + responseStream << "\t\t\t
    \n"; + responseStream << "\t\t\t
    "; +#line 250 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( user_group2->getModel()->getName() ); + responseStream << "\n"; + responseStream << "\t\t\t\t

    User 3: "; +#line 251 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( user_3->getPublicHex() ); + responseStream << "

    \n"; + responseStream << "\t\t\t
    \n"; + responseStream << "\t\t\t

    Time: "; +#line 253 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time2.string() ); + responseStream << "\n"; + responseStream << "\t\t

  • \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    2. Send a add-member transaction to hedera topic with one signature (first user)

    \n"; + responseStream << "\t\t\t"; +#line 257 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + time2.reset(); + if(!steps[0]) { responseStream << "\n"; + responseStream << "\t\t\t\t

    skipped

    \n"; + responseStream << "\t\t\t"; +#line 261 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else { + auto transaction1 = model::gradido::Transaction::createGroupMemberUpdate(user_1, user_group); + transaction1->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(1); + transaction1->sign(user_1); + auto transaction1_json = transaction1->getTransactionAsJson(true); + responseStream << "\n"; + responseStream << "\t\t\t

    "; +#line 267 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction1_json) ); + responseStream << "

    \n"; + responseStream << "\t\t\t"; +#line 268 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t

    Time: "; +#line 269 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time2.string() ); + responseStream << "\n"; + responseStream << "\t\t

  • \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    3. Send a add-member transaction to hedera topic with two signatures (first user and second user)

    \n"; + responseStream << "\t\t\t"; +#line 273 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + time2.reset(); + if(!steps[1]) { responseStream << "\n"; + responseStream << "\t\t\t\t

    skipped

    \n"; + responseStream << "\t\t\t"; +#line 277 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else { + auto transaction2 = model::gradido::Transaction::createGroupMemberUpdate(user_2, user_group); + transaction2->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(2); + transaction2->sign(user_2); + // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction2->sign(user_1); + auto transaction2_json = transaction2->getTransactionAsJson(true); + responseStream << "\n"; + responseStream << "\t\t\t

    "; +#line 286 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction2_json) ); + responseStream << "

    \n"; + responseStream << "\t\t\t"; +#line 287 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t

    Time: "; +#line 288 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time2.string() ); + responseStream << "\n"; + responseStream << "\t\t

  • \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    4. Send a creation transaction to second user, signed by first user

    \n"; + responseStream << "\t\t\t"; +#line 292 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + time2.reset(); + if(!steps[2]) { responseStream << "\n"; + responseStream << "\t\t\t\t

    skipped

    \n"; + responseStream << "\t\t\t"; +#line 296 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else { + auto transaction3 = model::gradido::Transaction::createCreation(user_2, 10000000, Poco::DateTime(), "Test Creation"); + // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction3->sign(user_1); + auto transaction3_json = transaction3->getTransactionAsJson(true); + responseStream << "\n"; + responseStream << "\t\t\t

    "; +#line 303 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction3_json) ); + responseStream << "

    \n"; + responseStream << "\t\t\t"; +#line 304 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t

    Time: "; +#line 305 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time2.string() ); + responseStream << "

    \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    5. Send a transfer transaction from second user to first user signed by second user

    \n"; + responseStream << "\t\t\t"; +#line 309 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + time2.reset(); + if(!steps[3]) { responseStream << "\n"; + responseStream << "\t\t\t\t

    skipped

    \n"; + responseStream << "\t\t\t"; +#line 313 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else { + auto user_1_pubkey = user_1->getModel()->getPublicKeyCopy(); + auto transaction4 = model::gradido::Transaction::createTransfer(user_2, user_1_pubkey, user_group, 5000000, "Test Transfer"); + // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction4[0]->sign(user_2); + auto transaction4_json = transaction4[0]->getTransactionAsJson(true); + responseStream << "\n"; + responseStream << "\t\t\t

    "; +#line 321 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction4_json) ); + responseStream << "

    \n"; + responseStream << "\t\t\t"; +#line 322 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t

    Time: "; +#line 323 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time2.string() ); + responseStream << "

    \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    6. Send a add-member transaction to hedera topic 2 with one signature (third user)

    \n"; + responseStream << "\t\t\t"; +#line 327 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + time2.reset(); + if(!steps[4]) { responseStream << "\n"; + responseStream << "\t\t\t\t

    skipped

    \n"; + responseStream << "\t\t\t"; +#line 331 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else { + auto transaction5 = model::gradido::Transaction::createGroupMemberUpdate(user_3, user_group2); + transaction5->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(1); + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction5->sign(user_3); + auto transaction5_json = transaction5->getTransactionAsJson(true); + responseStream << "\n"; + responseStream << "\t\t\t

    "; +#line 338 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction5_json) ); + responseStream << "

    \n"; + responseStream << "\t\t\t"; +#line 339 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t

    Time: "; +#line 340 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time2.string() ); + responseStream << "

    \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    7. Send a cross group transfer from second user to third user signed by second user

    \n"; + responseStream << "\t\t\t"; +#line 344 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + time2.reset(); + if(!steps[5]) { responseStream << "\n"; + responseStream << "\t\t\t\t

    skipped

    \n"; + responseStream << "\t\t\t"; +#line 348 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else { + auto user_3_pubkey = user_3->getModel()->getPublicKeyCopy(); + auto transaction6 = model::gradido::Transaction::createTransfer(user_2, user_3_pubkey, user_group2, 4000000, "Test Group Transfer", false); + if(!transaction6.size()) { + responseStream << "\n"; + responseStream << "\t\t\t\t
    \n"; + responseStream << "\t\t\t\t\treport_problem\n"; + responseStream << "\t\t\t\t\tError creating Transaction\n"; + responseStream << "\t\t\t\t
    \n"; + responseStream << "\t\t\t\t"; +#line 357 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + } else { + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction6[0]->sign(user_2); + auto transaction6_json = transaction6[0]->getTransactionAsJson(true); + auto paired_transaction = transaction6[0]->getPairedTransaction(); + responseStream << "\n"; + responseStream << "\t\t\t\t\t

    "; +#line 364 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction6_json) ); + responseStream << "

    \t\t\n"; + responseStream << "\t\t\t\t\t"; +#line 365 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + if(!paired_transaction.isNull()) { + auto transaction6_2_json = paired_transaction->getTransactionAsJson(true); + responseStream << "

    "; +#line 367 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(transaction6_2_json) ); + responseStream << "

    \n"; + responseStream << "\t\t\t\t\t"; +#line 368 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t\t"; +#line 369 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\t\t"; +#line 370 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << " \n"; + responseStream << "\t\t\t

    Time: "; +#line 371 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time2.string() ); + responseStream << "

    \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    8. Wait "; +#line 374 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( hedera_timeout ); + responseStream << " seconds to give hedera time to process transactions

    \n"; + responseStream << "\t\t\t"; +#line 375 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + if(!steps[6]) { responseStream << "\n"; + responseStream << "\t\t\t\t

    skipped

    \n"; + responseStream << "\t\t\t"; +#line 377 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else { + Poco::Thread::sleep(hedera_timeout * 1000); + } responseStream << "\n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t\t\t

    9. Ask choosen node for transaction and print result

    \n"; + responseStream << "\t\t\t"; +#line 383 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + time2.reset(); + if(!steps[7] || node_server.isNull()) { + responseStream << "

    skipped

    \n"; + responseStream << "\t\t\t"; +#line 386 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else { + auto node_server_model = node_server->getModel(); + JsonRPCRequest jsonrpc(node_server_model->getUrl(), node_server_model->getPort()); + Poco::JSON::Object params; + params.set("groupAlias", user_group->getModel()->getAlias()); + params.set("lastKnownSequenceNumber", 0); + auto gn_answear = jsonrpc.request("getTransactions", params); + if(!gn_answear.isNull()) { + std::stringstream ss; + Poco::JSON::Stringifier::stringify(gn_answear, ss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER); + std::string answear_string = ss.str(); responseStream << "\n"; + responseStream << "\t\t\t\t\t"; +#line 397 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(answear_string) ); +#line 397 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + } + } responseStream << "\n"; + responseStream << "\t\t\t

    Time: "; +#line 400 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time2.string() ); + responseStream << "

    \n"; + responseStream << "\t\t
  • \n"; + responseStream << "\t
\n"; + responseStream << "\t"; +#line 403 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } else if(PAGE_GET_TRANSACTION_RPC_CALL == page && !node_server.isNull()) { + Profiler time3; + auto node_server_model = node_server->getModel(); + auto user_group = controller::Group::load(node_server_model->getGroupId()); + JsonRPCRequest jsonrpc(node_server_model->getUrl(), node_server_model->getPort()); + Poco::JSON::Object params; + params.set("groupAlias", user_group->getModel()->getAlias()); + params.set("lastKnownSequenceNumber", 0); + auto gn_answear = jsonrpc.request("getTransactions", params); + if(!gn_answear.isNull()) { + std::stringstream ss; + Poco::JSON::Stringifier::stringify(gn_answear, ss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER); + std::string answear_string = ss.str(); responseStream << "\n"; + responseStream << "\t\t\t"; +#line 416 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( DataTypeConverter::replaceNewLineWithBr(answear_string) ); +#line 416 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + + } + responseStream << "\n"; + responseStream << "\t\t

Time: "; +#line 419 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + responseStream << ( time3.string() ); + responseStream << "

\n"; + responseStream << "\t"; +#line 420 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminNodeServerTest.cpsp" + } responseStream << "\n"; + responseStream << "\t\n"; + responseStream << "
\n"; + responseStream << "\n"; + // begin include footer.cpsp + responseStream << "
\n"; + responseStream << "

Copyright © Gradido 2020

\n"; + responseStream << "
\n"; + responseStream << "
\n"; + responseStream << "
\n"; + responseStream << " "; +#line 6 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\footer.cpsp" + responseStream << ( mTimeProfiler.string() ); + responseStream << "\n"; + responseStream << "
\n"; + responseStream << "
\n"; + responseStream << "

Login Server in Entwicklung

\n"; + responseStream << "

Alpha "; +#line 10 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\footer.cpsp" + responseStream << ( ServerConfig::g_versionString ); + responseStream << "

\n"; + responseStream << "
\n"; + responseStream << "
\n"; + responseStream << "\n"; + responseStream << "\n"; + responseStream << ""; + // end include footer.cpsp + responseStream << "\n"; + if (_compressResponse) _gzipStream.close(); +} diff --git a/login_server/src/cpp/HTTPInterface/AdminNodeServerTestPage.h b/login_server/src/cpp/HTTPInterface/AdminNodeServerTestPage.h index 12e550efa..a1ff3ad1d 100644 --- a/login_server/src/cpp/HTTPInterface/AdminNodeServerTestPage.h +++ b/login_server/src/cpp/HTTPInterface/AdminNodeServerTestPage.h @@ -1,18 +1,18 @@ -#ifndef AdminNodeServerTestPage_INCLUDED -#define AdminNodeServerTestPage_INCLUDED - - -#include "Poco/Net/HTTPRequestHandler.h" - - -#include "PageRequestMessagedHandler.h" - - -class AdminNodeServerTestPage: public PageRequestMessagedHandler -{ -public: - void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response); -}; - - -#endif // AdminNodeServerTestPage_INCLUDED +#ifndef AdminNodeServerTestPage_INCLUDED +#define AdminNodeServerTestPage_INCLUDED + + +#include "Poco/Net/HTTPRequestHandler.h" + + +#include "PageRequestMessagedHandler.h" + + +class AdminNodeServerTestPage: public PageRequestMessagedHandler +{ +public: + void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response); +}; + + +#endif // AdminNodeServerTestPage_INCLUDED diff --git a/login_server/src/cpp/HTTPInterface/LoginPage.h b/login_server/src/cpp/HTTPInterface/LoginPage.h index be3dfd97d..30c617eaf 100644 --- a/login_server/src/cpp/HTTPInterface/LoginPage.h +++ b/login_server/src/cpp/HTTPInterface/LoginPage.h @@ -1,20 +1,20 @@ -#ifndef LoginPage_INCLUDED -#define LoginPage_INCLUDED - - -#include "Poco/Net/HTTPRequestHandler.h" - - -#include "SessionHTTPRequestHandler.h" - - -class LoginPage: public SessionHTTPRequestHandler -{ -public: - LoginPage(Session*); - - void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response); -}; - - -#endif // LoginPage_INCLUDED +#ifndef LoginPage_INCLUDED +#define LoginPage_INCLUDED + + +#include "Poco/Net/HTTPRequestHandler.h" + + +#include "SessionHTTPRequestHandler.h" + + +class LoginPage: public SessionHTTPRequestHandler +{ +public: + LoginPage(Session*); + + void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response); +}; + + +#endif // LoginPage_INCLUDED diff --git a/login_server/src/cpp/JSONInterface/JsonGetUserInfos.cpp b/login_server/src/cpp/JSONInterface/JsonGetUserInfos.cpp index e519c3eba..0bab0d863 100644 --- a/login_server/src/cpp/JSONInterface/JsonGetUserInfos.cpp +++ b/login_server/src/cpp/JSONInterface/JsonGetUserInfos.cpp @@ -1,123 +1,123 @@ -#include "JsonGetUserInfos.h" - -#include "../lib/DataTypeConverter.h" -#include "../SingletonManager/SessionManager.h" -#include "../controller/User.h" -#include "../controller/EmailVerificationCode.h" - -#include "../ServerConfig.h" - -Poco::JSON::Object* JsonGetUserInfos::handle(Poco::Dynamic::Var params) -{ - /* - 'session_id' => $session_id, - 'email' => $email, - 'ask' => ['EmailOptIn.Register'] - */ - // incoming - int session_id = 0; - std::string email; - Poco::JSON::Array::Ptr askArray; - - auto sm = SessionManager::getInstance(); - - // if is json object - if (params.type() == typeid(Poco::JSON::Object::Ptr)) { - Poco::JSON::Object::Ptr paramJsonObject = params.extract(); - /// Throws a RangeException if the value does not fit - /// into the result variable. - /// Throws a NotImplementedException if conversion is - /// not available for the given type. - /// Throws InvalidAccessException if Var is empty. - try { - paramJsonObject->get("email").convert(email); - paramJsonObject->get("session_id").convert(session_id); - askArray = paramJsonObject->getArray("ask"); - } - catch (Poco::Exception& ex) { - return stateError("json exception", ex.displayText()); - } - } - else { - return stateError("parameter format unknown"); - } - - if (!session_id) { - return stateError("session_id invalid"); - } - if (askArray.isNull()) { - return stateError("ask is zero or not an array"); - } - - auto session = sm->getSession(session_id); - if (!session) { - return customStateError("not found", "session not found"); - } - - auto user = controller::User::create(); - if (1 != user->load(email)) { - return customStateError("not found", "user not found"); - } - auto userModel = user->getModel(); - - - Poco::JSON::Object* result = new Poco::JSON::Object; - result->set("state", "success"); - Poco::JSON::Array jsonErrorsArray; - Poco::JSON::Object jsonUser; - Poco::JSON::Object jsonServer; - - for (auto it = askArray->begin(); it != askArray->end(); it++) { - auto parameter = *it; - std::string parameterString; - try { - parameter.convert(parameterString); - if (parameterString == "EmailVerificationCode.Register") { - try { - auto emailVerificationCode = controller::EmailVerificationCode::load( - userModel->getID(), model::table::EMAIL_OPT_IN_REGISTER - ); - if (!emailVerificationCode) { - emailVerificationCode = controller::EmailVerificationCode::create(userModel->getID(), model::table::EMAIL_OPT_IN_REGISTER); - UniLib::controller::TaskPtr insert = new model::table::ModelInsertTask(emailVerificationCode->getModel(), false); - insert->scheduleTask(insert); - } - jsonUser.set("EmailVerificationCode.Register", std::to_string(emailVerificationCode->getModel()->getCode())); - } - catch (Poco::Exception& ex) { - printf("exception: %s\n", ex.displayText().data()); - } - } - else if (parameterString == "loginServer.path") { - jsonServer.set("loginServer.path", ServerConfig::g_serverPath); - } - else if (parameterString == "user.pubkeyhex") { - jsonUser.set("pubkeyhex", userModel->getPublicKeyHex()); - } - else if (parameterString == "user.first_name") { - jsonUser.set("first_name", userModel->getFirstName()); - } - else if (parameterString == "user.last_name") { - jsonUser.set("last_name", userModel->getLastName()); - } - else if (parameterString == "user.disabled") { - jsonUser.set("disabled", userModel->isDisabled()); - } - else if (parameterString == "user.email_checked") { - jsonUser.set("email_checked", userModel->isEmailChecked()); - } - else if (parameterString == "user.identHash") { - auto email = userModel->getEmail(); - jsonUser.set("identHash", DRMakeStringHash(email.data(), email.size())); - } - } - catch (Poco::Exception& ex) { - jsonErrorsArray.add("ask parameter invalid"); - } - } - result->set("errors", jsonErrorsArray); - result->set("userData", jsonUser); - result->set("server", jsonServer); - return result; - +#include "JsonGetUserInfos.h" + +#include "../lib/DataTypeConverter.h" +#include "../SingletonManager/SessionManager.h" +#include "../controller/User.h" +#include "../controller/EmailVerificationCode.h" + +#include "../ServerConfig.h" + +Poco::JSON::Object* JsonGetUserInfos::handle(Poco::Dynamic::Var params) +{ + /* + 'session_id' => $session_id, + 'email' => $email, + 'ask' => ['EmailOptIn.Register'] + */ + // incoming + int session_id = 0; + std::string email; + Poco::JSON::Array::Ptr askArray; + + auto sm = SessionManager::getInstance(); + + // if is json object + if (params.type() == typeid(Poco::JSON::Object::Ptr)) { + Poco::JSON::Object::Ptr paramJsonObject = params.extract(); + /// Throws a RangeException if the value does not fit + /// into the result variable. + /// Throws a NotImplementedException if conversion is + /// not available for the given type. + /// Throws InvalidAccessException if Var is empty. + try { + paramJsonObject->get("email").convert(email); + paramJsonObject->get("session_id").convert(session_id); + askArray = paramJsonObject->getArray("ask"); + } + catch (Poco::Exception& ex) { + return stateError("json exception", ex.displayText()); + } + } + else { + return stateError("parameter format unknown"); + } + + if (!session_id) { + return stateError("session_id invalid"); + } + if (askArray.isNull()) { + return stateError("ask is zero or not an array"); + } + + auto session = sm->getSession(session_id); + if (!session) { + return customStateError("not found", "session not found"); + } + + auto user = controller::User::create(); + if (1 != user->load(email)) { + return customStateError("not found", "user not found"); + } + auto userModel = user->getModel(); + + + Poco::JSON::Object* result = new Poco::JSON::Object; + result->set("state", "success"); + Poco::JSON::Array jsonErrorsArray; + Poco::JSON::Object jsonUser; + Poco::JSON::Object jsonServer; + + for (auto it = askArray->begin(); it != askArray->end(); it++) { + auto parameter = *it; + std::string parameterString; + try { + parameter.convert(parameterString); + if (parameterString == "EmailVerificationCode.Register") { + try { + auto emailVerificationCode = controller::EmailVerificationCode::load( + userModel->getID(), model::table::EMAIL_OPT_IN_REGISTER + ); + if (!emailVerificationCode) { + emailVerificationCode = controller::EmailVerificationCode::create(userModel->getID(), model::table::EMAIL_OPT_IN_REGISTER); + UniLib::controller::TaskPtr insert = new model::table::ModelInsertTask(emailVerificationCode->getModel(), false); + insert->scheduleTask(insert); + } + jsonUser.set("EmailVerificationCode.Register", std::to_string(emailVerificationCode->getModel()->getCode())); + } + catch (Poco::Exception& ex) { + printf("exception: %s\n", ex.displayText().data()); + } + } + else if (parameterString == "loginServer.path") { + jsonServer.set("loginServer.path", ServerConfig::g_serverPath); + } + else if (parameterString == "user.pubkeyhex") { + jsonUser.set("pubkeyhex", userModel->getPublicKeyHex()); + } + else if (parameterString == "user.first_name") { + jsonUser.set("first_name", userModel->getFirstName()); + } + else if (parameterString == "user.last_name") { + jsonUser.set("last_name", userModel->getLastName()); + } + else if (parameterString == "user.disabled") { + jsonUser.set("disabled", userModel->isDisabled()); + } + else if (parameterString == "user.email_checked") { + jsonUser.set("email_checked", userModel->isEmailChecked()); + } + else if (parameterString == "user.identHash") { + auto email = userModel->getEmail(); + jsonUser.set("identHash", DRMakeStringHash(email.data(), email.size())); + } + } + catch (Poco::Exception& ex) { + jsonErrorsArray.add("ask parameter invalid"); + } + } + result->set("errors", jsonErrorsArray); + result->set("userData", jsonUser); + result->set("server", jsonServer); + return result; + } \ No newline at end of file diff --git a/login_server/src/cpp/JSONInterface/JsonLogout.cpp b/login_server/src/cpp/JSONInterface/JsonLogout.cpp index 0b347f767..03cb25fb3 100644 --- a/login_server/src/cpp/JSONInterface/JsonLogout.cpp +++ b/login_server/src/cpp/JSONInterface/JsonLogout.cpp @@ -1,44 +1,44 @@ -#include "JsonLogout.h" - - - -#include "../SingletonManager/SessionManager.h" - - -Poco::JSON::Object* JsonLogout::handle(Poco::Dynamic::Var params) -{ - - auto sm = SessionManager::getInstance(); - int session_id = 0; - - // if is json object - if (params.type() == typeid(Poco::JSON::Object::Ptr)) { - Poco::JSON::Object::Ptr paramJsonObject = params.extract(); - /// Throws a RangeException if the value does not fit - /// into the result variable. - /// Throws a NotImplementedException if conversion is - /// not available for the given type. - /// Throws InvalidAccessException if Var is empty. - try { - paramJsonObject->get("session_id").convert(session_id); - } - catch (Poco::Exception& ex) { - return stateError("json exception", ex.displayText()); - } - } - else { - return stateError("parameter format unknown"); - } - - auto session = sm->getSession(session_id); - if (!session) { - return stateError("session not found", std::to_string(session_id)); - } - if (sm->releaseSession(session_id)) { - return stateSuccess(); - } - return stateError("error by releasing session"); - - - +#include "JsonLogout.h" + + + +#include "../SingletonManager/SessionManager.h" + + +Poco::JSON::Object* JsonLogout::handle(Poco::Dynamic::Var params) +{ + + auto sm = SessionManager::getInstance(); + int session_id = 0; + + // if is json object + if (params.type() == typeid(Poco::JSON::Object::Ptr)) { + Poco::JSON::Object::Ptr paramJsonObject = params.extract(); + /// Throws a RangeException if the value does not fit + /// into the result variable. + /// Throws a NotImplementedException if conversion is + /// not available for the given type. + /// Throws InvalidAccessException if Var is empty. + try { + paramJsonObject->get("session_id").convert(session_id); + } + catch (Poco::Exception& ex) { + return stateError("json exception", ex.displayText()); + } + } + else { + return stateError("parameter format unknown"); + } + + auto session = sm->getSession(session_id); + if (!session) { + return stateError("session not found", std::to_string(session_id)); + } + if (sm->releaseSession(session_id)) { + return stateSuccess(); + } + return stateError("error by releasing session"); + + + } \ No newline at end of file diff --git a/login_server/src/cpp/JSONInterface/JsonLogout.h b/login_server/src/cpp/JSONInterface/JsonLogout.h index 7243d2b8c..8b3def105 100644 --- a/login_server/src/cpp/JSONInterface/JsonLogout.h +++ b/login_server/src/cpp/JSONInterface/JsonLogout.h @@ -1,18 +1,18 @@ -#ifndef __JSON_INTERFACE_JSON_LOGOUT_ -#define __JSON_INTERFACE_JSON_LOGOUT_ - -#include "JsonRequestHandler.h" - -class JsonLogout : public JsonRequestHandler -{ -public: - JsonLogout(Poco::Net::IPAddress ip) : mClientIP(ip) {} - Poco::JSON::Object* handle(Poco::Dynamic::Var params); - -protected: - Poco::Net::IPAddress mClientIP; - - -}; - +#ifndef __JSON_INTERFACE_JSON_LOGOUT_ +#define __JSON_INTERFACE_JSON_LOGOUT_ + +#include "JsonRequestHandler.h" + +class JsonLogout : public JsonRequestHandler +{ +public: + JsonLogout(Poco::Net::IPAddress ip) : mClientIP(ip) {} + Poco::JSON::Object* handle(Poco::Dynamic::Var params); + +protected: + Poco::Net::IPAddress mClientIP; + + +}; + #endif // __JSON_INTERFACE_JSON_LOGOUT_ \ No newline at end of file diff --git a/login_server/src/cpp/JSONInterface/JsonTransaction.h b/login_server/src/cpp/JSONInterface/JsonTransaction.h index 7d842fac0..95e9885be 100644 --- a/login_server/src/cpp/JSONInterface/JsonTransaction.h +++ b/login_server/src/cpp/JSONInterface/JsonTransaction.h @@ -1,19 +1,19 @@ -#ifndef __JSON_INTERFACE_JSON_TRANSACTION_ -#define __JSON_INTERFACE_JSON_TRANSACTION_ - -#include "JsonRequestHandler.h" - -class Session; - -class JsonTransaction : public JsonRequestHandler -{ -public: - Poco::JSON::Object* handle(Poco::Dynamic::Var params); - -protected: - bool startProcessingTransaction(Session* session, const std::string& transactionBase64); - - -}; - +#ifndef __JSON_INTERFACE_JSON_TRANSACTION_ +#define __JSON_INTERFACE_JSON_TRANSACTION_ + +#include "JsonRequestHandler.h" + +class Session; + +class JsonTransaction : public JsonRequestHandler +{ +public: + Poco::JSON::Object* handle(Poco::Dynamic::Var params); + +protected: + bool startProcessingTransaction(Session* session, const std::string& transactionBase64); + + +}; + #endif // __JSON_INTERFACE_JSON_TRANSACTION_ \ No newline at end of file diff --git a/login_server/src/cpp/SingletonManager/EmailManager.cpp b/login_server/src/cpp/SingletonManager/EmailManager.cpp index 41f45b471..15f5b7777 100644 --- a/login_server/src/cpp/SingletonManager/EmailManager.cpp +++ b/login_server/src/cpp/SingletonManager/EmailManager.cpp @@ -1,173 +1,173 @@ -#include "EmailManager.h" -#include "../ServerConfig.h" - -#include "../Crypto/Obfus_array.h" -#include "../Crypto/DRRandom.h" - -#include "../SingletonManager/LanguageManager.h" - -#include "Poco/Net/SecureSMTPClientSession.h" -#include "Poco/Net/SSLException.h" - - -EmailManager::EmailManager() - : Thread("emails", false), mEmailLog(Poco::Logger::get("emailLog")), mInitalized(false), mDisableEmail(false) -{ - - -} - -EmailManager::~EmailManager() -{ - exit(); - -} - -EmailManager* EmailManager::getInstance() -{ - static EmailManager theOne; - return &theOne; -} - -bool EmailManager::init(const Poco::Util::LayeredConfiguration& cfg) -{ - try { - mDisableEmail = cfg.getBool("email.disable", false); - if (!mDisableEmail) { - mEmailAccount.sender = cfg.getString("email.sender"); - mEmailAccount.admin_receiver = cfg.getString("email.admin_receiver"); - mEmailAccount.username = cfg.getString("email.username"); - mEmailAccount.password = cfg.getString("email.password"); - mEmailAccount.url = cfg.getString("email.smtp.url"); - mEmailAccount.port = cfg.getInt("email.smtp.port"); - } - } - catch (Poco::Exception& ex) { - printf("email account not set in config: %s\n", ex.displayText().data()); - return false; - } - Thread::init("emails"); - mInitalized = true; - - DISASM_FALSERET; - ServerConfig::g_ServerKeySeed->put(3, DRRandom::r64()); - - return true; -} - -void EmailManager::addEmail(model::Email* email) { - if (mDisableEmail) { - std::string log_message = "Email should be sended to: "; - auto email_user = email->getUser(); - Poco::AutoPtr email_model; - if (email_user) { - email_model = email_user->getModel(); - log_message += email_model->getNameWithEmailHtml(); - } - if (email_model.isNull()) { - log_message += ""; - } - log_message += ", type: "; - log_message += model::Email::emailTypeString(email->getType()); - mEmailLog.log(log_message); - - delete email; - return; - } - mPendingEmails.push(email); - condSignal(); -} - -void EmailManager::exit() -{ - model::Email* email = nullptr; - while (mPendingEmails.pop(email)) { - delete email; - } - mInitalized = false; -} - -int EmailManager::ThreadFunction() -{ - // prepare connection to email server - if (ServerConfig::g_disableEmail) return 0; - - if (mPendingEmails.empty()) return 0; - - auto lm = LanguageManager::getInstance(); - - Poco::Net::SecureSMTPClientSession mailClientSession(mEmailAccount.url, mEmailAccount.port); - mailClientSession.login(); - try { - mailClientSession.startTLS(ServerConfig::g_SSL_CLient_Context); - mailClientSession.login(Poco::Net::SMTPClientSession::AUTH_LOGIN, mEmailAccount.username, mEmailAccount.password); - } - catch (Poco::Net::SSLException& ex) { - printf("[PrepareEmailTask] ssl certificate error: %s\nPlease make sure you have cacert.pem (CA/root certificates) next to binary from https://curl.haxx.se/docs/caextract.html\n", ex.displayText().data()); - return -1; - } - - model::Email* email = nullptr; - Poco::AutoPtr catalogs[2]; - - // if email list empty, wait 500ms x time before exit thread and closing connection - int timeoutWaits = 20; - - while (mPendingEmails.pop(email) || timeoutWaits > 0) { - if (email) { - Poco::Net::MailMessage mailMessage; - mailMessage.setSender(mEmailAccount.sender); - Languages lang_code = ServerConfig::g_default_locale; - auto email_user = email->getUser(); - if (email_user) { - Poco::AutoPtr userModel = email_user->getModel(); - - if (!userModel.isNull()) { - lang_code = LanguageManager::languageFromString(userModel->getLanguageKey()); - if (lang_code > LANG_COUNT) lang_code = ServerConfig::g_default_locale; - } - } - if (catalogs[lang_code].isNull()) { - catalogs[lang_code] = lm->getFreeCatalog(lang_code); - } - if (email->draft(&mailMessage, catalogs[lang_code])) { - - mailClientSession.sendMessage(mailMessage); - // add for debugging - if (email_user) { - //printf("send email to %s\n", user_model->getEmail().data()); - auto user_model = email_user->getModel(); - std::string log_message = "Email sended to: "; - if (user_model) { - log_message += email_user->getModel()->getNameWithEmailHtml(); - } - else { - log_message += ""; - } - log_message += ", type: "; - log_message += model::Email::emailTypeString(email->getType()); - mEmailLog.log(log_message); - } - } - else { - // error drafting email, shouldn't happend - printf("[EmailManager::ThreadFunction] Error drafting email\n"); - } - delete email; - email = nullptr; - } - if (mPendingEmails.empty()) { - Poco::Thread::sleep(500); - timeoutWaits--; - } - } - - - - - - - mailClientSession.close(); - - return 0; +#include "EmailManager.h" +#include "../ServerConfig.h" + +#include "../Crypto/Obfus_array.h" +#include "../Crypto/DRRandom.h" + +#include "../SingletonManager/LanguageManager.h" + +#include "Poco/Net/SecureSMTPClientSession.h" +#include "Poco/Net/SSLException.h" + + +EmailManager::EmailManager() + : Thread("emails", false), mEmailLog(Poco::Logger::get("emailLog")), mInitalized(false), mDisableEmail(false) +{ + + +} + +EmailManager::~EmailManager() +{ + exit(); + +} + +EmailManager* EmailManager::getInstance() +{ + static EmailManager theOne; + return &theOne; +} + +bool EmailManager::init(const Poco::Util::LayeredConfiguration& cfg) +{ + try { + mDisableEmail = cfg.getBool("email.disable", false); + if (!mDisableEmail) { + mEmailAccount.sender = cfg.getString("email.sender"); + mEmailAccount.admin_receiver = cfg.getString("email.admin_receiver"); + mEmailAccount.username = cfg.getString("email.username"); + mEmailAccount.password = cfg.getString("email.password"); + mEmailAccount.url = cfg.getString("email.smtp.url"); + mEmailAccount.port = cfg.getInt("email.smtp.port"); + } + } + catch (Poco::Exception& ex) { + printf("email account not set in config: %s\n", ex.displayText().data()); + return false; + } + Thread::init("emails"); + mInitalized = true; + + DISASM_FALSERET; + ServerConfig::g_ServerKeySeed->put(3, DRRandom::r64()); + + return true; +} + +void EmailManager::addEmail(model::Email* email) { + if (mDisableEmail) { + std::string log_message = "Email should be sended to: "; + auto email_user = email->getUser(); + Poco::AutoPtr email_model; + if (email_user) { + email_model = email_user->getModel(); + log_message += email_model->getNameWithEmailHtml(); + } + if (email_model.isNull()) { + log_message += ""; + } + log_message += ", type: "; + log_message += model::Email::emailTypeString(email->getType()); + mEmailLog.log(log_message); + + delete email; + return; + } + mPendingEmails.push(email); + condSignal(); +} + +void EmailManager::exit() +{ + model::Email* email = nullptr; + while (mPendingEmails.pop(email)) { + delete email; + } + mInitalized = false; +} + +int EmailManager::ThreadFunction() +{ + // prepare connection to email server + if (ServerConfig::g_disableEmail) return 0; + + if (mPendingEmails.empty()) return 0; + + auto lm = LanguageManager::getInstance(); + + Poco::Net::SecureSMTPClientSession mailClientSession(mEmailAccount.url, mEmailAccount.port); + mailClientSession.login(); + try { + mailClientSession.startTLS(ServerConfig::g_SSL_CLient_Context); + mailClientSession.login(Poco::Net::SMTPClientSession::AUTH_LOGIN, mEmailAccount.username, mEmailAccount.password); + } + catch (Poco::Net::SSLException& ex) { + printf("[PrepareEmailTask] ssl certificate error: %s\nPlease make sure you have cacert.pem (CA/root certificates) next to binary from https://curl.haxx.se/docs/caextract.html\n", ex.displayText().data()); + return -1; + } + + model::Email* email = nullptr; + Poco::AutoPtr catalogs[2]; + + // if email list empty, wait 500ms x time before exit thread and closing connection + int timeoutWaits = 20; + + while (mPendingEmails.pop(email) || timeoutWaits > 0) { + if (email) { + Poco::Net::MailMessage mailMessage; + mailMessage.setSender(mEmailAccount.sender); + Languages lang_code = ServerConfig::g_default_locale; + auto email_user = email->getUser(); + if (email_user) { + Poco::AutoPtr userModel = email_user->getModel(); + + if (!userModel.isNull()) { + lang_code = LanguageManager::languageFromString(userModel->getLanguageKey()); + if (lang_code > LANG_COUNT) lang_code = ServerConfig::g_default_locale; + } + } + if (catalogs[lang_code].isNull()) { + catalogs[lang_code] = lm->getFreeCatalog(lang_code); + } + if (email->draft(&mailMessage, catalogs[lang_code])) { + + mailClientSession.sendMessage(mailMessage); + // add for debugging + if (email_user) { + //printf("send email to %s\n", user_model->getEmail().data()); + auto user_model = email_user->getModel(); + std::string log_message = "Email sended to: "; + if (user_model) { + log_message += email_user->getModel()->getNameWithEmailHtml(); + } + else { + log_message += ""; + } + log_message += ", type: "; + log_message += model::Email::emailTypeString(email->getType()); + mEmailLog.log(log_message); + } + } + else { + // error drafting email, shouldn't happend + printf("[EmailManager::ThreadFunction] Error drafting email\n"); + } + delete email; + email = nullptr; + } + if (mPendingEmails.empty()) { + Poco::Thread::sleep(500); + timeoutWaits--; + } + } + + + + + + + mailClientSession.close(); + + return 0; } \ No newline at end of file diff --git a/login_server/src/cpp/model/hedera/TransactionId.cpp b/login_server/src/cpp/model/hedera/TransactionId.cpp index df6606af1..958c87f90 100644 --- a/login_server/src/cpp/model/hedera/TransactionId.cpp +++ b/login_server/src/cpp/model/hedera/TransactionId.cpp @@ -1,47 +1,47 @@ -#include "TransactionId.h" - -#include "../../lib/DataTypeConverter.h" - -namespace model { - namespace hedera { - TransactionId::TransactionId() - : shard(0), realm(0), num(0) - { - - } - - TransactionId::TransactionId(const proto::TransactionID& transaction) - { - auto account_id = transaction.accountid(); - shard = account_id.shardnum(); - realm = account_id.realmnum(); - num = account_id.accountnum(); - mTransactionValidStart = DataTypeConverter::convertFromProtoTimestamp(transaction.transactionvalidstart()); - - } - - TransactionId::TransactionId(int shard, int realm, int num, Poco::Timestamp transactionValidStart) - : shard(shard), realm(realm), num(num), mTransactionValidStart(transactionValidStart) - { - - } - - TransactionId::~TransactionId() - { - - } - - Poco::JSON::Object::Ptr TransactionId::convertToJSON() - { - Poco::JSON::Object::Ptr result = new Poco::JSON::Object; - result->set("transactionValidStart", mTransactionValidStart); - Poco::JSON::Object accountId; - accountId.set("shard", shard); - accountId.set("realm", realm); - accountId.set("num", num); - result->set("accountId", accountId); - return result; - } - - } +#include "TransactionId.h" + +#include "../../lib/DataTypeConverter.h" + +namespace model { + namespace hedera { + TransactionId::TransactionId() + : shard(0), realm(0), num(0) + { + + } + + TransactionId::TransactionId(const proto::TransactionID& transaction) + { + auto account_id = transaction.accountid(); + shard = account_id.shardnum(); + realm = account_id.realmnum(); + num = account_id.accountnum(); + mTransactionValidStart = DataTypeConverter::convertFromProtoTimestamp(transaction.transactionvalidstart()); + + } + + TransactionId::TransactionId(int shard, int realm, int num, Poco::Timestamp transactionValidStart) + : shard(shard), realm(realm), num(num), mTransactionValidStart(transactionValidStart) + { + + } + + TransactionId::~TransactionId() + { + + } + + Poco::JSON::Object::Ptr TransactionId::convertToJSON() + { + Poco::JSON::Object::Ptr result = new Poco::JSON::Object; + result->set("transactionValidStart", mTransactionValidStart); + Poco::JSON::Object accountId; + accountId.set("shard", shard); + accountId.set("realm", realm); + accountId.set("num", num); + result->set("accountId", accountId); + return result; + } + + } } \ No newline at end of file diff --git a/login_server/src/cpsp/adminNodeServerTest.cpsp b/login_server/src/cpsp/adminNodeServerTest.cpsp index a1cc0a295..610bb89d2 100644 --- a/login_server/src/cpsp/adminNodeServerTest.cpsp +++ b/login_server/src/cpsp/adminNodeServerTest.cpsp @@ -1,424 +1,424 @@ -<%@ page class="AdminNodeServerTestPage" %> -<%@ page form="true" %> -<%@ page compressed="true" %> -<%@ page baseClass="PageRequestMessagedHandler" %> -<%@ header include="PageRequestMessagedHandler.h" %> -<%! - -#include "../controller/NodeServer.h" -#include "../controller/User.h" -#include "../controller/HederaTopic.h" -#include "../lib/DataTypeConverter.h" -#include "../lib/Profiler.h" -#include "../lib/JsonRPCRequest.h" -#include "../model/gradido/Transaction.h" - -#include "Poco/Thread.h" -#include "Poco/DateTime.h" -#include "Poco/JSON/Stringifier.h" - -enum PageType -{ - PAGE_CHOOSE_TEST, - PAGE_RUN_4_SET_TEST, - PAGE_GET_TRANSACTION_RPC_CALL -}; - -%> -<%% - const char* pageName = "Node Server Test"; - PageType page = PAGE_CHOOSE_TEST; - Poco::AutoPtr node_server; - Poco::AutoPtr node_server2; - Poco::AutoPtr user; - Poco::AutoPtr hedera_topic; - Poco::AutoPtr hedera_topic2; - int hedera_timeout = 4; - int sleep_ms_between_transactions = 1000; - - bool steps[8]; memset(steps, 1, 8 * sizeof(bool)); - - - if(!form.empty()) - { - auto node_server_id_string = form.get("test-node-servers", ""); - if(node_server_id_string != "") { - int node_server_id = 0; - if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(node_server_id_string, node_server_id )) { - node_server = controller::NodeServer::load(node_server_id); - } - } - node_server_id_string = form.get("test-node-servers2", ""); - if(node_server_id_string != "") { - int node_server_id = 0; - if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(node_server_id_string, node_server_id )) { - node_server2 = controller::NodeServer::load(node_server_id); - } - } - auto topic_id_string = form.get("test-hedera-topic", ""); - if(topic_id_string != "") { - int topic_id = 0; - if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(topic_id_string, topic_id)) { - hedera_topic = controller::HederaTopic::load(topic_id); - } - } - topic_id_string = form.get("test-hedera-topic2", ""); - if(topic_id_string != "") { - int topic_id = 0; - if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(topic_id_string, topic_id)) { - hedera_topic2 = controller::HederaTopic::load(topic_id); - } - } - auto test_timeout_string = form.get("test-timeout", ""); - if(test_timeout_string != "") { - DataTypeConverter::strToInt(test_timeout_string, hedera_timeout); - } - auto test_part_timeout_string = form.get("test-part-timeout", ""); - if(test_part_timeout_string != "") { - DataTypeConverter::strToInt(test_part_timeout_string, sleep_ms_between_transactions); - } - auto submit = form.get("submit", ""); - if(submit == "Run 6-Test") { - page = PAGE_RUN_4_SET_TEST; - } else if(submit == "json-rpc getTransactions") { - page = PAGE_GET_TRANSACTION_RPC_CALL; - } - std::string step_temp; - for(int i = 0; i < 8; i++) { - std::string name = "step-"; - name += std::to_string(i+2); - step_temp = form.get(name, ""); - if(step_temp == "1") { - steps[i] = true; - } else { - steps[i] = false; - } - } - } - - auto node_servers = controller::NodeServer::load(model::table::NODE_SERVER_GRADIDO_NODE); - auto hedera_topics = controller::HederaTopic::listAll(); - -%><%@ include file="header_large.cpsp" %> -<%= getErrorsHtml() %> -
- -
- - -
-
style="display:block" <% } %>> -
-

Test 6-Set (3 AddMember, Creation, 2 Transfer) -

-
-
-

1. Create three new accounts and show user public keys for comparisation

-

checked="checked" <% } %> name="step-2" value="1"/> 2. Send a add-member transaction to hedera topic with one signature (first user)

-

checked="checked" <% } %> name="step-3" value="1"/> 3. Send a add-member transaction to hedera topic with two signatures (first user and second user)

-

checked="checked" <% } %> name="step-4" value="1"/> 4. Send a creation transaction to second user, signed by first user

-

checked="checked" <% } %> name="step-5" value="1"/> 5. Send a transfer transaction from second user to first user signed by second user

-

checked="checked" <% } %> name="step-6" value="1"/> 6. Send a add-member transaction to hedera topic 2 with one signature (third user)

-

checked="checked" <% } %> name="step-7" value="1"/> 7. Send a cross group transfer from second user to third user signed by second user

-

checked="checked" <% } %> name="step-8" value="1"/> 8. Wait x seconds to give hedera time to process transactions

-

checked="checked" <% } %> name="step-9" value="1"/> 9. Ask choosen node for transaction and print result

-
- Group 1 - - <% if(node_servers.size() == 0) { %> - Edit Node-Servers - <% } %> - - - <% if(hedera_topics.size() == 0) { %> - Edit Hedera-Topics - <% } %> - -
-
- Group 2 - - <% if(node_servers.size() == 0) { %> - Edit Node-Servers - <% } %> - - - <% if(hedera_topics.size() == 0) { %> - Edit Hedera-Topics - <% } %> - -
- - - seconds - - ms - -
-
-
-
style="display:block" <% } %>> -
-

Test 4-Set (2 AddMember, Creation, Transfer) -

-
-
- - <% if(node_servers.size() == 0) { %> - Edit Node-Servers - <% } %> - - -
-
-
- <% if(PAGE_RUN_4_SET_TEST == page && !hedera_topic.isNull() && !node_server.isNull()) { %> -
    -
  • -

    1. Create three new accounts and show user public keys for comparisation:

    - <% - Profiler time2; - auto group_id = hedera_topic->getModel()->getGroupId(); - auto group_id2 = hedera_topic2->getModel()->getGroupId(); - auto user_group = controller::Group::load(group_id); - auto user_group2 = controller::Group::load(group_id2); - auto mnemonic_type = ServerConfig::MNEMONIC_BIP0039_SORTED_ORDER; - - std::string password1 = "hsaj(2askaslASlllak3wjjeudsaj"; - auto user_1 = controller::User::create("testEmail@google.de", "Max", "Mustermann", group_id); - auto passphrase_1 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); - auto gradido_key_pair_1 = KeyPairEd25519::create(passphrase_1); - user_1->setGradidoKeyPair(gradido_key_pair_1); - user_1->login(password1); - - std::string password2 = "uweia8saiSale,dsasA"; - auto user_2 = controller::User::create("testEmail2@google.de", "MJax", "Mustrermann", group_id); - auto passphrase_2 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); - auto gradido_key_pair_2 = KeyPairEd25519::create(passphrase_2); - user_2->setGradidoKeyPair(gradido_key_pair_2); - user_2->login(password2); - - std::string password3 = "jaue_skaiellasealaK"; - auto user_3 = controller::User::create("testEmail3@gmail.com", "Morpheus", "Miaufull", group_id2); - auto passphrase_3 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); - auto gradido_key_pair_3 = KeyPairEd25519::create(passphrase_3); - user_3->setGradidoKeyPair(gradido_key_pair_3); - user_3->login(password3); - %> -
    <%= user_group->getModel()->getName() %> -

    User 1: <%= user_1->getPublicHex() %>

    -

    User 2: <%= user_2->getPublicHex() %>

    -
    -
    <%= user_group2->getModel()->getName() %> -

    User 3: <%= user_3->getPublicHex() %>

    -
    -

    Time: <%= time2.string() %> -

  • -
  • -

    2. Send a add-member transaction to hedera topic with one signature (first user)

    - <% - time2.reset(); - if(!steps[0]) { %> -

    skipped

    - <% } else { - auto transaction1 = model::gradido::Transaction::createGroupMemberUpdate(user_1, user_group); - transaction1->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(1); - transaction1->sign(user_1); - auto transaction1_json = transaction1->getTransactionAsJson(true); - %> -

    <%= DataTypeConverter::replaceNewLineWithBr(transaction1_json) %>

    - <% } %> -

    Time: <%= time2.string() %> -

  • -
  • -

    3. Send a add-member transaction to hedera topic with two signatures (first user and second user)

    - <% - time2.reset(); - if(!steps[1]) { %> -

    skipped

    - <% } else { - auto transaction2 = model::gradido::Transaction::createGroupMemberUpdate(user_2, user_group); - transaction2->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(2); - transaction2->sign(user_2); - // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction2->sign(user_1); - auto transaction2_json = transaction2->getTransactionAsJson(true); - %> -

    <%= DataTypeConverter::replaceNewLineWithBr(transaction2_json) %>

    - <% } %> -

    Time: <%= time2.string() %> -

  • -
  • -

    4. Send a creation transaction to second user, signed by first user

    - <% - time2.reset(); - if(!steps[2]) { %> -

    skipped

    - <% } else { - auto transaction3 = model::gradido::Transaction::createCreation(user_2, 10000000, Poco::DateTime(), "Test Creation"); - // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction3->sign(user_1); - auto transaction3_json = transaction3->getTransactionAsJson(true); - %> -

    <%= DataTypeConverter::replaceNewLineWithBr(transaction3_json) %>

    - <% } %> -

    Time: <%= time2.string() %>

    -
  • -
  • -

    5. Send a transfer transaction from second user to first user signed by second user

    - <% - time2.reset(); - if(!steps[3]) { %> -

    skipped

    - <% } else { - auto user_1_pubkey = user_1->getModel()->getPublicKeyCopy(); - auto transaction4 = model::gradido::Transaction::createTransfer(user_2, user_1_pubkey, user_group, 5000000, "Test Transfer"); - // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction4[0]->sign(user_2); - auto transaction4_json = transaction4[0]->getTransactionAsJson(true); - %> -

    <%= DataTypeConverter::replaceNewLineWithBr(transaction4_json) %>

    - <% } %> -

    Time: <%= time2.string() %>

    -
  • -
  • -

    6. Send a add-member transaction to hedera topic 2 with one signature (third user)

    - <% - time2.reset(); - if(!steps[4]) { %> -

    skipped

    - <% } else { - auto transaction5 = model::gradido::Transaction::createGroupMemberUpdate(user_3, user_group2); - transaction5->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(1); - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction5->sign(user_3); - auto transaction5_json = transaction5->getTransactionAsJson(true); - %> -

    <%= DataTypeConverter::replaceNewLineWithBr(transaction5_json) %>

    - <% } %> -

    Time: <%= time2.string() %>

    -
  • -
  • -

    7. Send a cross group transfer from second user to third user signed by second user

    - <% - time2.reset(); - if(!steps[5]) { %> -

    skipped

    - <% } else { - auto user_3_pubkey = user_3->getModel()->getPublicKeyCopy(); - auto transaction6 = model::gradido::Transaction::createTransfer(user_2, user_3_pubkey, user_group2, 4000000, "Test Group Transfer", false); - if(!transaction6.size()) { - %> - - <% - } else { - Poco::Thread::sleep(sleep_ms_between_transactions); - transaction6[0]->sign(user_2); - auto transaction6_json = transaction6[0]->getTransactionAsJson(true); - auto paired_transaction = transaction6[0]->getPairedTransaction(); - %> -

    <%= DataTypeConverter::replaceNewLineWithBr(transaction6_json) %>

    - <% if(!paired_transaction.isNull()) { - auto transaction6_2_json = paired_transaction->getTransactionAsJson(true); - %>

    <%= DataTypeConverter::replaceNewLineWithBr(transaction6_2_json) %>

    - <% } %> - <% } %> - <% } %> -

    Time: <%= time2.string() %>

    -
  • -
  • -

    8. Wait <%= hedera_timeout %> seconds to give hedera time to process transactions

    - <% if(!steps[6]) { %> -

    skipped

    - <% } else { - Poco::Thread::sleep(hedera_timeout * 1000); - } %> -
  • -
  • -

    9. Ask choosen node for transaction and print result

    - <% time2.reset(); - if(!steps[7] || node_server.isNull()) { - %>

    skipped

    - <% } else { - auto node_server_model = node_server->getModel(); - JsonRPCRequest jsonrpc(node_server_model->getUrl(), node_server_model->getPort()); - Poco::JSON::Object params; - params.set("groupAlias", user_group->getModel()->getAlias()); - params.set("lastKnownSequenceNumber", 0); - auto gn_answear = jsonrpc.request("getTransactions", params); - if(!gn_answear.isNull()) { - std::stringstream ss; - Poco::JSON::Stringifier::stringify(gn_answear, ss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER); - std::string answear_string = ss.str(); %> - <%= DataTypeConverter::replaceNewLineWithBr(answear_string) %><% - } - } %> -

    Time: <%= time2.string() %>

    -
  • -
- <% } else if(PAGE_GET_TRANSACTION_RPC_CALL == page && !node_server.isNull()) { - Profiler time3; - auto node_server_model = node_server->getModel(); - auto user_group = controller::Group::load(node_server_model->getGroupId()); - JsonRPCRequest jsonrpc(node_server_model->getUrl(), node_server_model->getPort()); - Poco::JSON::Object params; - params.set("groupAlias", user_group->getModel()->getAlias()); - params.set("lastKnownSequenceNumber", 0); - auto gn_answear = jsonrpc.request("getTransactions", params); - if(!gn_answear.isNull()) { - std::stringstream ss; - Poco::JSON::Stringifier::stringify(gn_answear, ss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER); - std::string answear_string = ss.str();%> - <%= DataTypeConverter::replaceNewLineWithBr(answear_string) %><% - } - %> -

Time: <%= time3.string() %>

- <% } %> - -
- -<%@ include file="footer.cpsp" %> +<%@ page class="AdminNodeServerTestPage" %> +<%@ page form="true" %> +<%@ page compressed="true" %> +<%@ page baseClass="PageRequestMessagedHandler" %> +<%@ header include="PageRequestMessagedHandler.h" %> +<%! + +#include "../controller/NodeServer.h" +#include "../controller/User.h" +#include "../controller/HederaTopic.h" +#include "../lib/DataTypeConverter.h" +#include "../lib/Profiler.h" +#include "../lib/JsonRPCRequest.h" +#include "../model/gradido/Transaction.h" + +#include "Poco/Thread.h" +#include "Poco/DateTime.h" +#include "Poco/JSON/Stringifier.h" + +enum PageType +{ + PAGE_CHOOSE_TEST, + PAGE_RUN_4_SET_TEST, + PAGE_GET_TRANSACTION_RPC_CALL +}; + +%> +<%% + const char* pageName = "Node Server Test"; + PageType page = PAGE_CHOOSE_TEST; + Poco::AutoPtr node_server; + Poco::AutoPtr node_server2; + Poco::AutoPtr user; + Poco::AutoPtr hedera_topic; + Poco::AutoPtr hedera_topic2; + int hedera_timeout = 4; + int sleep_ms_between_transactions = 1000; + + bool steps[8]; memset(steps, 1, 8 * sizeof(bool)); + + + if(!form.empty()) + { + auto node_server_id_string = form.get("test-node-servers", ""); + if(node_server_id_string != "") { + int node_server_id = 0; + if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(node_server_id_string, node_server_id )) { + node_server = controller::NodeServer::load(node_server_id); + } + } + node_server_id_string = form.get("test-node-servers2", ""); + if(node_server_id_string != "") { + int node_server_id = 0; + if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(node_server_id_string, node_server_id )) { + node_server2 = controller::NodeServer::load(node_server_id); + } + } + auto topic_id_string = form.get("test-hedera-topic", ""); + if(topic_id_string != "") { + int topic_id = 0; + if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(topic_id_string, topic_id)) { + hedera_topic = controller::HederaTopic::load(topic_id); + } + } + topic_id_string = form.get("test-hedera-topic2", ""); + if(topic_id_string != "") { + int topic_id = 0; + if(DataTypeConverter::NUMBER_PARSE_OKAY == DataTypeConverter::strToInt(topic_id_string, topic_id)) { + hedera_topic2 = controller::HederaTopic::load(topic_id); + } + } + auto test_timeout_string = form.get("test-timeout", ""); + if(test_timeout_string != "") { + DataTypeConverter::strToInt(test_timeout_string, hedera_timeout); + } + auto test_part_timeout_string = form.get("test-part-timeout", ""); + if(test_part_timeout_string != "") { + DataTypeConverter::strToInt(test_part_timeout_string, sleep_ms_between_transactions); + } + auto submit = form.get("submit", ""); + if(submit == "Run 6-Test") { + page = PAGE_RUN_4_SET_TEST; + } else if(submit == "json-rpc getTransactions") { + page = PAGE_GET_TRANSACTION_RPC_CALL; + } + std::string step_temp; + for(int i = 0; i < 8; i++) { + std::string name = "step-"; + name += std::to_string(i+2); + step_temp = form.get(name, ""); + if(step_temp == "1") { + steps[i] = true; + } else { + steps[i] = false; + } + } + } + + auto node_servers = controller::NodeServer::load(model::table::NODE_SERVER_GRADIDO_NODE); + auto hedera_topics = controller::HederaTopic::listAll(); + +%><%@ include file="header_large.cpsp" %> +<%= getErrorsHtml() %> +
+ +
+ + +
+
style="display:block" <% } %>> +
+

Test 6-Set (3 AddMember, Creation, 2 Transfer) +

+
+
+

1. Create three new accounts and show user public keys for comparisation

+

checked="checked" <% } %> name="step-2" value="1"/> 2. Send a add-member transaction to hedera topic with one signature (first user)

+

checked="checked" <% } %> name="step-3" value="1"/> 3. Send a add-member transaction to hedera topic with two signatures (first user and second user)

+

checked="checked" <% } %> name="step-4" value="1"/> 4. Send a creation transaction to second user, signed by first user

+

checked="checked" <% } %> name="step-5" value="1"/> 5. Send a transfer transaction from second user to first user signed by second user

+

checked="checked" <% } %> name="step-6" value="1"/> 6. Send a add-member transaction to hedera topic 2 with one signature (third user)

+

checked="checked" <% } %> name="step-7" value="1"/> 7. Send a cross group transfer from second user to third user signed by second user

+

checked="checked" <% } %> name="step-8" value="1"/> 8. Wait x seconds to give hedera time to process transactions

+

checked="checked" <% } %> name="step-9" value="1"/> 9. Ask choosen node for transaction and print result

+
+ Group 1 + + <% if(node_servers.size() == 0) { %> + Edit Node-Servers + <% } %> + + + <% if(hedera_topics.size() == 0) { %> + Edit Hedera-Topics + <% } %> + +
+
+ Group 2 + + <% if(node_servers.size() == 0) { %> + Edit Node-Servers + <% } %> + + + <% if(hedera_topics.size() == 0) { %> + Edit Hedera-Topics + <% } %> + +
+ + + seconds + + ms + +
+
+
+
style="display:block" <% } %>> +
+

Test 4-Set (2 AddMember, Creation, Transfer) +

+
+
+ + <% if(node_servers.size() == 0) { %> + Edit Node-Servers + <% } %> + + +
+
+
+ <% if(PAGE_RUN_4_SET_TEST == page && !hedera_topic.isNull() && !node_server.isNull()) { %> +
    +
  • +

    1. Create three new accounts and show user public keys for comparisation:

    + <% + Profiler time2; + auto group_id = hedera_topic->getModel()->getGroupId(); + auto group_id2 = hedera_topic2->getModel()->getGroupId(); + auto user_group = controller::Group::load(group_id); + auto user_group2 = controller::Group::load(group_id2); + auto mnemonic_type = ServerConfig::MNEMONIC_BIP0039_SORTED_ORDER; + + std::string password1 = "hsaj(2askaslASlllak3wjjeudsaj"; + auto user_1 = controller::User::create("testEmail@google.de", "Max", "Mustermann", group_id); + auto passphrase_1 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); + auto gradido_key_pair_1 = KeyPairEd25519::create(passphrase_1); + user_1->setGradidoKeyPair(gradido_key_pair_1); + user_1->login(password1); + + std::string password2 = "uweia8saiSale,dsasA"; + auto user_2 = controller::User::create("testEmail2@google.de", "MJax", "Mustrermann", group_id); + auto passphrase_2 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); + auto gradido_key_pair_2 = KeyPairEd25519::create(passphrase_2); + user_2->setGradidoKeyPair(gradido_key_pair_2); + user_2->login(password2); + + std::string password3 = "jaue_skaiellasealaK"; + auto user_3 = controller::User::create("testEmail3@gmail.com", "Morpheus", "Miaufull", group_id2); + auto passphrase_3 = Passphrase::generate(&ServerConfig::g_Mnemonic_WordLists[mnemonic_type]); + auto gradido_key_pair_3 = KeyPairEd25519::create(passphrase_3); + user_3->setGradidoKeyPair(gradido_key_pair_3); + user_3->login(password3); + %> +
    <%= user_group->getModel()->getName() %> +

    User 1: <%= user_1->getPublicHex() %>

    +

    User 2: <%= user_2->getPublicHex() %>

    +
    +
    <%= user_group2->getModel()->getName() %> +

    User 3: <%= user_3->getPublicHex() %>

    +
    +

    Time: <%= time2.string() %> +

  • +
  • +

    2. Send a add-member transaction to hedera topic with one signature (first user)

    + <% + time2.reset(); + if(!steps[0]) { %> +

    skipped

    + <% } else { + auto transaction1 = model::gradido::Transaction::createGroupMemberUpdate(user_1, user_group); + transaction1->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(1); + transaction1->sign(user_1); + auto transaction1_json = transaction1->getTransactionAsJson(true); + %> +

    <%= DataTypeConverter::replaceNewLineWithBr(transaction1_json) %>

    + <% } %> +

    Time: <%= time2.string() %> +

  • +
  • +

    3. Send a add-member transaction to hedera topic with two signatures (first user and second user)

    + <% + time2.reset(); + if(!steps[1]) { %> +

    skipped

    + <% } else { + auto transaction2 = model::gradido::Transaction::createGroupMemberUpdate(user_2, user_group); + transaction2->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(2); + transaction2->sign(user_2); + // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction2->sign(user_1); + auto transaction2_json = transaction2->getTransactionAsJson(true); + %> +

    <%= DataTypeConverter::replaceNewLineWithBr(transaction2_json) %>

    + <% } %> +

    Time: <%= time2.string() %> +

  • +
  • +

    4. Send a creation transaction to second user, signed by first user

    + <% + time2.reset(); + if(!steps[2]) { %> +

    skipped

    + <% } else { + auto transaction3 = model::gradido::Transaction::createCreation(user_2, 10000000, Poco::DateTime(), "Test Creation"); + // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction3->sign(user_1); + auto transaction3_json = transaction3->getTransactionAsJson(true); + %> +

    <%= DataTypeConverter::replaceNewLineWithBr(transaction3_json) %>

    + <% } %> +

    Time: <%= time2.string() %>

    +
  • +
  • +

    5. Send a transfer transaction from second user to first user signed by second user

    + <% + time2.reset(); + if(!steps[3]) { %> +

    skipped

    + <% } else { + auto user_1_pubkey = user_1->getModel()->getPublicKeyCopy(); + auto transaction4 = model::gradido::Transaction::createTransfer(user_2, user_1_pubkey, user_group, 5000000, "Test Transfer"); + // wait before sending fourth transaction, gn seems to crash by more than 3 transaction at nearly the same time + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction4[0]->sign(user_2); + auto transaction4_json = transaction4[0]->getTransactionAsJson(true); + %> +

    <%= DataTypeConverter::replaceNewLineWithBr(transaction4_json) %>

    + <% } %> +

    Time: <%= time2.string() %>

    +
  • +
  • +

    6. Send a add-member transaction to hedera topic 2 with one signature (third user)

    + <% + time2.reset(); + if(!steps[4]) { %> +

    skipped

    + <% } else { + auto transaction5 = model::gradido::Transaction::createGroupMemberUpdate(user_3, user_group2); + transaction5->getTransactionBody()->getGroupMemberUpdate()->setMinSignatureCount(1); + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction5->sign(user_3); + auto transaction5_json = transaction5->getTransactionAsJson(true); + %> +

    <%= DataTypeConverter::replaceNewLineWithBr(transaction5_json) %>

    + <% } %> +

    Time: <%= time2.string() %>

    +
  • +
  • +

    7. Send a cross group transfer from second user to third user signed by second user

    + <% + time2.reset(); + if(!steps[5]) { %> +

    skipped

    + <% } else { + auto user_3_pubkey = user_3->getModel()->getPublicKeyCopy(); + auto transaction6 = model::gradido::Transaction::createTransfer(user_2, user_3_pubkey, user_group2, 4000000, "Test Group Transfer", false); + if(!transaction6.size()) { + %> + + <% + } else { + Poco::Thread::sleep(sleep_ms_between_transactions); + transaction6[0]->sign(user_2); + auto transaction6_json = transaction6[0]->getTransactionAsJson(true); + auto paired_transaction = transaction6[0]->getPairedTransaction(); + %> +

    <%= DataTypeConverter::replaceNewLineWithBr(transaction6_json) %>

    + <% if(!paired_transaction.isNull()) { + auto transaction6_2_json = paired_transaction->getTransactionAsJson(true); + %>

    <%= DataTypeConverter::replaceNewLineWithBr(transaction6_2_json) %>

    + <% } %> + <% } %> + <% } %> +

    Time: <%= time2.string() %>

    +
  • +
  • +

    8. Wait <%= hedera_timeout %> seconds to give hedera time to process transactions

    + <% if(!steps[6]) { %> +

    skipped

    + <% } else { + Poco::Thread::sleep(hedera_timeout * 1000); + } %> +
  • +
  • +

    9. Ask choosen node for transaction and print result

    + <% time2.reset(); + if(!steps[7] || node_server.isNull()) { + %>

    skipped

    + <% } else { + auto node_server_model = node_server->getModel(); + JsonRPCRequest jsonrpc(node_server_model->getUrl(), node_server_model->getPort()); + Poco::JSON::Object params; + params.set("groupAlias", user_group->getModel()->getAlias()); + params.set("lastKnownSequenceNumber", 0); + auto gn_answear = jsonrpc.request("getTransactions", params); + if(!gn_answear.isNull()) { + std::stringstream ss; + Poco::JSON::Stringifier::stringify(gn_answear, ss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER); + std::string answear_string = ss.str(); %> + <%= DataTypeConverter::replaceNewLineWithBr(answear_string) %><% + } + } %> +

    Time: <%= time2.string() %>

    +
  • +
+ <% } else if(PAGE_GET_TRANSACTION_RPC_CALL == page && !node_server.isNull()) { + Profiler time3; + auto node_server_model = node_server->getModel(); + auto user_group = controller::Group::load(node_server_model->getGroupId()); + JsonRPCRequest jsonrpc(node_server_model->getUrl(), node_server_model->getPort()); + Poco::JSON::Object params; + params.set("groupAlias", user_group->getModel()->getAlias()); + params.set("lastKnownSequenceNumber", 0); + auto gn_answear = jsonrpc.request("getTransactions", params); + if(!gn_answear.isNull()) { + std::stringstream ss; + Poco::JSON::Stringifier::stringify(gn_answear, ss, 4, -1, Poco::JSON_PRESERVE_KEY_ORDER); + std::string answear_string = ss.str();%> + <%= DataTypeConverter::replaceNewLineWithBr(answear_string) %><% + } + %> +

Time: <%= time3.string() %>

+ <% } %> + +
+ +<%@ include file="footer.cpsp" %>