repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
evias/nem-php | src/Models/MosaicLevy.php | MosaicLevy.serialize | public function serialize($parameters = null)
{
// shortcuts
$serializer = $this->getSerializer();
$nisData = $this->toDTO();
if (empty($nisData)) {
$emptyLevy = $serializer->serializeInt(0);
return $emptyLevy;
}
// serialize
$type = $serializer->serializeInt($nisData["type"]);
$recipient = $serializer->serializeString($nisData["recipient"]);
$fee = $serializer->serializeLong($nisData["fee"]);
$mosaic = $this->mosaicId()->serialize();
// prepend size on 4 bytes + concatenate UInt8
return $this->getSerializer()
->aggregate($type, $recipient, $mosaic, $fee);
} | php | public function serialize($parameters = null)
{
// shortcuts
$serializer = $this->getSerializer();
$nisData = $this->toDTO();
if (empty($nisData)) {
$emptyLevy = $serializer->serializeInt(0);
return $emptyLevy;
}
// serialize
$type = $serializer->serializeInt($nisData["type"]);
$recipient = $serializer->serializeString($nisData["recipient"]);
$fee = $serializer->serializeLong($nisData["fee"]);
$mosaic = $this->mosaicId()->serialize();
// prepend size on 4 bytes + concatenate UInt8
return $this->getSerializer()
->aggregate($type, $recipient, $mosaic, $fee);
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"// shortcuts",
"$",
"serializer",
"=",
"$",
"this",
"->",
"getSerializer",
"(",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
")",
";",
"if",
"(",
"e... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *Mosaic Levy* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"Mosaic",
"Levy",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicLevy.php#L98-L118 |
evias/nem-php | src/Core/Serializer.php | Serializer.serialize | public function serialize(/*mixed*/ $data)
{
if (null === $data) {
return $this->serializeInt(null);
}
elseif (is_array($data)) {
return $this->serializeUInt8($data);
}
elseif (is_integer($data)) {
return $this->serializeLong($data);
}
elseif (is_string($data)) {
return $this->serializeString($data);
}
elseif ($data instanceof Serializable) {
return $data->serialize();
}
throw new RuntimeException("Invalid parameter provided to \\NEM\\Core\\Serialize::serialize().");
} | php | public function serialize(/*mixed*/ $data)
{
if (null === $data) {
return $this->serializeInt(null);
}
elseif (is_array($data)) {
return $this->serializeUInt8($data);
}
elseif (is_integer($data)) {
return $this->serializeLong($data);
}
elseif (is_string($data)) {
return $this->serializeString($data);
}
elseif ($data instanceof Serializable) {
return $data->serialize();
}
throw new RuntimeException("Invalid parameter provided to \\NEM\\Core\\Serialize::serialize().");
} | [
"public",
"function",
"serialize",
"(",
"/*mixed*/",
"$",
"data",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"data",
")",
"{",
"return",
"$",
"this",
"->",
"serializeInt",
"(",
"null",
")",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"data",
")",
... | Serialize any input for the NEM network.
@param array|string|integer|\NEM\Core\Serializer $data
@return array Returns a byte-array with values in UInt8 representation.
@throws RuntimeException On unrecognized `data` argument. | [
"Serialize",
"any",
"input",
"for",
"the",
"NEM",
"network",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Serializer.php#L95-L114 |
evias/nem-php | src/Core/Serializer.php | Serializer.serializeInt | public function serializeInt(int $number = null)
{
if (null === $number) {
return $this->serializeInt(self::NULL_SENTINEL);
}
else {
$uint8 = [
$number & 0xff,
($number >> 8) & 0xff,
($number >> 16) & 0xff,
($number >> 24) & 0xff
];
}
return $uint8;
} | php | public function serializeInt(int $number = null)
{
if (null === $number) {
return $this->serializeInt(self::NULL_SENTINEL);
}
else {
$uint8 = [
$number & 0xff,
($number >> 8) & 0xff,
($number >> 16) & 0xff,
($number >> 24) & 0xff
];
}
return $uint8;
} | [
"public",
"function",
"serializeInt",
"(",
"int",
"$",
"number",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"number",
")",
"{",
"return",
"$",
"this",
"->",
"serializeInt",
"(",
"self",
"::",
"NULL_SENTINEL",
")",
";",
"}",
"else",
"{",
"$... | Internal method to serialize a decimal number into a
Integer on 4 Bytes.
This method is used in all other serializeX methods and
should not be used directly from outside the NEM SDK.
@internal This method should not be used directly
@param integer $number
@return array Returns a byte-array with values in UInt8 representation. | [
"Internal",
"method",
"to",
"serialize",
"a",
"decimal",
"number",
"into",
"a",
"Integer",
"on",
"4",
"Bytes",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Serializer.php#L128-L143 |
evias/nem-php | src/Core/Serializer.php | Serializer.serializeString | public function serializeString(string $str = null)
{
if (null === $str) {
$uint8 = $this->serializeInt(null);
}
else {
// prepend size on 4 bytes
$count = strlen($str);
$uint8 = $this->serializeInt($count);
// UTF-8 to binary
for ($i = 0; $i < $count; $i++) {
$dec = Ed25519::chrToInt(substr($str, $i, 1));
array_push($uint8, $dec);
}
}
return $uint8;
} | php | public function serializeString(string $str = null)
{
if (null === $str) {
$uint8 = $this->serializeInt(null);
}
else {
// prepend size on 4 bytes
$count = strlen($str);
$uint8 = $this->serializeInt($count);
// UTF-8 to binary
for ($i = 0; $i < $count; $i++) {
$dec = Ed25519::chrToInt(substr($str, $i, 1));
array_push($uint8, $dec);
}
}
return $uint8;
} | [
"public",
"function",
"serializeString",
"(",
"string",
"$",
"str",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"str",
")",
"{",
"$",
"uint8",
"=",
"$",
"this",
"->",
"serializeInt",
"(",
"null",
")",
";",
"}",
"else",
"{",
"// prepend size... | Serialize string data. The serialized string will be prefixed
with a 4-bytes long Size field followed by the UInt8 representation
of the given `str`.
Takes in a string and returns an array of Unsigned Integers
on 8-bits.
@internal This method is used internally
@param string $str
@return array Returns a byte-array with values in UInt8 representation. | [
"Serialize",
"string",
"data",
".",
"The",
"serialized",
"string",
"will",
"be",
"prefixed",
"with",
"a",
"4",
"-",
"bytes",
"long",
"Size",
"field",
"followed",
"by",
"the",
"UInt8",
"representation",
"of",
"the",
"given",
"str",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Serializer.php#L157-L175 |
evias/nem-php | src/Core/Serializer.php | Serializer.serializeUInt8 | public function serializeUInt8(array $uint8Str = null)
{
if (null === $uint8Str) {
$uint8 = $this->serializeInt(null);
}
else {
// prepend size on 4 bytes
$count = count($uint8Str);
$uint8 = $this->serializeInt($count);
for ($i = 0; $i < $count; $i++) {
array_push($uint8, $uint8Str[$i]);
}
}
return $uint8;
} | php | public function serializeUInt8(array $uint8Str = null)
{
if (null === $uint8Str) {
$uint8 = $this->serializeInt(null);
}
else {
// prepend size on 4 bytes
$count = count($uint8Str);
$uint8 = $this->serializeInt($count);
for ($i = 0; $i < $count; $i++) {
array_push($uint8, $uint8Str[$i]);
}
}
return $uint8;
} | [
"public",
"function",
"serializeUInt8",
"(",
"array",
"$",
"uint8Str",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"uint8Str",
")",
"{",
"$",
"uint8",
"=",
"$",
"this",
"->",
"serializeInt",
"(",
"null",
")",
";",
"}",
"else",
"{",
"// prep... | Serialize unsigned char data. The serialized string will be prefixed
with a 4-bytes long Size field followed by the given `str`.
Takes in a 8bit-string and returns an array of Unsigned Integers
on 8-bits.
@internal This method is used internally
@param string $str
@return array Returns a byte-array with values in UInt8 representation. | [
"Serialize",
"unsigned",
"char",
"data",
".",
"The",
"serialized",
"string",
"will",
"be",
"prefixed",
"with",
"a",
"4",
"-",
"bytes",
"long",
"Size",
"field",
"followed",
"by",
"the",
"given",
"str",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Serializer.php#L188-L204 |
evias/nem-php | src/Core/Serializer.php | Serializer.serializeLong | public function serializeLong(int $long = null)
{
if (null === $long) {
// long on 8 bytes always
$uint8 = array_merge($this->serializeInt(null), $this->serializeInt(0));
}
else {
// prepend size on 4 bytes
$uint64L = $this->serializeInt($long);
$uint64H = $this->serializeInt($long >> 32);
$uint8 = array_merge($uint64L, $uint64H);
if (($len = count($uint8)) === 8)
// job done
return $uint8;
// right padding to 8 bytes
for ($i = 0, $done = 8 - $len; $i < $done; $i++) {
array_push($uint8, 0);
}
}
return $uint8;
} | php | public function serializeLong(int $long = null)
{
if (null === $long) {
// long on 8 bytes always
$uint8 = array_merge($this->serializeInt(null), $this->serializeInt(0));
}
else {
// prepend size on 4 bytes
$uint64L = $this->serializeInt($long);
$uint64H = $this->serializeInt($long >> 32);
$uint8 = array_merge($uint64L, $uint64H);
if (($len = count($uint8)) === 8)
// job done
return $uint8;
// right padding to 8 bytes
for ($i = 0, $done = 8 - $len; $i < $done; $i++) {
array_push($uint8, 0);
}
}
return $uint8;
} | [
"public",
"function",
"serializeLong",
"(",
"int",
"$",
"long",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"long",
")",
"{",
"// long on 8 bytes always",
"$",
"uint8",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"serializeInt",
"(",
"null",
")... | Serialize UInt64 numbers. This corresponds to the `long` variable type
in C.
@param integer $long
@return array | [
"Serialize",
"UInt64",
"numbers",
".",
"This",
"corresponds",
"to",
"the",
"long",
"variable",
"type",
"in",
"C",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Serializer.php#L213-L236 |
evias/nem-php | src/Core/Serializer.php | Serializer.aggregate | public function aggregate(/* [array $uint8_1, array $uint8_2, ...] */)
{
// read dynamic arguments
$count = func_num_args();
if (! $count) {
return [];
}
// interpret dynamic arguments and concatenate
// byte arrays into one aggregated byte array `concat`.
$concat = [];
$length = 0;
for ($i = 0; $i < $count; $i++) {
$argument = func_get_arg($i);
if (! is_array($argument)) {
// object is not serialized yet
$argument = $this->serialize($argument);
}
$concat = array_merge($concat, $argument);
$length += count($argument);
}
// prepend size on 4 bytes
$output = $this->serializeInt($length);
// append serialized parts
$output = array_merge($output, $concat);
return $output;
} | php | public function aggregate(/* [array $uint8_1, array $uint8_2, ...] */)
{
// read dynamic arguments
$count = func_num_args();
if (! $count) {
return [];
}
// interpret dynamic arguments and concatenate
// byte arrays into one aggregated byte array `concat`.
$concat = [];
$length = 0;
for ($i = 0; $i < $count; $i++) {
$argument = func_get_arg($i);
if (! is_array($argument)) {
// object is not serialized yet
$argument = $this->serialize($argument);
}
$concat = array_merge($concat, $argument);
$length += count($argument);
}
// prepend size on 4 bytes
$output = $this->serializeInt($length);
// append serialized parts
$output = array_merge($output, $concat);
return $output;
} | [
"public",
"function",
"aggregate",
"(",
"/* [array $uint8_1, array $uint8_2, ...] */",
")",
"{",
"// read dynamic arguments",
"$",
"count",
"=",
"func_num_args",
"(",
")",
";",
"if",
"(",
"!",
"$",
"count",
")",
"{",
"return",
"[",
"]",
";",
"}",
"// interpret d... | This method lets you aggregate multiple serialized
byte arrays.
It will also prepend a size on 4 bytes representing
the *count of the merged/aggregated byte arrays*.
This method accepts *any* count of array arguments.
The passed array must contain UInt8 representation
of bytes (see serializeX methods).
@param array $uint8_1
@param array $uint8_2
@param array $uint8_X
@return array | [
"This",
"method",
"lets",
"you",
"aggregate",
"multiple",
"serialized",
"byte",
"arrays",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Serializer.php#L254-L283 |
evias/nem-php | src/Models/Account.php | Account.toDTO | public function toDTO($filterByKey = null)
{
$toDTO = [
"account" => [
"address" => $this->address()->toClean(),
"balance" => $this->balance()->toMicro(),
"vestedBalance" => $this->vestedBalance()->toMicro(),
"importance" => $this->importance/*()->toScientific()*/,
"publicKey" => $this->publicKey,
"label" => $this->label,
"harvestedBlocks" => $this->harvestedBlocks,
"multisigInfo" => $this->multisigInfo()->toDTO(),
],
"meta" => [
"status" => $this->status,
"remoteStatus" => $this->remoteStatus,
"cosignatoryOf" => $this->cosignatoryOf()->toDTO(),
"cosignatories" => $this->cosignatories()->toDTO(),
]
];
if ($filterByKey && isset($toDTO[$filterByKey]))
return $toDTO[$filterByKey];
return $toDTO;
} | php | public function toDTO($filterByKey = null)
{
$toDTO = [
"account" => [
"address" => $this->address()->toClean(),
"balance" => $this->balance()->toMicro(),
"vestedBalance" => $this->vestedBalance()->toMicro(),
"importance" => $this->importance/*()->toScientific()*/,
"publicKey" => $this->publicKey,
"label" => $this->label,
"harvestedBlocks" => $this->harvestedBlocks,
"multisigInfo" => $this->multisigInfo()->toDTO(),
],
"meta" => [
"status" => $this->status,
"remoteStatus" => $this->remoteStatus,
"cosignatoryOf" => $this->cosignatoryOf()->toDTO(),
"cosignatories" => $this->cosignatories()->toDTO(),
]
];
if ($filterByKey && isset($toDTO[$filterByKey]))
return $toDTO[$filterByKey];
return $toDTO;
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"$",
"toDTO",
"=",
"[",
"\"account\"",
"=>",
"[",
"\"address\"",
"=>",
"$",
"this",
"->",
"address",
"(",
")",
"->",
"toClean",
"(",
")",
",",
"\"balance\"",
"=>",
"$",
"t... | Account DTO represents NIS API's [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair).
@see [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair)
@return array Associative array containing a NIS *compliable* account representation. | [
"Account",
"DTO",
"represents",
"NIS",
"API",
"s",
"[",
"AccountMetaDataPair",
"]",
"(",
"https",
":",
"//",
"bob",
".",
"nem",
".",
"ninja",
"/",
"docs",
"/",
"#accountMetaDataPair",
")",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Account.php#L76-L101 |
evias/nem-php | src/Models/Account.php | Account.cosignatoryOf | public function cosignatoryOf(array $data = null)
{
$multisigs = $data ?: $this->getAttribute("cosignatoryOf") ?: [];
return (new CollectionMutator())->mutate("account", $multisigs);
} | php | public function cosignatoryOf(array $data = null)
{
$multisigs = $data ?: $this->getAttribute("cosignatoryOf") ?: [];
return (new CollectionMutator())->mutate("account", $multisigs);
} | [
"public",
"function",
"cosignatoryOf",
"(",
"array",
"$",
"data",
"=",
"null",
")",
"{",
"$",
"multisigs",
"=",
"$",
"data",
"?",
":",
"$",
"this",
"->",
"getAttribute",
"(",
"\"cosignatoryOf\"",
")",
"?",
":",
"[",
"]",
";",
"return",
"(",
"new",
"C... | Mutator for the cosignatoryOf object collection.
@return \NEM\Models\ModelCollection | [
"Mutator",
"for",
"the",
"cosignatoryOf",
"object",
"collection",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Account.php#L148-L152 |
evias/nem-php | src/Models/Account.php | Account.cosignatories | public function cosignatories(array $data = null)
{
$cosignatories = $data ?: $this->getAttribute("cosignatories") ?: [];
return (new CollectionMutator())->mutate("account", $cosignatories);
} | php | public function cosignatories(array $data = null)
{
$cosignatories = $data ?: $this->getAttribute("cosignatories") ?: [];
return (new CollectionMutator())->mutate("account", $cosignatories);
} | [
"public",
"function",
"cosignatories",
"(",
"array",
"$",
"data",
"=",
"null",
")",
"{",
"$",
"cosignatories",
"=",
"$",
"data",
"?",
":",
"$",
"this",
"->",
"getAttribute",
"(",
"\"cosignatories\"",
")",
"?",
":",
"[",
"]",
";",
"return",
"(",
"new",
... | Mutator for the cosignatories object collection.
@return \NEM\Models\ModelCollection | [
"Mutator",
"for",
"the",
"cosignatories",
"object",
"collection",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Account.php#L159-L163 |
evias/nem-php | src/Core/KeccakHasher.php | KeccakHasher.hash | static public function hash($algorithm, $data, $raw_output = false)
{
$hashBits = self::getHashBitLength($algorithm);
return Keccak::hash($data, (int) $hashBits, (bool) $raw_output);
} | php | static public function hash($algorithm, $data, $raw_output = false)
{
$hashBits = self::getHashBitLength($algorithm);
return Keccak::hash($data, (int) $hashBits, (bool) $raw_output);
} | [
"static",
"public",
"function",
"hash",
"(",
"$",
"algorithm",
",",
"$",
"data",
",",
"$",
"raw_output",
"=",
"false",
")",
"{",
"$",
"hashBits",
"=",
"self",
"::",
"getHashBitLength",
"(",
"$",
"algorithm",
")",
";",
"return",
"Keccak",
"::",
"hash",
... | Non-Incremental Keccak Hash implementation.
@param null|string|integer $algorithm The hashing algorithm or Hash Bit Length.
@param string|\NEM\Core\Buffer $data The data that needs to be hashed.
@param boolean $raw_output Whether to return raw data or a Hexadecimal hash.
@return string | [
"Non",
"-",
"Incremental",
"Keccak",
"Hash",
"implementation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/KeccakHasher.php#L72-L76 |
evias/nem-php | src/Core/KeccakHasher.php | KeccakHasher.getHashBitLength | static public function getHashBitLength($algorithm = null)
{
if (!$algorithm) {
return self::HASH_BIT_LENGTH;
}
if (is_integer($algorithm)) {
// direct hash-bit-length provided
return (int) $algorithm;
}
elseif (strpos(strtolower($algorithm), "keccak-") !== false) {
$bits = (int) substr($algorithm, -3); // keccak-256, keccak-512, etc.
if (! in_array($bits, [256, 228, 384, 512]))
$bits = 512;
return $bits;
}
return self::HASH_BIT_LENGTH;
} | php | static public function getHashBitLength($algorithm = null)
{
if (!$algorithm) {
return self::HASH_BIT_LENGTH;
}
if (is_integer($algorithm)) {
// direct hash-bit-length provided
return (int) $algorithm;
}
elseif (strpos(strtolower($algorithm), "keccak-") !== false) {
$bits = (int) substr($algorithm, -3); // keccak-256, keccak-512, etc.
if (! in_array($bits, [256, 228, 384, 512]))
$bits = 512;
return $bits;
}
return self::HASH_BIT_LENGTH;
} | [
"static",
"public",
"function",
"getHashBitLength",
"(",
"$",
"algorithm",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"algorithm",
")",
"{",
"return",
"self",
"::",
"HASH_BIT_LENGTH",
";",
"}",
"if",
"(",
"is_integer",
"(",
"$",
"algorithm",
")",
")",
... | Helper function used to determine each hash's Bits length
by a given `algorithm`.
The `algorithm` parameter can be a integer directly and should
then represent a Bits Length for generated Hashes.
@param null|string|integer $algorithm The hashing algorithm or Hashes' Bits Length.
@return integer | [
"Helper",
"function",
"used",
"to",
"determine",
"each",
"hash",
"s",
"Bits",
"length",
"by",
"a",
"given",
"algorithm",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/KeccakHasher.php#L88-L108 |
evias/nem-php | src/Mosaics/Template.php | Template.properties | public function properties(array $properties = null)
{
$data = [
new MosaicProperty(["name" => "divisibility", "value" => $this->divisibility]),
new MosaicProperty(["name" => "initialSupply", "value" => $this->initialSupply]),
new MosaicProperty(["name" => "supplyMutable", "value" => $this->supplyMutable]),
new MosaicProperty(["name" => "transferable", "value" => $this->transferable]),
];
return new MosaicProperties($data);
} | php | public function properties(array $properties = null)
{
$data = [
new MosaicProperty(["name" => "divisibility", "value" => $this->divisibility]),
new MosaicProperty(["name" => "initialSupply", "value" => $this->initialSupply]),
new MosaicProperty(["name" => "supplyMutable", "value" => $this->supplyMutable]),
new MosaicProperty(["name" => "transferable", "value" => $this->transferable]),
];
return new MosaicProperties($data);
} | [
"public",
"function",
"properties",
"(",
"array",
"$",
"properties",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"[",
"new",
"MosaicProperty",
"(",
"[",
"\"name\"",
"=>",
"\"divisibility\"",
",",
"\"value\"",
"=>",
"$",
"this",
"->",
"divisibility",
"]",
")",... | Mutator for `properties` relation.
This will return a NIS compliant collection of [MosaicProperties](https://bob.nem.ninja/docs/#mosaicProperties) object.
@param array $properties Array of MosaicProperty instances
@return \NEM\Models\MosaicProperties | [
"Mutator",
"for",
"properties",
"relation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Mosaics/Template.php#L96-L106 |
evias/nem-php | src/Traits/Connectable.php | Connectable.setProtocol | public function setProtocol($protocol)
{
$lowerProtocol = strtolower($protocol);
// handle special cases where protocol is not
// formatted as intended yet.
if ("websocket" == $lowerProtocol)
$lowerProtocol = "ws";
if (in_array($lowerProtocol, ["https", "wss"])) {
// provided secure type of protocol
$this->setUseSsl(true);
$lowerProtocol = substr($lowerProtocol, 0, -1);
}
$this->protocol = $lowerProtocol;
return $this;
} | php | public function setProtocol($protocol)
{
$lowerProtocol = strtolower($protocol);
// handle special cases where protocol is not
// formatted as intended yet.
if ("websocket" == $lowerProtocol)
$lowerProtocol = "ws";
if (in_array($lowerProtocol, ["https", "wss"])) {
// provided secure type of protocol
$this->setUseSsl(true);
$lowerProtocol = substr($lowerProtocol, 0, -1);
}
$this->protocol = $lowerProtocol;
return $this;
} | [
"public",
"function",
"setProtocol",
"(",
"$",
"protocol",
")",
"{",
"$",
"lowerProtocol",
"=",
"strtolower",
"(",
"$",
"protocol",
")",
";",
"// handle special cases where protocol is not",
"// formatted as intended yet.",
"if",
"(",
"\"websocket\"",
"==",
"$",
"lowe... | This method should implement a protocol
setter which will be used to determine
which Protocol is used in the Base URL.
@param string $protocol
@return \NEM\Contracts\HttpHandler | [
"This",
"method",
"should",
"implement",
"a",
"protocol",
"setter",
"which",
"will",
"be",
"used",
"to",
"determine",
"which",
"Protocol",
"is",
"used",
"in",
"the",
"Base",
"URL",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Traits/Connectable.php#L113-L131 |
evias/nem-php | src/Traits/Connectable.php | Connectable.getBasicAuth | public function getBasicAuth()
{
if (empty($this->basicAuth))
return "";
if (empty($this->basicAuth["username"]))
// Username cannot be empty in Basic Authentication
return "";
$username = $this->basicAuth["username"];
$password = isset($this->basicAuth["password"]) ? $this->basicAuth["password"] : "";
return sprintf("%s:%s@", $username, $password);
} | php | public function getBasicAuth()
{
if (empty($this->basicAuth))
return "";
if (empty($this->basicAuth["username"]))
// Username cannot be empty in Basic Authentication
return "";
$username = $this->basicAuth["username"];
$password = isset($this->basicAuth["password"]) ? $this->basicAuth["password"] : "";
return sprintf("%s:%s@", $username, $password);
} | [
"public",
"function",
"getBasicAuth",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"basicAuth",
")",
")",
"return",
"\"\"",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"basicAuth",
"[",
"\"username\"",
"]",
")",
")",
"// Username can... | This method returns the username:password@ format
string to perform Basic Authentication using the
URL.
@return [type] [description] | [
"This",
"method",
"returns",
"the",
"username",
":",
"password@",
"format",
"string",
"to",
"perform",
"Basic",
"Authentication",
"using",
"the",
"URL",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Traits/Connectable.php#L276-L288 |
evias/nem-php | src/Traits/Connectable.php | Connectable.getBaseUrl | public function getBaseUrl()
{
return $this->getScheme() . $this->getBasicAuth() . $this->getHost() . ":" . $this->getPort() . $this->getEndpoint();
} | php | public function getBaseUrl()
{
return $this->getScheme() . $this->getBasicAuth() . $this->getHost() . ":" . $this->getPort() . $this->getEndpoint();
} | [
"public",
"function",
"getBaseUrl",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"getScheme",
"(",
")",
".",
"$",
"this",
"->",
"getBasicAuth",
"(",
")",
".",
"$",
"this",
"->",
"getHost",
"(",
")",
".",
"\":\"",
".",
"$",
"this",
"->",
"getPort",
"... | Getter for `base_url` property.
@return string | [
"Getter",
"for",
"base_url",
"property",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Traits/Connectable.php#L295-L298 |
evias/nem-php | src/Traits/Connectable.php | Connectable.fillFromBaseUrl | public function fillFromBaseUrl($baseUrl)
{
$reg = "/^(https?):\/\/((www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6})(:([0-9]+))?/";
$matches = [];
$scheme = "http";
$host = "hugealice.nem.ninja";
$port = 7890;
if ((bool) preg_match_all($reg, $baseUrl, $matches)) {
$scheme = $matches[1][0];
$host = $matches[2][0];
$port = $matches[5][0];
}
$this->setUseSsl($scheme === "https");
$this->setProtocol($scheme);
$this->setHost($host);
$this->setPort((int) $port);
return $this;
} | php | public function fillFromBaseUrl($baseUrl)
{
$reg = "/^(https?):\/\/((www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6})(:([0-9]+))?/";
$matches = [];
$scheme = "http";
$host = "hugealice.nem.ninja";
$port = 7890;
if ((bool) preg_match_all($reg, $baseUrl, $matches)) {
$scheme = $matches[1][0];
$host = $matches[2][0];
$port = $matches[5][0];
}
$this->setUseSsl($scheme === "https");
$this->setProtocol($scheme);
$this->setHost($host);
$this->setPort((int) $port);
return $this;
} | [
"public",
"function",
"fillFromBaseUrl",
"(",
"$",
"baseUrl",
")",
"{",
"$",
"reg",
"=",
"\"/^(https?):\\/\\/((www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6})(:([0-9]+))?/\"",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"$",
"scheme",
"=",
"\"http\"",
";",
"$",
"h... | Helper class method to create a Connectabl object from
a fully qualified base url.
@param string $baseUrl
@return \NEM\Traits\Connectable | [
"Helper",
"class",
"method",
"to",
"create",
"a",
"Connectabl",
"object",
"from",
"a",
"fully",
"qualified",
"base",
"url",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Traits/Connectable.php#L316-L335 |
evias/nem-php | src/Infrastructure/ConnectionPool.php | ConnectionPool.getEndpoint | public function getEndpoint($forceNew = false)
{
$index = $forceNew === true ? ++$this->poolIndex : $this->poolIndex;
if ($index == count($this->nodes)) {
$index = 0;
}
if (!isset($this->endpoints[$this->network][$index])) {
$api = new API([
"use_ssl" => false,
"protocol" => "http",
"host" => $this->nodes[$this->network][$index],
"port" => 7890,
"endpoint" => "/",
]);
$this->endpoints[$this->network][$index] = $api;
}
$this->poolIndex = $index;
return $this->endpoints[$this->network][$index];
} | php | public function getEndpoint($forceNew = false)
{
$index = $forceNew === true ? ++$this->poolIndex : $this->poolIndex;
if ($index == count($this->nodes)) {
$index = 0;
}
if (!isset($this->endpoints[$this->network][$index])) {
$api = new API([
"use_ssl" => false,
"protocol" => "http",
"host" => $this->nodes[$this->network][$index],
"port" => 7890,
"endpoint" => "/",
]);
$this->endpoints[$this->network][$index] = $api;
}
$this->poolIndex = $index;
return $this->endpoints[$this->network][$index];
} | [
"public",
"function",
"getEndpoint",
"(",
"$",
"forceNew",
"=",
"false",
")",
"{",
"$",
"index",
"=",
"$",
"forceNew",
"===",
"true",
"?",
"++",
"$",
"this",
"->",
"poolIndex",
":",
"$",
"this",
"->",
"poolIndex",
";",
"if",
"(",
"$",
"index",
"==",
... | Get a connected API using the NEM node configured
at the current `poolIndex`
@param boolean $forceNew
@return \NEM\API | [
"Get",
"a",
"connected",
"API",
"using",
"the",
"NEM",
"node",
"configured",
"at",
"the",
"current",
"poolIndex"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/ConnectionPool.php#L102-L123 |
evias/nem-php | src/Core/Encoder.php | Encoder.hex2bin | public function hex2bin($hex)
{
$binLen = ceil(mb_strlen($hex) / 2);
// size validation while creating
$buffer = Buffer::fromHex($hex, $binLen);
return $buffer->getBinary();
} | php | public function hex2bin($hex)
{
$binLen = ceil(mb_strlen($hex) / 2);
// size validation while creating
$buffer = Buffer::fromHex($hex, $binLen);
return $buffer->getBinary();
} | [
"public",
"function",
"hex2bin",
"(",
"$",
"hex",
")",
"{",
"$",
"binLen",
"=",
"ceil",
"(",
"mb_strlen",
"(",
"$",
"hex",
")",
"/",
"2",
")",
";",
"// size validation while creating",
"$",
"buffer",
"=",
"Buffer",
"::",
"fromHex",
"(",
"$",
"hex",
","... | Encode a Hexadecimal string to corresponding string characters
using the Buffer class as a backbone.
@param string $hex
@return string | [
"Encode",
"a",
"Hexadecimal",
"string",
"to",
"corresponding",
"string",
"characters",
"using",
"the",
"Buffer",
"class",
"as",
"a",
"backbone",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encoder.php#L44-L51 |
evias/nem-php | src/Core/Encoder.php | Encoder.ua2bin | public function ua2bin(array $uint8)
{
$bin = "";
foreach ($uint8 as $ix => $char) {
$buf = Buffer::fromInt($char, 1);
$bin .= $buf->getBinary();
}
$buffer = new Buffer($bin);
return $buffer->getBinary();
} | php | public function ua2bin(array $uint8)
{
$bin = "";
foreach ($uint8 as $ix => $char) {
$buf = Buffer::fromInt($char, 1);
$bin .= $buf->getBinary();
}
$buffer = new Buffer($bin);
return $buffer->getBinary();
} | [
"public",
"function",
"ua2bin",
"(",
"array",
"$",
"uint8",
")",
"{",
"$",
"bin",
"=",
"\"\"",
";",
"foreach",
"(",
"$",
"uint8",
"as",
"$",
"ix",
"=>",
"$",
"char",
")",
"{",
"$",
"buf",
"=",
"Buffer",
"::",
"fromInt",
"(",
"$",
"char",
",",
"... | Encode a UInt8 array to its bytes representation.
@param array $uint8 UInt8 array to convert to its bytes representation.
@return string Byte-level representation of the UInt8 array. | [
"Encode",
"a",
"UInt8",
"array",
"to",
"its",
"bytes",
"representation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encoder.php#L72-L82 |
evias/nem-php | src/Core/Encoder.php | Encoder.ua2words | public function ua2words(array $uint8)
{
$uint8 = $uint8;
$int32 = [];
// 4 bytes in a row ! => 4 times uint8 is an int32.
for ($i = 0, $bytes = count($uint8); $i < $bytes; $i += 4) {
$b1 = $uint8[$i];
$b2 = isset($uint8[$i+1]) ? $uint8[$i+1] : 0;
$b3 = isset($uint8[$i+2]) ? $uint8[$i+2] : 0;
$b4 = isset($uint8[$i+3]) ? $uint8[$i+3] : 0;
// (byte_1 * 16777216) + (byte_2 * 65536) + (byte_3 * 256) + byte_4
$i32 = $b1 * 0x1000000 + $b2 * 0x10000 + $b3 * 0x100 + $b4;
// negative amounts are represented in [0, 2147483647] range
// 0x100000000 is double of 2147483647 minus 2.
$signed = $i32 > 0x7fffffff ? $i32 - 0x100000000 : $i32;
array_push($int32, $signed);
}
return $int32;
} | php | public function ua2words(array $uint8)
{
$uint8 = $uint8;
$int32 = [];
// 4 bytes in a row ! => 4 times uint8 is an int32.
for ($i = 0, $bytes = count($uint8); $i < $bytes; $i += 4) {
$b1 = $uint8[$i];
$b2 = isset($uint8[$i+1]) ? $uint8[$i+1] : 0;
$b3 = isset($uint8[$i+2]) ? $uint8[$i+2] : 0;
$b4 = isset($uint8[$i+3]) ? $uint8[$i+3] : 0;
// (byte_1 * 16777216) + (byte_2 * 65536) + (byte_3 * 256) + byte_4
$i32 = $b1 * 0x1000000 + $b2 * 0x10000 + $b3 * 0x100 + $b4;
// negative amounts are represented in [0, 2147483647] range
// 0x100000000 is double of 2147483647 minus 2.
$signed = $i32 > 0x7fffffff ? $i32 - 0x100000000 : $i32;
array_push($int32, $signed);
}
return $int32;
} | [
"public",
"function",
"ua2words",
"(",
"array",
"$",
"uint8",
")",
"{",
"$",
"uint8",
"=",
"$",
"uint8",
";",
"$",
"int32",
"=",
"[",
"]",
";",
"// 4 bytes in a row ! => 4 times uint8 is an int32.",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"bytes",
"=",... | Convert a UInt8 array to a Int32 array (WordArray).
The returned array contains entries of type Int32.
@param array $uint8 UInt8 array to convert to Int32 array.
@return array Array of Int32 representations. | [
"Convert",
"a",
"UInt8",
"array",
"to",
"a",
"Int32",
"array",
"(",
"WordArray",
")",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encoder.php#L92-L115 |
evias/nem-php | src/Core/Encoder.php | Encoder.ua2hex | public function ua2hex(array $uint8)
{
$uint8 = $uint8 ?: $this->toUInt8();
$hex = "";
$enc = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for ($i = 0, $bytes = count($uint8); $i < $bytes; $i++) {
$code = $uint8[$i];
$hex .= $enc[static::unsignedRightShift($code, 4)];
$hex .= $enc[($code & 0x0f)];
}
return $hex;
} | php | public function ua2hex(array $uint8)
{
$uint8 = $uint8 ?: $this->toUInt8();
$hex = "";
$enc = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for ($i = 0, $bytes = count($uint8); $i < $bytes; $i++) {
$code = $uint8[$i];
$hex .= $enc[static::unsignedRightShift($code, 4)];
$hex .= $enc[($code & 0x0f)];
}
return $hex;
} | [
"public",
"function",
"ua2hex",
"(",
"array",
"$",
"uint8",
")",
"{",
"$",
"uint8",
"=",
"$",
"uint8",
"?",
":",
"$",
"this",
"->",
"toUInt8",
"(",
")",
";",
"$",
"hex",
"=",
"\"\"",
";",
"$",
"enc",
"=",
"[",
"'0'",
",",
"'1'",
",",
"'2'",
"... | Encode a UInt8 array (WordArray) to its hexadecimal representation.
@param array $uint8 UInt8 array to convert to Int32 array.
@return string Hexadecimal representation of the UInt8 array. | [
"Encode",
"a",
"UInt8",
"array",
"(",
"WordArray",
")",
"to",
"its",
"hexadecimal",
"representation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encoder.php#L123-L136 |
evias/nem-php | src/Models/Transaction/MultisigAggregateModification.php | MultisigAggregateModification.serialize | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->toDTO("transaction");
$network = $parameters ?: -104; // default testnet
// shortcuts
$serializer = $this->getSerializer();
$output = [];
$mapped = $this->modifications()->map(function($modification) {
return new MultisigModification($modification);
});
// modifications must be grouped by type to be sorted
// first by type, then lexicographically by address
$modificationsByType = [];
foreach ($mapped as $modification) {
// shortcuts
$pubKey = $modification->cosignatoryAccount->publicKey;
$type = $modification->modificationType;
$address = Address::fromPublicKey($pubKey, -104)->address;
if (! isset($modificationsByType[$type])) {
$modificationsByType[$type] = [];
}
// group by type
$modificationsByType[$type][$address] = $modification;
}
// sort by type, then sort by address
ksort($modificationsByType);
foreach ($modificationsByType as $modType => &$modsByAddresses) {
ksort($modsByAddresses);
}
// serialize specialized fields
$uint8_size = $serializer->serializeInt(count($nisData["modifications"]));
$uint8_mods = [];
foreach ($modificationsByType as $modType => $modifications) {
foreach ($modifications as $address => $modification) {
// use MultisigModification::serialize() specialization
$uint8_mod = $modification->serialize($parameters);
$uint8_mods = array_merge($uint8_mods, $uint8_mod);
}
}
// serialize relativeChange only for transaction.version > v2
$uint8_change = [];
$version = $nisData["version"];
// XXX should not use v2 constants but arithmetic test
if (in_array($version, [Transaction::VERSION_2,
Transaction::VERSION_2_TEST,
Transaction::VERSION_2_MIJIN])) {
$change = (int) $nisData["minCosignatories"]["relativeChange"];
if ($change < 0) {
// apply sentinel to negative numbers
$change = Serializer::NULL_SENTINEL & $change;
}
// size-security through Buffer class
$chBuf = Buffer::fromInt($change, 4, null, Buffer::PAD_LEFT);
$uint8_change = array_reverse($chBuf->toUInt8());
$uint8_lenCh = $serializer->serializeInt(4);
// prefix serialized size
$uint8_change = array_merge($uint8_lenCh, $uint8_change);
}
// else {
// v1 does not have multisig *modifications* (no relativeChange possible)
// }
// concatenate the UInt8 representation
$output = array_merge(
$uint8_size,
$uint8_mods,
$uint8_change);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | php | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->toDTO("transaction");
$network = $parameters ?: -104; // default testnet
// shortcuts
$serializer = $this->getSerializer();
$output = [];
$mapped = $this->modifications()->map(function($modification) {
return new MultisigModification($modification);
});
// modifications must be grouped by type to be sorted
// first by type, then lexicographically by address
$modificationsByType = [];
foreach ($mapped as $modification) {
// shortcuts
$pubKey = $modification->cosignatoryAccount->publicKey;
$type = $modification->modificationType;
$address = Address::fromPublicKey($pubKey, -104)->address;
if (! isset($modificationsByType[$type])) {
$modificationsByType[$type] = [];
}
// group by type
$modificationsByType[$type][$address] = $modification;
}
// sort by type, then sort by address
ksort($modificationsByType);
foreach ($modificationsByType as $modType => &$modsByAddresses) {
ksort($modsByAddresses);
}
// serialize specialized fields
$uint8_size = $serializer->serializeInt(count($nisData["modifications"]));
$uint8_mods = [];
foreach ($modificationsByType as $modType => $modifications) {
foreach ($modifications as $address => $modification) {
// use MultisigModification::serialize() specialization
$uint8_mod = $modification->serialize($parameters);
$uint8_mods = array_merge($uint8_mods, $uint8_mod);
}
}
// serialize relativeChange only for transaction.version > v2
$uint8_change = [];
$version = $nisData["version"];
// XXX should not use v2 constants but arithmetic test
if (in_array($version, [Transaction::VERSION_2,
Transaction::VERSION_2_TEST,
Transaction::VERSION_2_MIJIN])) {
$change = (int) $nisData["minCosignatories"]["relativeChange"];
if ($change < 0) {
// apply sentinel to negative numbers
$change = Serializer::NULL_SENTINEL & $change;
}
// size-security through Buffer class
$chBuf = Buffer::fromInt($change, 4, null, Buffer::PAD_LEFT);
$uint8_change = array_reverse($chBuf->toUInt8());
$uint8_lenCh = $serializer->serializeInt(4);
// prefix serialized size
$uint8_change = array_merge($uint8_lenCh, $uint8_change);
}
// else {
// v1 does not have multisig *modifications* (no relativeChange possible)
// }
// concatenate the UInt8 representation
$output = array_merge(
$uint8_size,
$uint8_mods,
$uint8_change);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
"\"transaction\"",
")",
";",
"$",... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *MultisigAggregateModification* serialization.
This will sort multisig modifications contained in the transaction.
When the transaction is serialized, the multisig modifications
are sorted by type and lexicographically by address.
Following is the resulting sort order for the below defined
transaction:
A = bc5761bb3a903d136910fca661c6b1af4d819df4c270f5241143408384322c58
B = 7cbc80a218acba575305e7ff951a336ec66bd122519b12dc26eace26a1354962
C = d4301b99c4a79ef071f9a161d65cd95cba0ca3003cb0138d8b62ff770487a8c4
A = bc57.. = TD5MITTMM2XDQVJSHEKSPJTCGLFAYFGYDFHPGBEC
B = 7cbc.. = TBYCP5ZYZ4BLCD2TOHXXM6I6ZFK2JQF57SE5QVTK
C = d430.. = TBJ3RBTPA5LSPBPINJY622WTENAF7KGZI53D6DGO
Resulting Order: C, B, A
@see \NEM\Contracts\Serializable
@param null|string $parameters This parameter can be used to pass a Network ID in case
you wish to use the right network addresses to sort
your modifications. Sadly modifications are ordered by
address, not by public key. But usually, when you compare
multiple addresses (pub keys), only the first few characters
are actually needed for sorting. This is why using the default
testnet network is OK too (only the checksum changes due to
network prefix change).
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"MultisigAggregateModification",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MultisigAggregateModification.php#L97-L182 |
evias/nem-php | src/Models/Transaction/MultisigAggregateModification.php | MultisigAggregateModification.minCosignatories | public function minCosignatories($minCosignatories = null)
{
$minCosignatories = $minCosignatories ?: $this->getAttribute("minCosignatories") ?: $this->relativeChange;
// "minCosignatories" can be used as direct attribute setter
if (is_integer($minCosignatories)) {
$relativeChange = $minCosignatories;
}
// "minCosignatories" is also a sub-dto
elseif (is_array($minCosignatories) && isset($minCosignatories["relativeChange"])) {
$relativeChange = $minCosignatories["relativeChange"];
}
else {
$relativeChange = $this->relativeChange ?: 0;
}
$this->setAttribute("relativeChange", $relativeChange);
return new Model(["relativeChange" => $this->relativeChange]);
} | php | public function minCosignatories($minCosignatories = null)
{
$minCosignatories = $minCosignatories ?: $this->getAttribute("minCosignatories") ?: $this->relativeChange;
// "minCosignatories" can be used as direct attribute setter
if (is_integer($minCosignatories)) {
$relativeChange = $minCosignatories;
}
// "minCosignatories" is also a sub-dto
elseif (is_array($minCosignatories) && isset($minCosignatories["relativeChange"])) {
$relativeChange = $minCosignatories["relativeChange"];
}
else {
$relativeChange = $this->relativeChange ?: 0;
}
$this->setAttribute("relativeChange", $relativeChange);
return new Model(["relativeChange" => $this->relativeChange]);
} | [
"public",
"function",
"minCosignatories",
"(",
"$",
"minCosignatories",
"=",
"null",
")",
"{",
"$",
"minCosignatories",
"=",
"$",
"minCosignatories",
"?",
":",
"$",
"this",
"->",
"getAttribute",
"(",
"\"minCosignatories\"",
")",
"?",
":",
"$",
"this",
"->",
... | Mutator for the modifications collection.
@return \NEM\Models\ModelCollection | [
"Mutator",
"for",
"the",
"modifications",
"collection",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MultisigAggregateModification.php#L227-L245 |
evias/nem-php | src/Models/Transaction/MosaicTransfer.php | MosaicTransfer.serialize | public function serialize($parameters = null)
{
// @see NEM\Models\Transaction\Transfer::serialize()
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_mosaics = $this->mosaics()->serialize();
return ($this->serialized = array_merge($baseTx, $uint8_mosaics));
} | php | public function serialize($parameters = null)
{
// @see NEM\Models\Transaction\Transfer::serialize()
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_mosaics = $this->mosaics()->serialize();
return ($this->serialized = array_merge($baseTx, $uint8_mosaics));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"// @see NEM\\Models\\Transaction\\Transfer::serialize()",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->"... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *Transfer* serialization.
@see \NEM\Contracts\Serializable
@see \NEM\Models\Transaction\Transfer::serialize()
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"Transfer",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicTransfer.php#L63-L76 |
evias/nem-php | src/Models/Transaction/MosaicTransfer.php | MosaicTransfer.extend | public function extend()
{
$version = $this->getAttribute("version");
$twoByOld = [
Transaction::VERSION_1 => Transaction::VERSION_2,
Transaction::VERSION_1_TEST => Transaction::VERSION_2_TEST,
Transaction::VERSION_1_MIJIN => Transaction::VERSION_2_MIJIN,
];
// MosaicTransfer always use *VERSION 2 TRANSACTIONS*.
// this small block will make sure to stay on the correct
// network in case a version was set before.
if (in_array($version, array_keys($twoByOld))) {
// switch to v2
$version = $twoByOld[$version];
}
elseif (!$version || !in_array($version, array_values($twoByOld))) {
// invalid version provided, set default
$version = Transaction::VERSION_2_TEST;
}
return [
"amount" => $this->amount()->toMicro(),
"recipient" => $this->recipient()->address()->toClean(),
"message" => $this->message()->toDTO(),
"mosaics" => $this->mosaics()->toDTO(),
// transaction type specialization
"type" => TransactionType::TRANSFER,
"version" => $version,
];
} | php | public function extend()
{
$version = $this->getAttribute("version");
$twoByOld = [
Transaction::VERSION_1 => Transaction::VERSION_2,
Transaction::VERSION_1_TEST => Transaction::VERSION_2_TEST,
Transaction::VERSION_1_MIJIN => Transaction::VERSION_2_MIJIN,
];
// MosaicTransfer always use *VERSION 2 TRANSACTIONS*.
// this small block will make sure to stay on the correct
// network in case a version was set before.
if (in_array($version, array_keys($twoByOld))) {
// switch to v2
$version = $twoByOld[$version];
}
elseif (!$version || !in_array($version, array_values($twoByOld))) {
// invalid version provided, set default
$version = Transaction::VERSION_2_TEST;
}
return [
"amount" => $this->amount()->toMicro(),
"recipient" => $this->recipient()->address()->toClean(),
"message" => $this->message()->toDTO(),
"mosaics" => $this->mosaics()->toDTO(),
// transaction type specialization
"type" => TransactionType::TRANSFER,
"version" => $version,
];
} | [
"public",
"function",
"extend",
"(",
")",
"{",
"$",
"version",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"\"version\"",
")",
";",
"$",
"twoByOld",
"=",
"[",
"Transaction",
"::",
"VERSION_1",
"=>",
"Transaction",
"::",
"VERSION_2",
",",
"Transaction",
":... | The MosaicTransfer transaction type adds the `mosaics` offset
to the Transaction DTO and also adds all fields defined in the
Transfer::extend() overload.
@return array | [
"The",
"MosaicTransfer",
"transaction",
"type",
"adds",
"the",
"mosaics",
"offset",
"to",
"the",
"Transaction",
"DTO",
"and",
"also",
"adds",
"all",
"fields",
"defined",
"in",
"the",
"Transfer",
"::",
"extend",
"()",
"overload",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicTransfer.php#L85-L116 |
evias/nem-php | src/Models/Transaction/MosaicTransfer.php | MosaicTransfer.extendFee | public function extendFee()
{
// identify network
$address = $this->recipient()->address();
$networkId = 104;
if (!empty($address->toClean()))
$networkId = Network::fromAddress($address);
// load definitions for attached mosaics.
$definitions = MosaicDefinitions::create($this->mosaics, $networkId);
// calculate fees for mosaics
$mosaicsFee = Fee::calculateForMosaics(
$definitions,
$this->mosaics(),
$this->amount()->toMicro());
return $mosaicsFee;
} | php | public function extendFee()
{
// identify network
$address = $this->recipient()->address();
$networkId = 104;
if (!empty($address->toClean()))
$networkId = Network::fromAddress($address);
// load definitions for attached mosaics.
$definitions = MosaicDefinitions::create($this->mosaics, $networkId);
// calculate fees for mosaics
$mosaicsFee = Fee::calculateForMosaics(
$definitions,
$this->mosaics(),
$this->amount()->toMicro());
return $mosaicsFee;
} | [
"public",
"function",
"extendFee",
"(",
")",
"{",
"// identify network",
"$",
"address",
"=",
"$",
"this",
"->",
"recipient",
"(",
")",
"->",
"address",
"(",
")",
";",
"$",
"networkId",
"=",
"104",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"address",
"... | The extendFee() method must be overloaded by any Transaction Type
which needs to extend the base FEE to a custom FEE.
@return array | [
"The",
"extendFee",
"()",
"method",
"must",
"be",
"overloaded",
"by",
"any",
"Transaction",
"Type",
"which",
"needs",
"to",
"extend",
"the",
"base",
"FEE",
"to",
"a",
"custom",
"FEE",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicTransfer.php#L124-L143 |
evias/nem-php | src/Models/Transaction/MosaicTransfer.php | MosaicTransfer.attachMosaic | public function attachMosaic($mosaic, $quantity = null)
{
$attachment = $this->prepareAttachment($mosaic);
$actualAmt = $attachment->quantity ?: $quantity ?: 0;
$attachment->setAttribute("quantity", $actualAmt);
// push to internal storage
$attachments = $this->getAttribute("mosaics") ?: [];
array_push($attachments, $attachment);
$this->setAttribute("mosaics", $attachments);
return $this;
} | php | public function attachMosaic($mosaic, $quantity = null)
{
$attachment = $this->prepareAttachment($mosaic);
$actualAmt = $attachment->quantity ?: $quantity ?: 0;
$attachment->setAttribute("quantity", $actualAmt);
// push to internal storage
$attachments = $this->getAttribute("mosaics") ?: [];
array_push($attachments, $attachment);
$this->setAttribute("mosaics", $attachments);
return $this;
} | [
"public",
"function",
"attachMosaic",
"(",
"$",
"mosaic",
",",
"$",
"quantity",
"=",
"null",
")",
"{",
"$",
"attachment",
"=",
"$",
"this",
"->",
"prepareAttachment",
"(",
"$",
"mosaic",
")",
";",
"$",
"actualAmt",
"=",
"$",
"attachment",
"->",
"quantity... | Helper to easily attach mosaics to the attachments.
@param string|\NEM\Models\Mosaic|\NEM\Models\MosaicAttachment $mosaic
@param null|integer $quantity
@return \NEM\Models\Transaction\MosaicTransfer | [
"Helper",
"to",
"easily",
"attach",
"mosaics",
"to",
"the",
"attachments",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicTransfer.php#L166-L178 |
evias/nem-php | src/Models/Transaction/MosaicTransfer.php | MosaicTransfer.prepareAttachment | protected function prepareAttachment($mosaic)
{
if ($mosaic instanceof MosaicAttachment) {
return $mosaic;
}
elseif ($mosaic instanceof MosaicAttachments) {
return $mosaic->shift();
}
elseif ($mosaic instanceof Mosaic) {
return new MosaicAttachment(["mosaicId" => $mosaic->toDTO()]);
}
elseif ($mosaic instanceof MosaicDefinition) {
return new MosaicAttachment(["mosaicId" => $mosaic->id()->toDTO()]);
}
elseif (is_string($mosaic)) {
return $this->prepareAttachment(Mosaic::create($mosaic));
}
throw new InvalidArgumentException("Unrecognized mosaic parameter type passed to \\NEM\\Models\\Transaction\\MosaicTransfer::attachMosaic().");
} | php | protected function prepareAttachment($mosaic)
{
if ($mosaic instanceof MosaicAttachment) {
return $mosaic;
}
elseif ($mosaic instanceof MosaicAttachments) {
return $mosaic->shift();
}
elseif ($mosaic instanceof Mosaic) {
return new MosaicAttachment(["mosaicId" => $mosaic->toDTO()]);
}
elseif ($mosaic instanceof MosaicDefinition) {
return new MosaicAttachment(["mosaicId" => $mosaic->id()->toDTO()]);
}
elseif (is_string($mosaic)) {
return $this->prepareAttachment(Mosaic::create($mosaic));
}
throw new InvalidArgumentException("Unrecognized mosaic parameter type passed to \\NEM\\Models\\Transaction\\MosaicTransfer::attachMosaic().");
} | [
"protected",
"function",
"prepareAttachment",
"(",
"$",
"mosaic",
")",
"{",
"if",
"(",
"$",
"mosaic",
"instanceof",
"MosaicAttachment",
")",
"{",
"return",
"$",
"mosaic",
";",
"}",
"elseif",
"(",
"$",
"mosaic",
"instanceof",
"MosaicAttachments",
")",
"{",
"r... | Helper to prepare a MosaicAttachment object out of any one of string, | [
"Helper",
"to",
"prepare",
"a",
"MosaicAttachment",
"object",
"out",
"of",
"any",
"one",
"of",
"string"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicTransfer.php#L183-L202 |
evias/nem-php | src/Core/Signature.php | Signature.create | static public function create(KeyPair $kp, $data, $algorithm = 'keccak-512')
{
$sig = new static($privateKey, $publicKey, $algorithm);
return $sig;
} | php | static public function create(KeyPair $kp, $data, $algorithm = 'keccak-512')
{
$sig = new static($privateKey, $publicKey, $algorithm);
return $sig;
} | [
"static",
"public",
"function",
"create",
"(",
"KeyPair",
"$",
"kp",
",",
"$",
"data",
",",
"$",
"algorithm",
"=",
"'keccak-512'",
")",
"{",
"$",
"sig",
"=",
"new",
"static",
"(",
"$",
"privateKey",
",",
"$",
"publicKey",
",",
"$",
"algorithm",
")",
... | This method creates a Signature of said `data` with the
given `keyPair` KeyPair object.
@param \NEM\Core\KeyPair $keyPair The KeyPair object with which you want to sign `data`.
@param string|\NEM\Core\Buffer $data The data that needs to be signed.
@param null|string $algorithm The hash algorithm that you wish to use for signature creation.
@return \NEM\Core\Signature
@throws \NEM\Errors\NISInvalidSignatureContent On invalid `data` argument. Should be a \NEM\Core\Buffer or a string. | [
"This",
"method",
"creates",
"a",
"Signature",
"of",
"said",
"data",
"with",
"the",
"given",
"keyPair",
"KeyPair",
"object",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Signature.php#L74-L78 |
evias/nem-php | src/Core/Signature.php | Signature.prepareData | protected function prepareData($data)
{
if ($data instanceof Buffer) {
$this->data = $data;
}
elseif (is_string($data)) {
$this->data = new Buffer($data); // auto-sized
}
elseif (is_array($data)) {
// Uint8 provided (serialized data)
$this->data = Buffer::fromUInt8($data);
}
else {
throw new NISInvalidSignatureContent("Invalid content provided for \\NEM\\Core\\Signature object.");
}
return $this;
} | php | protected function prepareData($data)
{
if ($data instanceof Buffer) {
$this->data = $data;
}
elseif (is_string($data)) {
$this->data = new Buffer($data); // auto-sized
}
elseif (is_array($data)) {
// Uint8 provided (serialized data)
$this->data = Buffer::fromUInt8($data);
}
else {
throw new NISInvalidSignatureContent("Invalid content provided for \\NEM\\Core\\Signature object.");
}
return $this;
} | [
"protected",
"function",
"prepareData",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
"instanceof",
"Buffer",
")",
"{",
"$",
"this",
"->",
"data",
"=",
"$",
"data",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"data",
")",
")",
"{",
"$",
... | This method will prepare the given data and populate the
`data` property with a prepared and correctly sized Buffer.
@param string|\NEM\Core\Buffer $data The data that needs to be signed.
@return \NEM\Core\Signature
@throws \NEM\Errors\NISInvalidSignatureContent On invalid `data` argument. Should be a \NEM\Core\Buffer or a string. | [
"This",
"method",
"will",
"prepare",
"the",
"given",
"data",
"and",
"populate",
"the",
"data",
"property",
"with",
"a",
"prepared",
"and",
"correctly",
"sized",
"Buffer",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Signature.php#L127-L144 |
evias/nem-php | src/Infrastructure/Account.php | Account.generateAccount | public function generateAccount()
{
$params = [];
$apiUrl = $this->getPath('generate', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createAccountModel($object); //XXX brr => error/content validation first
} | php | public function generateAccount()
{
$params = [];
$apiUrl = $this->getPath('generate', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createAccountModel($object); //XXX brr => error/content validation first
} | [
"public",
"function",
"generateAccount",
"(",
")",
"{",
"$",
"params",
"=",
"[",
"]",
";",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'generate'",
",",
"$",
"params",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"api",
"->",
"get... | Let NIS generate an account KeyPair.
WARNING: This method can only be used on a locally running
NIS. It is preferred to use the \NEM\Core\KeyPair
class to create accounts on your machine rather than
let NIS create an account for you.
@internal This method only works with a locally running NIS.
@return object Object with keys `address`, `publicKey` and `privateKey`. | [
"Let",
"NIS",
"generate",
"an",
"account",
"KeyPair",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L53-L62 |
evias/nem-php | src/Infrastructure/Account.php | Account.getFromAddress | public function getFromAddress($address)
{
$apiUrl = $this->getPath('get', ["address" => $address]);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createAccountModel($object);
} | php | public function getFromAddress($address)
{
$apiUrl = $this->getPath('get', ["address" => $address]);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createAccountModel($object);
} | [
"public",
"function",
"getFromAddress",
"(",
"$",
"address",
")",
"{",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'get'",
",",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"api",
"->",... | Gets an [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair) for an account
by its Base32 address representation (T-, N-, M- prefixed addresses).
@param string $address Base32 representation of the account address (T-, N-, M- prefixed addresses).
@return object Instance with keys from [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair) objects. | [
"Gets",
"an",
"[",
"AccountMetaDataPair",
"]",
"(",
"https",
":",
"//",
"bob",
".",
"nem",
".",
"ninja",
"/",
"docs",
"/",
"#accountMetaDataPair",
")",
"for",
"an",
"account",
"by",
"its",
"Base32",
"address",
"representation",
"(",
"T",
"-",
"N",
"-",
... | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L71-L79 |
evias/nem-php | src/Infrastructure/Account.php | Account.getFromPublicKey | public function getFromPublicKey($publicKey)
{
$apiUrl = $this->getPath('get/from-public-key', ["publicKey" => $publicKey]);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createAccountModel($object);
} | php | public function getFromPublicKey($publicKey)
{
$apiUrl = $this->getPath('get/from-public-key', ["publicKey" => $publicKey]);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createAccountModel($object);
} | [
"public",
"function",
"getFromPublicKey",
"(",
"$",
"publicKey",
")",
"{",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'get/from-public-key'",
",",
"[",
"\"publicKey\"",
"=>",
"$",
"publicKey",
"]",
")",
";",
"$",
"response",
"=",
"$",
"this",
... | Gets an [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair) for an account
by its public key hexadecimal representation.
@param string $publicKey Hexadecimal representation of the Public Key
@return object Instance with keys from [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair) objects. | [
"Gets",
"an",
"[",
"AccountMetaDataPair",
"]",
"(",
"https",
":",
"//",
"bob",
".",
"nem",
".",
"ninja",
"/",
"docs",
"/",
"#accountMetaDataPair",
")",
"for",
"an",
"account",
"by",
"its",
"public",
"key",
"hexadecimal",
"representation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L88-L96 |
evias/nem-php | src/Infrastructure/Account.php | Account.status | public function status($address)
{
$apiUrl = $this->getPath('status', ["address" => $address]);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createBaseModel($object);
} | php | public function status($address)
{
$apiUrl = $this->getPath('status', ["address" => $address]);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createBaseModel($object);
} | [
"public",
"function",
"status",
"(",
"$",
"address",
")",
"{",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'status'",
",",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"api",
"->",
"g... | Gets the [AccountMetaData](https://bob.nem.ninja/docs/#accountMetaData) from an account.
@param string $address Base32 representation of the account address (T-, N-, M- prefixed addresses).
@return object Instance with keys from [AccountMetaData](https://bob.nem.ninja/docs/#accountMetaData) objects. | [
"Gets",
"the",
"[",
"AccountMetaData",
"]",
"(",
"https",
":",
"//",
"bob",
".",
"nem",
".",
"ninja",
"/",
"docs",
"/",
"#accountMetaData",
")",
"from",
"an",
"account",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L138-L146 |
evias/nem-php | src/Infrastructure/Account.php | Account.incomingTransactions | public function incomingTransactions($address, $hash = null, $id = null)
{
$params = ["address" => $address];
if ($hash !== null)
$params["hash"] = $hash;
if ($id !== null)
$params["id"] = $id;
$apiUrl = $this->getPath('transfers/incoming', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createTransactionCollection($object['data']); //XXX brr => error/content validation first
} | php | public function incomingTransactions($address, $hash = null, $id = null)
{
$params = ["address" => $address];
if ($hash !== null)
$params["hash"] = $hash;
if ($id !== null)
$params["id"] = $id;
$apiUrl = $this->getPath('transfers/incoming', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createTransactionCollection($object['data']); //XXX brr => error/content validation first
} | [
"public",
"function",
"incomingTransactions",
"(",
"$",
"address",
",",
"$",
"hash",
"=",
"null",
",",
"$",
"id",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
";",
"if",
"(",
"$",
"hash",
"!==",
"null",
... | A transaction is said to be incoming with respect to an account if the account is the recipient of the
transaction. In the same way outgoing transaction are the transactions where the account is the sender of the
transaction. Unconfirmed transactions are those transactions that have not yet been included in a block.
Unconfirmed transactions are not guaranteed to be included in any block.
@param string $address Base32 representation of the account address (T-, N-, M- prefixed addresses).
@param string $hash (Optional) The 256 bit sha3 hash of the transaction up to which transactions are returned.
@param integer $id (Optional) The transaction id up to which transactions are returned. This parameter will prevail over the hash parameter.
@return array Array of object with keys from [TransactionMetaDataPair](https://bob.nem.ninja/docs/#transactionMetaDataPair) objects. | [
"A",
"transaction",
"is",
"said",
"to",
"be",
"incoming",
"with",
"respect",
"to",
"an",
"account",
"if",
"the",
"account",
"is",
"the",
"recipient",
"of",
"the",
"transaction",
".",
"In",
"the",
"same",
"way",
"outgoing",
"transaction",
"are",
"the",
"tra... | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L159-L175 |
evias/nem-php | src/Infrastructure/Account.php | Account.unconfirmedTransactions | public function unconfirmedTransactions($address, $hash = null)
{
$params = ["address" => $address];
if ($hash !== null)
$params["hash"] = $hash;
$apiUrl = $this->getPath('unconfirmedTransactions', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$data = json_decode($response, true);
return $this->createTransactionCollection($object['data']); //XXX brr => error/content validation first
} | php | public function unconfirmedTransactions($address, $hash = null)
{
$params = ["address" => $address];
if ($hash !== null)
$params["hash"] = $hash;
$apiUrl = $this->getPath('unconfirmedTransactions', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$data = json_decode($response, true);
return $this->createTransactionCollection($object['data']); //XXX brr => error/content validation first
} | [
"public",
"function",
"unconfirmedTransactions",
"(",
"$",
"address",
",",
"$",
"hash",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
";",
"if",
"(",
"$",
"hash",
"!==",
"null",
")",
"$",
"params",
"[",
"\"... | Gets the array of transactions for which an account is the sender or receiver and which have not yet been
included in a block
@param string $address Base32 representation of the account address (T-, N-, M- prefixed addresses).
@param string $hash (Optional) The 256 bit sha3 hash of the transaction up to which transactions are returned.
@return array Array of object with keys from [TransactionMetaDataPair](https://bob.nem.ninja/docs/#transactionMetaDataPair) objects. | [
"Gets",
"the",
"array",
"of",
"transactions",
"for",
"which",
"an",
"account",
"is",
"the",
"sender",
"or",
"receiver",
"and",
"which",
"have",
"not",
"yet",
"been",
"included",
"in",
"a",
"block"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L241-L254 |
evias/nem-php | src/Infrastructure/Account.php | Account.getHarvestInfo | public function getHarvestInfo($address, $hash = null)
{
$params = ["address" => $address];
if ($hash !== null)
$params["hash"] = $hash;
$apiUrl = $this->getPath('harvests', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$data = json_decode($response, true);
return $this->createBaseModel($object); //XXX brr => error/content validation first
} | php | public function getHarvestInfo($address, $hash = null)
{
$params = ["address" => $address];
if ($hash !== null)
$params["hash"] = $hash;
$apiUrl = $this->getPath('harvests', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$data = json_decode($response, true);
return $this->createBaseModel($object); //XXX brr => error/content validation first
} | [
"public",
"function",
"getHarvestInfo",
"(",
"$",
"address",
",",
"$",
"hash",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
";",
"if",
"(",
"$",
"hash",
"!==",
"null",
")",
"$",
"params",
"[",
"\"hash\"",
... | Gets an array of harvest info objects for an account.
@param string $address The address of the account.
@param string %hash The 256 bit sha3 hash of the block up to which harvested blocks are returned.
@return object Instance with keys from [HarvestInfo](https://bob.nem.ninja/docs/#harvestInfo) objects. | [
"Gets",
"an",
"array",
"of",
"harvest",
"info",
"objects",
"for",
"an",
"account",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L263-L276 |
evias/nem-php | src/Infrastructure/Account.php | Account.getAccountImportances | public function getAccountImportances($address)
{
$params = ["address" => $address];
$apiUrl = $this->getPath('importances', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createBaseCollection($object['data']); //XXX brr => error/content validation first
} | php | public function getAccountImportances($address)
{
$params = ["address" => $address];
$apiUrl = $this->getPath('importances', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createBaseCollection($object['data']); //XXX brr => error/content validation first
} | [
"public",
"function",
"getAccountImportances",
"(",
"$",
"address",
")",
"{",
"$",
"params",
"=",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
";",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'importances'",
",",
"$",
"params",
")",
";",
... | Gets an array of account importance view model objects.
@param string $address The address of the account.
@return array Array of object with keys from [AccountImportanceViewModl](https://bob.nem.ninja/docs/#accountImportanceViewModel) objects. | [
"Gets",
"an",
"array",
"of",
"account",
"importance",
"view",
"model",
"objects",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L284-L293 |
evias/nem-php | src/Infrastructure/Account.php | Account.getOwnedNamespaces | public function getOwnedNamespaces($address, $parent = null, $id = null, $pageSize = null)
{
$params = ["address" => $address];
if ($hash !== null)
$params["hash"] = $hash;
if ($id !== null)
$params["id"] = $id;
if ($pageSize !== null)
$params["pageSize"] = $pageSize;
$apiUrl = $this->getPath('namespace/page', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createNamespaceCollection($object['data']); //XXX brr => error/content validation first
} | php | public function getOwnedNamespaces($address, $parent = null, $id = null, $pageSize = null)
{
$params = ["address" => $address];
if ($hash !== null)
$params["hash"] = $hash;
if ($id !== null)
$params["id"] = $id;
if ($pageSize !== null)
$params["pageSize"] = $pageSize;
$apiUrl = $this->getPath('namespace/page', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createNamespaceCollection($object['data']); //XXX brr => error/content validation first
} | [
"public",
"function",
"getOwnedNamespaces",
"(",
"$",
"address",
",",
"$",
"parent",
"=",
"null",
",",
"$",
"id",
"=",
"null",
",",
"$",
"pageSize",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
";",
"if",
... | Gets an array of namespace objects for a given account address.
The parent parameter is optional. If supplied, only sub-namespaces of the parent namespace are returned.
@param string $address The address of the account.
@param null|string $parent The (optional) parent namespace id.
@param null|integer $id The (optional) namespace database id up to which namespaces are returned.
@param null|integer $pageSize The (optional) number of namespaces to be returned.
@return array Array of object with keys from [NamespaceMetaDataPair](https://bob.nem.ninja/docs/#namespaceMetaDataPair) objects. | [
"Gets",
"an",
"array",
"of",
"namespace",
"objects",
"for",
"a",
"given",
"account",
"address",
".",
"The",
"parent",
"parameter",
"is",
"optional",
".",
"If",
"supplied",
"only",
"sub",
"-",
"namespaces",
"of",
"the",
"parent",
"namespace",
"are",
"returned... | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L305-L324 |
evias/nem-php | src/Infrastructure/Account.php | Account.getCreatedMosaics | public function getCreatedMosaics($address, $parent = null, $id = null)
{
$params = ["address" => $address];
if ($parent !== null)
$params["parent"] = $parent;
if ($id !== null)
$params["id"] = $id;
$apiUrl = $this->getPath('mosaic/definition/page', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createMosaicCollection($object['data']); //XXX brr => error/content validation first
} | php | public function getCreatedMosaics($address, $parent = null, $id = null)
{
$params = ["address" => $address];
if ($parent !== null)
$params["parent"] = $parent;
if ($id !== null)
$params["id"] = $id;
$apiUrl = $this->getPath('mosaic/definition/page', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createMosaicCollection($object['data']); //XXX brr => error/content validation first
} | [
"public",
"function",
"getCreatedMosaics",
"(",
"$",
"address",
",",
"$",
"parent",
"=",
"null",
",",
"$",
"id",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
";",
"if",
"(",
"$",
"parent",
"!==",
"null",
... | Gets an array of mosaic definition objects for a given account address. The parent parameter is optional.
If supplied, only mosaic definitions for the given parent namespace are returned.
The id parameter is optional and allows retrieving mosaic definitions in batches of 25 mosaic definitions.
@param string $address The address of the account.
@param null|string $parent The (optional) parent namespace id.
@param null|integer $id The (optional) mosaic definition database id up to which mosaic definitions are returned.
@return array Array of object with keys from [MosaicDefinitionMetaDataPair](https://bob.nem.ninja/docs/#mosaicDefinitionMetaDataPair) objects. | [
"Gets",
"an",
"array",
"of",
"mosaic",
"definition",
"objects",
"for",
"a",
"given",
"account",
"address",
".",
"The",
"parent",
"parameter",
"is",
"optional",
".",
"If",
"supplied",
"only",
"mosaic",
"definitions",
"for",
"the",
"given",
"parent",
"namespace"... | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L336-L352 |
evias/nem-php | src/Infrastructure/Account.php | Account.getOwnedMosaics | public function getOwnedMosaics($address)
{
$params = ["address" => $address];
$apiUrl = $this->getPath('mosaic/owned', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createMosaicCollection($object['data']); //XXX brr => error/content validation first
} | php | public function getOwnedMosaics($address)
{
$params = ["address" => $address];
$apiUrl = $this->getPath('mosaic/owned', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createMosaicCollection($object['data']); //XXX brr => error/content validation first
} | [
"public",
"function",
"getOwnedMosaics",
"(",
"$",
"address",
")",
"{",
"$",
"params",
"=",
"[",
"\"address\"",
"=>",
"$",
"address",
"]",
";",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'mosaic/owned'",
",",
"$",
"params",
")",
";",
"$",
... | Gets an array of mosaic objects for a given account address.
@param string $address The address of the account.
@return array Array of object with keys from [MosaicDefinitionMetaDataPair](https://bob.nem.ninja/docs/#mosaicDefinitionMetaDataPair) objects. | [
"Gets",
"an",
"array",
"of",
"mosaic",
"objects",
"for",
"a",
"given",
"account",
"address",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L360-L370 |
evias/nem-php | src/Infrastructure/Account.php | Account.getHistoricalAccountData | public function getHistoricalAccountData($address, $startHeight = null, $endHeight = null, $increment = null)
{
$params = ["address" => $address];
if ($startHeight !== null)
$params["startHeight"] = $startHeight;
if ($endHeight !== null)
$params["endHeight"] = $endHeight;
if ($increment !== null)
$params["increment"] = $increment;
$apiUrl = $this->getPath('historical/get', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response);
return $this->createBaseCollection($object['data']); //XXX brr => error/content validation first
} | php | public function getHistoricalAccountData($address, $startHeight = null, $endHeight = null, $increment = null)
{
$params = ["address" => $address];
if ($startHeight !== null)
$params["startHeight"] = $startHeight;
if ($endHeight !== null)
$params["endHeight"] = $endHeight;
if ($increment !== null)
$params["increment"] = $increment;
$apiUrl = $this->getPath('historical/get', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response);
return $this->createBaseCollection($object['data']); //XXX brr => error/content validation first
} | [
"public",
"function",
"getHistoricalAccountData",
"(",
"$",
"address",
",",
"$",
"startHeight",
"=",
"null",
",",
"$",
"endHeight",
"=",
"null",
",",
"$",
"increment",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"\"address\"",
"=>",
"$",
"address",
"... | Gets historical information for an account.
@param string $address The address of the account.
@param integer $startHeight The block height from which on the data should be supplied.
@param integer $endHeight The block height up to which the data should be supplied. The end height must be greater than or equal to the start height.
@param integer $increment The value by which the height is incremented between each data point. The value must be
greater than 0. NIS can supply up to 1000 data points with one request. Requesting more
than 1000 data points results in an error.
@return array Array of object with keys from [Mosaic](https://bob.nem.ninja/docs/#mosaics) objects. | [
"Gets",
"historical",
"information",
"for",
"an",
"account",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L383-L402 |
evias/nem-php | src/Infrastructure/Account.php | Account.getUnlockInfo | public function getUnlockInfo()
{
$params = [];
$apiUrl = $this->getPath('unlocked/info', []);
$response = $this->api->post($apiUrl, $params);
//XXX include Error checks
$object = json_decode($response);
return $this->createBaseModel($object); //XXX brr => error/content validation first
} | php | public function getUnlockInfo()
{
$params = [];
$apiUrl = $this->getPath('unlocked/info', []);
$response = $this->api->post($apiUrl, $params);
//XXX include Error checks
$object = json_decode($response);
return $this->createBaseModel($object); //XXX brr => error/content validation first
} | [
"public",
"function",
"getUnlockInfo",
"(",
")",
"{",
"$",
"params",
"=",
"[",
"]",
";",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'unlocked/info'",
",",
"[",
"]",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"api",
"->",
"post"... | Each node can allow users to harvest with their delegated key on that node.
The NIS configuration has entries for configuring the maximum number of allowed harvesters and optionally allow
harvesting only for certain account addresses. The unlock info gives information about the maximum number of
allowed harvesters and how many harvesters are already using the node.
@return object Object with num-unlocked and max-unlocked keys. | [
"Each",
"node",
"can",
"allow",
"users",
"to",
"harvest",
"with",
"their",
"delegated",
"key",
"on",
"that",
"node",
".",
"The",
"NIS",
"configuration",
"has",
"entries",
"for",
"configuring",
"the",
"maximum",
"number",
"of",
"allowed",
"harvesters",
"and",
... | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L412-L421 |
evias/nem-php | src/Infrastructure/Account.php | Account.startHarvesting | public function startHarvesting($privateKey)
{
$params = ["value" => $privateKey];
$apiUrl = $this->getPath('unlock', $params);
$response = $this->api->post($apiUrl, []);
//XXX include Error checks
$object = json_decode($response);
return $this->createBaseModel($object); //XXX brr => error/content validation first
} | php | public function startHarvesting($privateKey)
{
$params = ["value" => $privateKey];
$apiUrl = $this->getPath('unlock', $params);
$response = $this->api->post($apiUrl, []);
//XXX include Error checks
$object = json_decode($response);
return $this->createBaseModel($object); //XXX brr => error/content validation first
} | [
"public",
"function",
"startHarvesting",
"(",
"$",
"privateKey",
")",
"{",
"$",
"params",
"=",
"[",
"\"value\"",
"=>",
"$",
"privateKey",
"]",
";",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'unlock'",
",",
"$",
"params",
")",
";",
"$",
... | Unlocks an account (starts harvesting).
@param host - string
@param privateKey - string
@return Array<boolean> | [
"Unlocks",
"an",
"account",
"(",
"starts",
"harvesting",
")",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Account.php#L431-L441 |
evias/nem-php | src/ServiceProvider.php | ServiceProvider.setupConfig | protected function setupConfig()
{
$source = realpath(__DIR__.'/../config') . "/nem.php";
if (! $this->isLumen())
// console laravel, use config_path helper
$this->publishes([$source => config_path('nem.php')]);
else
// lumen configure app
$this->app->configure('nem.config');
$this->mergeConfigFrom($source, 'nem.config');
} | php | protected function setupConfig()
{
$source = realpath(__DIR__.'/../config') . "/nem.php";
if (! $this->isLumen())
// console laravel, use config_path helper
$this->publishes([$source => config_path('nem.php')]);
else
// lumen configure app
$this->app->configure('nem.config');
$this->mergeConfigFrom($source, 'nem.config');
} | [
"protected",
"function",
"setupConfig",
"(",
")",
"{",
"$",
"source",
"=",
"realpath",
"(",
"__DIR__",
".",
"'/../config'",
")",
".",
"\"/nem.php\"",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"isLumen",
"(",
")",
")",
"// console laravel, use config_path helper"... | Setup the NEM blockchain config.
@return void | [
"Setup",
"the",
"NEM",
"blockchain",
"config",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/ServiceProvider.php#L76-L87 |
evias/nem-php | src/ServiceProvider.php | ServiceProvider.registerPreConfiguredApiClients | protected function registerPreConfiguredApiClients()
{
$this->app->bindIf("nem", function()
{
$environment = env("APP_ENV", "testing");
$envConfig = $environment == "production" ? "primary" : "testing";
$config = $this->app["nem.config"];
$nisConf = $config["nis"][$envConfig];
$client = new API($nisConf);
return $client;
}, true); // shared=true
$this->app->bindIf("nem.ncc", function()
{
$environment = env("APP_ENV", "testing");
$envConfig = $environment == "production" ? "primary" : "testing";
$config = $this->app["nem.config"];
$nccConf = $config["ncc"][$envConfig];
$client = new API($nccConf);
return $client;
}, true); // shared=true
$this->app->bindIf("nem.sdk", function()
{
$environment = env("APP_ENV", "testing");
$envConfig = $environment == "production" ? "primary" : "testing";
$api = $this->app["nem"];
$sdk = new SDK([], $api); // use already initialized NIS API client
return $sdk;
}, true); // shared=true
} | php | protected function registerPreConfiguredApiClients()
{
$this->app->bindIf("nem", function()
{
$environment = env("APP_ENV", "testing");
$envConfig = $environment == "production" ? "primary" : "testing";
$config = $this->app["nem.config"];
$nisConf = $config["nis"][$envConfig];
$client = new API($nisConf);
return $client;
}, true); // shared=true
$this->app->bindIf("nem.ncc", function()
{
$environment = env("APP_ENV", "testing");
$envConfig = $environment == "production" ? "primary" : "testing";
$config = $this->app["nem.config"];
$nccConf = $config["ncc"][$envConfig];
$client = new API($nccConf);
return $client;
}, true); // shared=true
$this->app->bindIf("nem.sdk", function()
{
$environment = env("APP_ENV", "testing");
$envConfig = $environment == "production" ? "primary" : "testing";
$api = $this->app["nem"];
$sdk = new SDK([], $api); // use already initialized NIS API client
return $sdk;
}, true); // shared=true
} | [
"protected",
"function",
"registerPreConfiguredApiClients",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bindIf",
"(",
"\"nem\"",
",",
"function",
"(",
")",
"{",
"$",
"environment",
"=",
"env",
"(",
"\"APP_ENV\"",
",",
"\"testing\"",
")",
";",
"$",
"env... | Register all pre-configured NEM API clients.
This will register following IoC bindings:
- nem : using the primary NIS server configuration
- nem.testing : using the testing NIS server configuration
- nem.ncc : using the primary NCC client configuration
- nem.ncc.testing : using the testing NCC client configuration
- nem.sdk : The SDK interface
All registered bindings will return an instance of
NEM\API.
@see \NEM\API
@return void | [
"Register",
"all",
"pre",
"-",
"configured",
"NEM",
"API",
"clients",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/ServiceProvider.php#L137-L173 |
evias/nem-php | src/Infrastructure/Transaction.php | Transaction.signTransaction | public function signTransaction(TxModel $transaction, KeyPair $kp = null)
{
// always set optional `signer` in case we provide a KeyPair
if (null !== $kp) {
$transaction->setAttribute("signer", $kp->getPublicKey("hex"));
}
// now we can serialize and sign
$serialized = $transaction->serialize();
$serialHex = Buffer::fromUInt8($serialized)->getHex();
$serialBin = hex2bin($serialHex);
return null !== $kp ? $kp->sign($serialBin) : null;
} | php | public function signTransaction(TxModel $transaction, KeyPair $kp = null)
{
// always set optional `signer` in case we provide a KeyPair
if (null !== $kp) {
$transaction->setAttribute("signer", $kp->getPublicKey("hex"));
}
// now we can serialize and sign
$serialized = $transaction->serialize();
$serialHex = Buffer::fromUInt8($serialized)->getHex();
$serialBin = hex2bin($serialHex);
return null !== $kp ? $kp->sign($serialBin) : null;
} | [
"public",
"function",
"signTransaction",
"(",
"TxModel",
"$",
"transaction",
",",
"KeyPair",
"$",
"kp",
"=",
"null",
")",
"{",
"// always set optional `signer` in case we provide a KeyPair",
"if",
"(",
"null",
"!==",
"$",
"kp",
")",
"{",
"$",
"transaction",
"->",
... | Helper method to sign a transaction with a given keypair `kp`.
If no keypair is provided, this method will return `null`.
@internal This method is used internally to determined whether
instanciated keypairs are detected and to make sure that
Client Signatures are always created when possible.
@param \NEM\Models\Transaction $transaction
@param null|\NEM\Core\KeyPair $kp
@return null|\NEM\Core\Buffer | [
"Helper",
"method",
"to",
"sign",
"a",
"transaction",
"with",
"a",
"given",
"keypair",
"kp",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Transaction.php#L82-L94 |
evias/nem-php | src/Infrastructure/Transaction.php | Transaction.announce | public function announce(TxModel $transaction, KeyPair $kp = null)
{
// always set optional `signer` in case we provide a KeyPair
if (null !== $kp) {
$transaction->setAttribute("signer", $kp->getPublicKey("hex"));
}
// now we can serialize and sign
$serialized = $transaction->serialize();
$signature = $this->signTransaction($transaction, $kp, $serialized);
$broadcast = [];
if ($signature) {
// valid KeyPair provided, signature was created.
// recommended signed transaction broadcast method.
// this will use the /transaction/announce endpoint.
$broadcast = [
"data" => Buffer::fromUInt8($serialized)->getHex(),
"signature" => $signature->getHex(),
];
}
else {
// WARNING: with this you must provide a `privateKey`
// in the transaction attributes. This is *not* recommended.
$broadcast = $transaction->toDTO();
}
$endpoint = $this->getAnnouncePath($transaction, $kp);
$apiUrl = $this->getPath($endpoint, []);
$response = $this->api->postJSON($apiUrl, $broadcast);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createBaseModel($object); //XXX brr => error/content validation first
} | php | public function announce(TxModel $transaction, KeyPair $kp = null)
{
// always set optional `signer` in case we provide a KeyPair
if (null !== $kp) {
$transaction->setAttribute("signer", $kp->getPublicKey("hex"));
}
// now we can serialize and sign
$serialized = $transaction->serialize();
$signature = $this->signTransaction($transaction, $kp, $serialized);
$broadcast = [];
if ($signature) {
// valid KeyPair provided, signature was created.
// recommended signed transaction broadcast method.
// this will use the /transaction/announce endpoint.
$broadcast = [
"data" => Buffer::fromUInt8($serialized)->getHex(),
"signature" => $signature->getHex(),
];
}
else {
// WARNING: with this you must provide a `privateKey`
// in the transaction attributes. This is *not* recommended.
$broadcast = $transaction->toDTO();
}
$endpoint = $this->getAnnouncePath($transaction, $kp);
$apiUrl = $this->getPath($endpoint, []);
$response = $this->api->postJSON($apiUrl, $broadcast);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createBaseModel($object); //XXX brr => error/content validation first
} | [
"public",
"function",
"announce",
"(",
"TxModel",
"$",
"transaction",
",",
"KeyPair",
"$",
"kp",
"=",
"null",
")",
"{",
"// always set optional `signer` in case we provide a KeyPair",
"if",
"(",
"null",
"!==",
"$",
"kp",
")",
"{",
"$",
"transaction",
"->",
"setA... | Announce a transaction. The transaction will be serialized before
it is sent to the server.
Additionally, a KeyPair object can be passed to this method *if you wish
to have the transaction **signed locally** by the SDK instead of letting
the remote NIS sign for you*. The local signing method **is recommended**.
WARNING: In case you don't provide this method with a KeyPair,
you must provide a `privateKey` in the transaction attributes.
It is *not* recommended to send `privateKey` data over any network,
even local.
@param \NEM\Models\Transaction $transaction
@return \NEM\Models\Model | [
"Announce",
"a",
"transaction",
".",
"The",
"transaction",
"will",
"be",
"serialized",
"before",
"it",
"is",
"sent",
"to",
"the",
"server",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Transaction.php#L112-L147 |
evias/nem-php | src/Infrastructure/Transaction.php | Transaction.byHash | public function byHash($hash)
{
$params = ["hash" => $hash];
$apiUrl = $this->getPath('get', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createTransactionModel($object['data']); //XXX brr => error/content validation first
} | php | public function byHash($hash)
{
$params = ["hash" => $hash];
$apiUrl = $this->getPath('get', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createTransactionModel($object['data']); //XXX brr => error/content validation first
} | [
"public",
"function",
"byHash",
"(",
"$",
"hash",
")",
"{",
"$",
"params",
"=",
"[",
"\"hash\"",
"=>",
"$",
"hash",
"]",
";",
"$",
"apiUrl",
"=",
"$",
"this",
"->",
"getPath",
"(",
"'get'",
",",
"$",
"params",
")",
";",
"$",
"response",
"=",
"$",... | Gets a transaction meta data pair where the transaction hash corresponds
to the said `hash` parameter. | [
"Gets",
"a",
"transaction",
"meta",
"data",
"pair",
"where",
"the",
"transaction",
"hash",
"corresponds",
"to",
"the",
"said",
"hash",
"parameter",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Transaction.php#L153-L162 |
evias/nem-php | src/API.php | API.setOptions | public function setOptions(array $options)
{
foreach ($options as $option => $config) {
if (! (bool) preg_match("/^[0-9A-Za-z_]+$/", $option))
// invalid option format
throw new InvalidArgumentException("Invalid option name provided to evias\\NEMBlockchain\\API@setOptions: " . var_export($option, true));
$upper = str_replace(" ", "", ucwords(str_replace("_", " ", $option)));
$setter = "set" . $upper;
if (method_exists($this, $setter))
$this->$setter($config);
elseif (method_exists($this->getRequestHandler(), $setter))
$this->getRequestHandler()->$setter($config);
}
return $this;
} | php | public function setOptions(array $options)
{
foreach ($options as $option => $config) {
if (! (bool) preg_match("/^[0-9A-Za-z_]+$/", $option))
// invalid option format
throw new InvalidArgumentException("Invalid option name provided to evias\\NEMBlockchain\\API@setOptions: " . var_export($option, true));
$upper = str_replace(" ", "", ucwords(str_replace("_", " ", $option)));
$setter = "set" . $upper;
if (method_exists($this, $setter))
$this->$setter($config);
elseif (method_exists($this->getRequestHandler(), $setter))
$this->getRequestHandler()->$setter($config);
}
return $this;
} | [
"public",
"function",
"setOptions",
"(",
"array",
"$",
"options",
")",
"{",
"foreach",
"(",
"$",
"options",
"as",
"$",
"option",
"=>",
"$",
"config",
")",
"{",
"if",
"(",
"!",
"(",
"bool",
")",
"preg_match",
"(",
"\"/^[0-9A-Za-z_]+$/\"",
",",
"$",
"opt... | This method allows to set the API configuration
through an array rather than using the Laravel
and Lumen Config contracts.
@param array $options
@return \NEM\API
@throws InvalidArgumentException on invalid option names. | [
"This",
"method",
"allows",
"to",
"set",
"the",
"API",
"configuration",
"through",
"an",
"array",
"rather",
"than",
"using",
"the",
"Laravel",
"and",
"Lumen",
"Config",
"contracts",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/API.php#L84-L101 |
evias/nem-php | src/API.php | API.getRequestHandler | public function getRequestHandler()
{
if (isset($this->requestHandler))
return $this->requestHandler;
// now instantiating handler from config
$handlerClass = "\\" . ltrim($this->handlerClass, "\\");
if (!class_exists($handlerClass))
throw new RuntimeException("Unable to create HTTP Handler instance with class: " . var_export($handlerClass, true));
$this->requestHandler = new $handlerClass();
return $this->requestHandler;
} | php | public function getRequestHandler()
{
if (isset($this->requestHandler))
return $this->requestHandler;
// now instantiating handler from config
$handlerClass = "\\" . ltrim($this->handlerClass, "\\");
if (!class_exists($handlerClass))
throw new RuntimeException("Unable to create HTTP Handler instance with class: " . var_export($handlerClass, true));
$this->requestHandler = new $handlerClass();
return $this->requestHandler;
} | [
"public",
"function",
"getRequestHandler",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"requestHandler",
")",
")",
"return",
"$",
"this",
"->",
"requestHandler",
";",
"// now instantiating handler from config",
"$",
"handlerClass",
"=",
"\"\\\\\"",
... | The getRequestHandler method creates an instance of the
`handlerClass` and returns it.
@return \NEM\Contracts\RequestHandler | [
"The",
"getRequestHandler",
"method",
"creates",
"an",
"instance",
"of",
"the",
"handlerClass",
"and",
"returns",
"it",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/API.php#L211-L223 |
evias/nem-php | src/Core/KeyPair.php | KeyPair.getAddress | public function getAddress($networkId = 104, $prettyFormat = false)
{
$address = \NEM\Models\Address::fromPublicKey($this->getPublicKey(), $networkId);
if ($prettyFormat) {
return $address->toPretty();
}
return $address->toClean();
} | php | public function getAddress($networkId = 104, $prettyFormat = false)
{
$address = \NEM\Models\Address::fromPublicKey($this->getPublicKey(), $networkId);
if ($prettyFormat) {
return $address->toPretty();
}
return $address->toClean();
} | [
"public",
"function",
"getAddress",
"(",
"$",
"networkId",
"=",
"104",
",",
"$",
"prettyFormat",
"=",
"false",
")",
"{",
"$",
"address",
"=",
"\\",
"NEM",
"\\",
"Models",
"\\",
"Address",
"::",
"fromPublicKey",
"(",
"$",
"this",
"->",
"getPublicKey",
"("... | This method should return the *base32 encoded representation* of the
NEM Address.
@param string|integer $networkId A network ID OR a network name. (default mainnet)
@param boolean $prettyFormat Boolean whether address should be prettified or not.
@return string | [
"This",
"method",
"should",
"return",
"the",
"*",
"base32",
"encoded",
"representation",
"*",
"of",
"the",
"NEM",
"Address",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/KeyPair.php#L174-L182 |
evias/nem-php | src/Core/KeyPair.php | KeyPair.sign | public function sign($data, $algorithm = "keccak-512", $enc = null)
{
if ($data instanceof Buffer) {
$data = $data->getBinary();
}
elseif (is_string($data) && ctype_xdigit($data)) {
$data = Buffer::fromHex($data)->getBinary();
}
elseif (is_array($data)) {
// Uint8 provided (serialized data)
$data = Buffer::fromUInt8($data)->getBinary();
}
elseif (!is_string($data)) {
throw new NISInvalidSignatureContent("Invalid data argument passed in \\NEM\\Core\\KeyPair::sign().");
}
$buf = new Buffer($data);
$sig = new Signature($this, $buf, $algorithm);
return $this->encodeKey($sig->getSignature(), $enc);
} | php | public function sign($data, $algorithm = "keccak-512", $enc = null)
{
if ($data instanceof Buffer) {
$data = $data->getBinary();
}
elseif (is_string($data) && ctype_xdigit($data)) {
$data = Buffer::fromHex($data)->getBinary();
}
elseif (is_array($data)) {
// Uint8 provided (serialized data)
$data = Buffer::fromUInt8($data)->getBinary();
}
elseif (!is_string($data)) {
throw new NISInvalidSignatureContent("Invalid data argument passed in \\NEM\\Core\\KeyPair::sign().");
}
$buf = new Buffer($data);
$sig = new Signature($this, $buf, $algorithm);
return $this->encodeKey($sig->getSignature(), $enc);
} | [
"public",
"function",
"sign",
"(",
"$",
"data",
",",
"$",
"algorithm",
"=",
"\"keccak-512\"",
",",
"$",
"enc",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"data",
"instanceof",
"Buffer",
")",
"{",
"$",
"data",
"=",
"$",
"data",
"->",
"getBinary",
"(",
"... | This method returns a 64 bytes signature of the *data signed with the
current `secretKey`*.
You can also specify the `enc` parameter to be "hex", "uint8" or "int32".
@param null|array|string|\NEM\Core\Buffer $data The data that needs to be signed.
@param string $algorithm The hash algorithm used for signature creation.
@param string|integer $enc Which encoding to return (One of: "hex", "uint8", "int32")
@return \NEM\Core\Buffer|string|array Returns either of Buffer, string hexadecimal representation, or UInt8 or Int32 array. | [
"This",
"method",
"returns",
"a",
"64",
"bytes",
"signature",
"of",
"the",
"*",
"data",
"signed",
"with",
"the",
"current",
"secretKey",
"*",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/KeyPair.php#L195-L214 |
evias/nem-php | src/Core/KeyPair.php | KeyPair.preparePrivateKey | protected function preparePrivateKey($privateKey = null)
{
if (is_string($privateKey)) {
// provided a string, must check if it contains 64 or 66 characters.
// and whether it is valid hexadecimal data.
$keySize = strlen($privateKey);
if ($keySize !== 64 && $keySize !== 66) {
throw new NISInvalidPrivateKeySize("Private keys must be 64 or 66 characters exactly.");
}
elseif (! ctype_xdigit($privateKey)) {
throw new NISInvalidPrivateKeyContent("Argument 'privateKey' in KeyPair::create must contain only Hexadecimal data.");
}
// remove NIS negative "00" prefix if available.
$this->privateKey = Buffer::fromHex(substr($privateKey, -64), 32);
}
elseif ($privateKey instanceof KeyPair) {
// copy construction - copy the KeyPair object
$this->privateKey = $privateKey->privateKey;
$this->secretKey = $privateKey->secretKey;
$this->publicKey = $privateKey->publicKey;
}
elseif ($privateKey instanceof Buffer) {
// copy construction - clone the buffer (binary data of the private key)
$this->privateKey = clone $privateKey;
}
elseif (null === $privateKey) {
// no `privateKey` provided, generate a new KeyPair
$this->privateKey = new Buffer(random_bytes(32), 32);
}
elseif ($privateKey !== null) {
// `privateKey` could not be interpreted.
throw new RuntimeException("Invalid Private key for KeyPair creation. Please use hexadecimal notation (64|66 characters string) or the \\NEM\\Core\\Buffer class.");
}
// secret key is the byte-level-reversed representation of the private key.
$this->secretKey = $this->privateKey->flip();
return $this;
} | php | protected function preparePrivateKey($privateKey = null)
{
if (is_string($privateKey)) {
// provided a string, must check if it contains 64 or 66 characters.
// and whether it is valid hexadecimal data.
$keySize = strlen($privateKey);
if ($keySize !== 64 && $keySize !== 66) {
throw new NISInvalidPrivateKeySize("Private keys must be 64 or 66 characters exactly.");
}
elseif (! ctype_xdigit($privateKey)) {
throw new NISInvalidPrivateKeyContent("Argument 'privateKey' in KeyPair::create must contain only Hexadecimal data.");
}
// remove NIS negative "00" prefix if available.
$this->privateKey = Buffer::fromHex(substr($privateKey, -64), 32);
}
elseif ($privateKey instanceof KeyPair) {
// copy construction - copy the KeyPair object
$this->privateKey = $privateKey->privateKey;
$this->secretKey = $privateKey->secretKey;
$this->publicKey = $privateKey->publicKey;
}
elseif ($privateKey instanceof Buffer) {
// copy construction - clone the buffer (binary data of the private key)
$this->privateKey = clone $privateKey;
}
elseif (null === $privateKey) {
// no `privateKey` provided, generate a new KeyPair
$this->privateKey = new Buffer(random_bytes(32), 32);
}
elseif ($privateKey !== null) {
// `privateKey` could not be interpreted.
throw new RuntimeException("Invalid Private key for KeyPair creation. Please use hexadecimal notation (64|66 characters string) or the \\NEM\\Core\\Buffer class.");
}
// secret key is the byte-level-reversed representation of the private key.
$this->secretKey = $this->privateKey->flip();
return $this;
} | [
"protected",
"function",
"preparePrivateKey",
"(",
"$",
"privateKey",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"privateKey",
")",
")",
"{",
"// provided a string, must check if it contains 64 or 66 characters.",
"// and whether it is valid hexadecimal data.",
... | This method will parse a given `privateKey` such that we
store the binary representation of the private key *always*.
This method is used internally to create the KeyPair secret key
which is the key that is actually hashed and derived to get the
public key.
@internal
@param null|string|\NEM\Core\Buffer|\NEM\Core\KeyPair $privateKey The private key in hexadecimal format (or in Buffer).
@return \NEM\Core\KeyPair
@throws \NEM\Errors\NISInvalidPrivateKeySize On string key size with wrong length. (strictly 64 or 66 characters)
@throws \NEM\Errors\NISInvalidPrivateKeyContent On string key invalid content. (non hexadecimal characters) | [
"This",
"method",
"will",
"parse",
"a",
"given",
"privateKey",
"such",
"that",
"we",
"store",
"the",
"binary",
"representation",
"of",
"the",
"private",
"key",
"*",
"always",
"*",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/KeyPair.php#L230-L269 |
evias/nem-php | src/Core/KeyPair.php | KeyPair.preparePublicKey | protected function preparePublicKey($publicKey = null)
{
if (is_string($publicKey)) {
// provided a string, must check if it contains 64 characters.
// and whether it is valid hexadecimal data.
$keySize = strlen($publicKey);
if ($keySize !== 64) {
throw new NISInvalidPublicKeySize("Public keys must be strictly 64 hexadecimal characters.");
}
elseif (! ctype_xdigit($publicKey)) {
throw new NISInvalidPublicKeyContent("Argument 'publicKey' in KeyPair::create must contain only Hexadecimal data.");
}
$this->publicKey = Buffer::fromHex($publicKey, 32);
}
elseif ($publicKey instanceof Buffer) {
// copy construction - clone the buffer (binary data of the private key)
$this->publicKey = clone $publicKey;
}
elseif ($publicKey !== null) {
// `publicKey` could not be interpreted.
throw new RuntimeException("Invalid Private key for KeyPair creation. Please use hexadecimal notation (64|66 characters string) or the \\NEM\\Core\\Buffer class.");
}
return $this->publicKey;
} | php | protected function preparePublicKey($publicKey = null)
{
if (is_string($publicKey)) {
// provided a string, must check if it contains 64 characters.
// and whether it is valid hexadecimal data.
$keySize = strlen($publicKey);
if ($keySize !== 64) {
throw new NISInvalidPublicKeySize("Public keys must be strictly 64 hexadecimal characters.");
}
elseif (! ctype_xdigit($publicKey)) {
throw new NISInvalidPublicKeyContent("Argument 'publicKey' in KeyPair::create must contain only Hexadecimal data.");
}
$this->publicKey = Buffer::fromHex($publicKey, 32);
}
elseif ($publicKey instanceof Buffer) {
// copy construction - clone the buffer (binary data of the private key)
$this->publicKey = clone $publicKey;
}
elseif ($publicKey !== null) {
// `publicKey` could not be interpreted.
throw new RuntimeException("Invalid Private key for KeyPair creation. Please use hexadecimal notation (64|66 characters string) or the \\NEM\\Core\\Buffer class.");
}
return $this->publicKey;
} | [
"protected",
"function",
"preparePublicKey",
"(",
"$",
"publicKey",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"publicKey",
")",
")",
"{",
"// provided a string, must check if it contains 64 characters.",
"// and whether it is valid hexadecimal data.",
"$",
... | This method will parse a given `publicKey` such that we
store the binary representation of the public key *always*.
This method is used internally whenever a public key *is not*
derived of the passed private key but rather passed directly in
hexadecimal or binary representation.
@internal
@param null|string|\NEM\Core\Buffer $publicKey The public key in hexadecimal format (or in Buffer).
@return \NEM\Core\KeyPair
@throws \NEM\Errors\NISInvalidPublicKeySize On string key size with wrong length. (strictly 64 characters)
@throws \NEM\Errors\NISInvalidPublicKeyContent On string key invalid content. (non hexadecimal characters) | [
"This",
"method",
"will",
"parse",
"a",
"given",
"publicKey",
"such",
"that",
"we",
"store",
"the",
"binary",
"representation",
"of",
"the",
"public",
"key",
"*",
"always",
"*",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/KeyPair.php#L285-L311 |
evias/nem-php | src/Core/KeyPair.php | KeyPair.encodeKey | protected function encodeKey(Buffer $key, $enc = null)
{
if ("hex" === $enc || (int) $enc == 16) {
return $key->getHex();
}
elseif ("uint8" === $enc || (int) $enc == 8) {
return $key->toUInt8();
}
elseif ("int32" === $enc || (int) $enc == 32) {
$encoder = new Encoder;
return $encoder->ua2words($key->toUInt8());
}
return $key;
} | php | protected function encodeKey(Buffer $key, $enc = null)
{
if ("hex" === $enc || (int) $enc == 16) {
return $key->getHex();
}
elseif ("uint8" === $enc || (int) $enc == 8) {
return $key->toUInt8();
}
elseif ("int32" === $enc || (int) $enc == 32) {
$encoder = new Encoder;
return $encoder->ua2words($key->toUInt8());
}
return $key;
} | [
"protected",
"function",
"encodeKey",
"(",
"Buffer",
"$",
"key",
",",
"$",
"enc",
"=",
"null",
")",
"{",
"if",
"(",
"\"hex\"",
"===",
"$",
"enc",
"||",
"(",
"int",
")",
"$",
"enc",
"==",
"16",
")",
"{",
"return",
"$",
"key",
"->",
"getHex",
"(",
... | This method encodes a given `key` to the given `enc` codec or
returns the Buffer itself if no encoding was specified.
@param \NEM\Core\Buffer $key The Key object (Buffer) that needs to be encoded.
@param string|integer $enc Which encoding to use (One of: "hex", "uint8", "int32")
@return \NEM\Core\Buffer|string|array Returns either of Buffer, string hexadecimal representation, or UInt8 or Int32 array. | [
"This",
"method",
"encodes",
"a",
"given",
"key",
"to",
"the",
"given",
"enc",
"codec",
"or",
"returns",
"the",
"Buffer",
"itself",
"if",
"no",
"encoding",
"was",
"specified",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/KeyPair.php#L321-L335 |
evias/nem-php | src/Models/Transaction/ImportanceTransfer.php | ImportanceTransfer.serialize | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_mode = $serializer->serializeInt($nisData["mode"]);
$uint8_acct = $serializer->serializeString(hex2bin($nisData["remoteAccount"]));
// concatenate the UInt8 representation
$output = array_merge(
$uint8_mode,
$uint8_acct);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | php | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_mode = $serializer->serializeInt($nisData["mode"]);
$uint8_acct = $serializer->serializeString(hex2bin($nisData["remoteAccount"]));
// concatenate the UInt8 representation
$output = array_merge(
$uint8_mode,
$uint8_acct);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"extend",
"(",
")",
";",
"// shortcuts",
"$",
... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *ImportanceTransfer* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"ImportanceTransfer",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/ImportanceTransfer.php#L65-L85 |
evias/nem-php | src/Models/Transaction/ImportanceTransfer.php | ImportanceTransfer.extend | public function extend()
{
// set default mode in case its invalid
$mode = $this->getAttribute("mode");
if (! $mode || ! in_array($mode, [self::MODE_ACTIVATE, self::MODE_DEACTIVATE])) {
$mode = self::MODE_ACTIVATE;
$this->setAttribute("mode", $mode);
}
return [
"remoteAccount" => $this->remoteAccount()->publicKey,
"mode" => $this->mode,
// transaction type specialization
"type" => TransactionType::IMPORTANCE_TRANSFER,
];
} | php | public function extend()
{
// set default mode in case its invalid
$mode = $this->getAttribute("mode");
if (! $mode || ! in_array($mode, [self::MODE_ACTIVATE, self::MODE_DEACTIVATE])) {
$mode = self::MODE_ACTIVATE;
$this->setAttribute("mode", $mode);
}
return [
"remoteAccount" => $this->remoteAccount()->publicKey,
"mode" => $this->mode,
// transaction type specialization
"type" => TransactionType::IMPORTANCE_TRANSFER,
];
} | [
"public",
"function",
"extend",
"(",
")",
"{",
"// set default mode in case its invalid",
"$",
"mode",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"\"mode\"",
")",
";",
"if",
"(",
"!",
"$",
"mode",
"||",
"!",
"in_array",
"(",
"$",
"mode",
",",
"[",
"sel... | The Signature transaction type does not need to add an offset to
the transaction base DTO.
@return array | [
"The",
"Signature",
"transaction",
"type",
"does",
"not",
"need",
"to",
"add",
"an",
"offset",
"to",
"the",
"transaction",
"base",
"DTO",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/ImportanceTransfer.php#L93-L108 |
evias/nem-php | src/Mosaics/Dim/Coin.php | Coin.levy | public function levy(array $levy = null)
{
$data = $levy ?: [
"type" => MosaicLevy::TYPE_PERCENTILE,
"fee" => 10,
"recipient" => "NCGGLVO2G3CUACVI5GNX2KRBJSQCN4RDL2ZWJ4DP",
"mosaicId" => $this->id()->toDTO(),
];
return new MosaicLevy($data);
} | php | public function levy(array $levy = null)
{
$data = $levy ?: [
"type" => MosaicLevy::TYPE_PERCENTILE,
"fee" => 10,
"recipient" => "NCGGLVO2G3CUACVI5GNX2KRBJSQCN4RDL2ZWJ4DP",
"mosaicId" => $this->id()->toDTO(),
];
return new MosaicLevy($data);
} | [
"public",
"function",
"levy",
"(",
"array",
"$",
"levy",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"$",
"levy",
"?",
":",
"[",
"\"type\"",
"=>",
"MosaicLevy",
"::",
"TYPE_PERCENTILE",
",",
"\"fee\"",
"=>",
"10",
",",
"\"recipient\"",
"=>",
"\"NCGGLVO2G3CU... | Mutator for `levy` relation.
This will return a NIS compliant [MosaicLevy](https://bob.nem.ninja/docs/#mosaicLevy) object.
@param array $mosaidId Array should contain offsets `type`, `recipient`, `mosaicId` and `fee`.
@return \NEM\Models\MosaicLevy | [
"Mutator",
"for",
"levy",
"relation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Mosaics/Dim/Coin.php#L87-L97 |
evias/nem-php | src/Core/Buffer.php | Buffer.bufferize | static public function bufferize($data, $byteSize = null, $paddingDirection = self::PAD_LEFT)
{
if (is_integer($data)) {
// Buffer from Decimal
return Buffer::fromInt($data, $byteSize, null, $paddingDirection);
}
$charLen = strlen($data);
if (ctype_xdigit($data) && $charLen % 32 === 0) {
// Buffer from Hexadecimal
return Buffer::fromHex($data, $byteSize, $paddingDirection);
}
// Buffer from Normalized String
return Buffer::fromString($data, $paddingDirection);
} | php | static public function bufferize($data, $byteSize = null, $paddingDirection = self::PAD_LEFT)
{
if (is_integer($data)) {
// Buffer from Decimal
return Buffer::fromInt($data, $byteSize, null, $paddingDirection);
}
$charLen = strlen($data);
if (ctype_xdigit($data) && $charLen % 32 === 0) {
// Buffer from Hexadecimal
return Buffer::fromHex($data, $byteSize, $paddingDirection);
}
// Buffer from Normalized String
return Buffer::fromString($data, $paddingDirection);
} | [
"static",
"public",
"function",
"bufferize",
"(",
"$",
"data",
",",
"$",
"byteSize",
"=",
"null",
",",
"$",
"paddingDirection",
"=",
"self",
"::",
"PAD_LEFT",
")",
"{",
"if",
"(",
"is_integer",
"(",
"$",
"data",
")",
")",
"{",
"// Buffer from Decimal",
"... | Build a Buffer from `data`.
Dynamic Buffer creation. Decimals, Hexadecimals
and String are handled differently in binary form.
Only use the bufferize method for Hexadecimal input
in case you are sure about the data length. It must
be a multiple of 32-bytes. (32, 64, 96, etc.)
When you are working with Hexadecimal data, it is
*preferred* to use the `fromHex` method directly.
@param string|integer $data
@param integer $byteSize
@return \NEM\Core\Buffer | [
"Build",
"a",
"Buffer",
"from",
"data",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L147-L162 |
evias/nem-php | src/Core/Buffer.php | Buffer.fromString | static public function fromString($string, $paddingDirection = self::PAD_LEFT)
{
if (!class_exists("Normalizer")) {
// Data representation Normalization not supported
return new Buffer($string, null, $paddingDirection);
}
// Normalizer is used to avoid problems with UTF-8 serialization
$normalized = \Normalizer::normalize($string, \Normalizer::FORM_KD);
return new Buffer($normalized, null, $paddingDirection);
} | php | static public function fromString($string, $paddingDirection = self::PAD_LEFT)
{
if (!class_exists("Normalizer")) {
// Data representation Normalization not supported
return new Buffer($string, null, $paddingDirection);
}
// Normalizer is used to avoid problems with UTF-8 serialization
$normalized = \Normalizer::normalize($string, \Normalizer::FORM_KD);
return new Buffer($normalized, null, $paddingDirection);
} | [
"static",
"public",
"function",
"fromString",
"(",
"$",
"string",
",",
"$",
"paddingDirection",
"=",
"self",
"::",
"PAD_LEFT",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"\"Normalizer\"",
")",
")",
"{",
"// Data representation Normalization not supported",
"re... | Build Buffer from string
In case \Normalizer is available, the utf-8 string will
be normalized with Normalization Form KD.
@param string $string
@return \NEM\Core\Buffer | [
"Build",
"Buffer",
"from",
"string"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L173-L183 |
evias/nem-php | src/Core/Buffer.php | Buffer.fromHex | static public function fromHex($hexString = '', $byteSize = null, $paddingDirection = self::PAD_LEFT)
{
if (strlen($hexString) > 0 && !ctype_xdigit($hexString)) {
throw new InvalidArgumentException('NEM\\Core\\Buffer::hex: non-hexadecimal character passed');
}
// format to binary hexadecimal string
$binary = pack("H*", $hexString);
return new self($binary, $byteSize, $paddingDirection);
} | php | static public function fromHex($hexString = '', $byteSize = null, $paddingDirection = self::PAD_LEFT)
{
if (strlen($hexString) > 0 && !ctype_xdigit($hexString)) {
throw new InvalidArgumentException('NEM\\Core\\Buffer::hex: non-hexadecimal character passed');
}
// format to binary hexadecimal string
$binary = pack("H*", $hexString);
return new self($binary, $byteSize, $paddingDirection);
} | [
"static",
"public",
"function",
"fromHex",
"(",
"$",
"hexString",
"=",
"''",
",",
"$",
"byteSize",
"=",
"null",
",",
"$",
"paddingDirection",
"=",
"self",
"::",
"PAD_LEFT",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"hexString",
")",
">",
"0",
"&&",
"!... | Buffer::fromHex()
Create a new buffer from a hexadecimal string.
@param string $hexString
@param integer $byteSize
@return \NEM\Core\Buffer
@throws \InvalidArgumentException On non-hexadecimal content in `hexString` | [
"Buffer",
"::",
"fromHex",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L195-L204 |
evias/nem-php | src/Core/Buffer.php | Buffer.fromInt | static public function fromInt($integer, $byteSize = null, GmpMathInterface $math = null, $paddingDirection = self::PAD_LEFT)
{
if ($integer < 0) {
throw new InvalidArgumentException('Buffer::int supports only unsigned integers.');
}
$math = $math ?: EccFactory::getAdapter();
$binary = null;
if ($integer !== null) {
$binary = pack("H*", $math->decHex($integer));
}
return new self($binary, $byteSize, $paddingDirection);
} | php | static public function fromInt($integer, $byteSize = null, GmpMathInterface $math = null, $paddingDirection = self::PAD_LEFT)
{
if ($integer < 0) {
throw new InvalidArgumentException('Buffer::int supports only unsigned integers.');
}
$math = $math ?: EccFactory::getAdapter();
$binary = null;
if ($integer !== null) {
$binary = pack("H*", $math->decHex($integer));
}
return new self($binary, $byteSize, $paddingDirection);
} | [
"static",
"public",
"function",
"fromInt",
"(",
"$",
"integer",
",",
"$",
"byteSize",
"=",
"null",
",",
"GmpMathInterface",
"$",
"math",
"=",
"null",
",",
"$",
"paddingDirection",
"=",
"self",
"::",
"PAD_LEFT",
")",
"{",
"if",
"(",
"$",
"integer",
"<",
... | Buffer::fromInt()
Create a new buffer from an integer.
The decimal format will be converted to hexadecimal first then
packed as a hexadecimal string.
@param int|string $integer
@param null|int $byteSize
@param \Mdanter\Ecc\Math\GmpMathInterface $math Allow to define custom Math Adapter.
@return \NEM\Core\Buffer
@throws InvalidArgumentException On negative integer value | [
"Buffer",
"::",
"fromInt",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L238-L251 |
evias/nem-php | src/Core/Buffer.php | Buffer.getBinary | public function getBinary()
{
// if a size is specified we'll make sure the value returned is *strictly* of that size
if ($this->size !== null) {
if (strlen($this->buffer) < $this->size) {
// internal size of buffer is *too small*
// will now pad the string (zeropadding).
$direction = $this->paddingDirection == self::PAD_RIGHT ? STR_PAD_RIGHT : STR_PAD_LEFT;
return str_pad($this->buffer, $this->size, chr(0), $direction);
}
elseif (strlen($this->buffer) > $this->size) {
// buffer size overflow - truncate the buffer
return substr($this->buffer, 0, $this->size);
}
}
return $this->buffer;
} | php | public function getBinary()
{
// if a size is specified we'll make sure the value returned is *strictly* of that size
if ($this->size !== null) {
if (strlen($this->buffer) < $this->size) {
// internal size of buffer is *too small*
// will now pad the string (zeropadding).
$direction = $this->paddingDirection == self::PAD_RIGHT ? STR_PAD_RIGHT : STR_PAD_LEFT;
return str_pad($this->buffer, $this->size, chr(0), $direction);
}
elseif (strlen($this->buffer) > $this->size) {
// buffer size overflow - truncate the buffer
return substr($this->buffer, 0, $this->size);
}
}
return $this->buffer;
} | [
"public",
"function",
"getBinary",
"(",
")",
"{",
"// if a size is specified we'll make sure the value returned is *strictly* of that size",
"if",
"(",
"$",
"this",
"->",
"size",
"!==",
"null",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"this",
"->",
"buffer",
")",
... | Buffer::getBinary()
Get the binary data of the buffer.
The binary data will be truncated or padded in case
the buffer content size and buffer size do not
match.
This ensures that *whenever a size is set*, we will
get a strictly well-sized binary data format.
@return string | [
"Buffer",
"::",
"getBinary",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L291-L308 |
evias/nem-php | src/Core/Buffer.php | Buffer.getGmp | public function getGmp($base = null)
{
$gmp = gmp_init($this->getHex(), 16);
if (null !== $base)
return gmp_strval($gmp, (int) $base);
return $gmp;
} | php | public function getGmp($base = null)
{
$gmp = gmp_init($this->getHex(), 16);
if (null !== $base)
return gmp_strval($gmp, (int) $base);
return $gmp;
} | [
"public",
"function",
"getGmp",
"(",
"$",
"base",
"=",
"null",
")",
"{",
"$",
"gmp",
"=",
"gmp_init",
"(",
"$",
"this",
"->",
"getHex",
"(",
")",
",",
"16",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"base",
")",
"return",
"gmp_strval",
"(",
"$",
... | Buffer::getGmp()
Get Base16 representation (hexadecimal).
This uses the GNU Multiple Precision PHP wrapper to
create a GMP number with the given base. (here 16 - hexadecimal)
@return \GMP | [
"Buffer",
"::",
"getGmp",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L332-L340 |
evias/nem-php | src/Core/Buffer.php | Buffer.slice | public function slice($start, $end = null)
{
if ($start > $this->getSize()) {
throw new InvalidArgumentException('Start exceeds buffer length');
}
if ($end === null) {
return new self(substr($this->getBinary(), $start));
}
if ($end > $this->getSize()) {
throw new InvalidArgumentException('Length exceeds buffer length');
}
$string = substr($this->getBinary(), $start, $end);
if (!is_string($string)) {
throw new RuntimeException('Failed to slice string of with requested start/end');
}
$length = strlen($string);
return new self($string, $length);
} | php | public function slice($start, $end = null)
{
if ($start > $this->getSize()) {
throw new InvalidArgumentException('Start exceeds buffer length');
}
if ($end === null) {
return new self(substr($this->getBinary(), $start));
}
if ($end > $this->getSize()) {
throw new InvalidArgumentException('Length exceeds buffer length');
}
$string = substr($this->getBinary(), $start, $end);
if (!is_string($string)) {
throw new RuntimeException('Failed to slice string of with requested start/end');
}
$length = strlen($string);
return new self($string, $length);
} | [
"public",
"function",
"slice",
"(",
"$",
"start",
",",
"$",
"end",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"start",
">",
"$",
"this",
"->",
"getSize",
"(",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Start exceeds buffer length'",
")... | Buffer::slice()
Get part of a buffer content.
@param integer $start Where in the buffer content should we start?
@param integer|null $end (Optional) end of slice
@return \NEM\Core\Buffer
@throws \InvalidArgumentException On invalid start or end parameter
@throws \RuntimeException On invalid resulting string slice | [
"Buffer",
"::",
"slice",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L404-L425 |
evias/nem-php | src/Core/Buffer.php | Buffer.equals | public function equals(Buffer $other)
{
return ($other->getSize() === $this->getSize()
&& $other->getBinary() === $this->getBinary());
} | php | public function equals(Buffer $other)
{
return ($other->getSize() === $this->getSize()
&& $other->getBinary() === $this->getBinary());
} | [
"public",
"function",
"equals",
"(",
"Buffer",
"$",
"other",
")",
"{",
"return",
"(",
"$",
"other",
"->",
"getSize",
"(",
")",
"===",
"$",
"this",
"->",
"getSize",
"(",
")",
"&&",
"$",
"other",
"->",
"getBinary",
"(",
")",
"===",
"$",
"this",
"->",... | Buffer::equals()
Buffer comparison operator.
@param Buffer $other
@return bool | [
"Buffer",
"::",
"equals",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L435-L439 |
evias/nem-php | src/Core/Buffer.php | Buffer.decimalToBinary | public function decimalToBinary($decimal, $size = null, $padding = false, $direction = self::PAD_LEFT)
{
if ($decimal < 0xfd) {
// Uint8 (unsigned char)
$bin = chr($decimal);
}
elseif ($decimal <= 0xffff) {
// Uint16 (unsigned short)
$bin = pack("Cv", 0xfd, $decimal);
}
elseif ($decimal <= 0xffffffff) {
// Uint32 (unsigned long)
$bin = pack("CV", 0xfe, $decimal);
}
else {
// Uint64 (unsigned long long)
// convert to 32-bit notation and concat-pack
$smallerThan = 0x00000000ffffffff;
$biggerThan = 0xffffffff00000000;
$a32 = ($decimal & $biggerThan) >>32;
$b32 = $decimal & $smallerThan;
$bin = pack("NN", $a32, $b32);
}
// add padding when needed
if ($padding = true && $size) {
$buf = new Buffer($bin, $size, $direction);
$bin = $buf->getBinary();
}
return $bin;
} | php | public function decimalToBinary($decimal, $size = null, $padding = false, $direction = self::PAD_LEFT)
{
if ($decimal < 0xfd) {
// Uint8 (unsigned char)
$bin = chr($decimal);
}
elseif ($decimal <= 0xffff) {
// Uint16 (unsigned short)
$bin = pack("Cv", 0xfd, $decimal);
}
elseif ($decimal <= 0xffffffff) {
// Uint32 (unsigned long)
$bin = pack("CV", 0xfe, $decimal);
}
else {
// Uint64 (unsigned long long)
// convert to 32-bit notation and concat-pack
$smallerThan = 0x00000000ffffffff;
$biggerThan = 0xffffffff00000000;
$a32 = ($decimal & $biggerThan) >>32;
$b32 = $decimal & $smallerThan;
$bin = pack("NN", $a32, $b32);
}
// add padding when needed
if ($padding = true && $size) {
$buf = new Buffer($bin, $size, $direction);
$bin = $buf->getBinary();
}
return $bin;
} | [
"public",
"function",
"decimalToBinary",
"(",
"$",
"decimal",
",",
"$",
"size",
"=",
"null",
",",
"$",
"padding",
"=",
"false",
",",
"$",
"direction",
"=",
"self",
"::",
"PAD_LEFT",
")",
"{",
"if",
"(",
"$",
"decimal",
"<",
"0xfd",
")",
"{",
"// Uint... | Buffer::decimalToBinary()
Return variable-sized Binary Integer value from decimal
value `decimal`.
This will return either a `unsigned char`, a 16-bit
number, a 32-bit number or a 64-bit
number.
@param int $decimal
@return string Binary Data | [
"Buffer",
"::",
"decimalToBinary",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L454-L487 |
evias/nem-php | src/Core/Buffer.php | Buffer.flipBytes | public function flipBytes($bytes = null)
{
if (null === $bytes && $this instanceof Buffer) {
$bytes = $this;
}
$isBuffer = $bytes instanceof Buffer;
if ($isBuffer) {
$bytes = $bytes->getBinary();
}
$flipped = implode('', array_reverse(str_split($bytes, 1)));
if ($isBuffer) {
$flipped = new Buffer($flipped);
}
return $flipped;
} | php | public function flipBytes($bytes = null)
{
if (null === $bytes && $this instanceof Buffer) {
$bytes = $this;
}
$isBuffer = $bytes instanceof Buffer;
if ($isBuffer) {
$bytes = $bytes->getBinary();
}
$flipped = implode('', array_reverse(str_split($bytes, 1)));
if ($isBuffer) {
$flipped = new Buffer($flipped);
}
return $flipped;
} | [
"public",
"function",
"flipBytes",
"(",
"$",
"bytes",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"bytes",
"&&",
"$",
"this",
"instanceof",
"Buffer",
")",
"{",
"$",
"bytes",
"=",
"$",
"this",
";",
"}",
"$",
"isBuffer",
"=",
"$",
"bytes",
... | Buffer::flipBytes()
Flip byte order (reverse order) of this binary string. Accepts a string or Buffer,
and will return whatever type it was given.
@param null|string|\NEM\Core\Buffer $bytes Bytes that must be reversed.
@return string|\NEM\Core\Buffer | [
"Buffer",
"::",
"flipBytes",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L511-L528 |
evias/nem-php | src/Core/Buffer.php | Buffer.toUInt8 | public function toUInt8()
{
$binary = $this->getBinary();
$split = str_split($binary, 1);
// argument *by-reference*
array_walk($split, function(&$item, $ix) {
$buf = new Buffer($item, 1);
$item = (int) $buf->getInt();
});
return $split;
} | php | public function toUInt8()
{
$binary = $this->getBinary();
$split = str_split($binary, 1);
// argument *by-reference*
array_walk($split, function(&$item, $ix) {
$buf = new Buffer($item, 1);
$item = (int) $buf->getInt();
});
return $split;
} | [
"public",
"function",
"toUInt8",
"(",
")",
"{",
"$",
"binary",
"=",
"$",
"this",
"->",
"getBinary",
"(",
")",
";",
"$",
"split",
"=",
"str_split",
"(",
"$",
"binary",
",",
"1",
")",
";",
"// argument *by-reference*",
"array_walk",
"(",
"$",
"split",
",... | Transfer binary data into a unsigned char array. Unsigned Char
is the same as UInt8 in Javascript or other languages, it represents
unsigned integers on 8 bits (1 byte).
@return array | [
"Transfer",
"binary",
"data",
"into",
"a",
"unsigned",
"char",
"array",
".",
"Unsigned",
"Char",
"is",
"the",
"same",
"as",
"UInt8",
"in",
"Javascript",
"or",
"other",
"languages",
"it",
"represents",
"unsigned",
"integers",
"on",
"8",
"bits",
"(",
"1",
"b... | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L537-L549 |
evias/nem-php | src/Core/Buffer.php | Buffer.concat | public function concat(Buffer $buffer)
{
// size-protected through Buffer class
$this->buffer = $this->buffer . $buffer->getBinary();
$this->size += $buffer->getSize();
return $this;
} | php | public function concat(Buffer $buffer)
{
// size-protected through Buffer class
$this->buffer = $this->buffer . $buffer->getBinary();
$this->size += $buffer->getSize();
return $this;
} | [
"public",
"function",
"concat",
"(",
"Buffer",
"$",
"buffer",
")",
"{",
"// size-protected through Buffer class",
"$",
"this",
"->",
"buffer",
"=",
"$",
"this",
"->",
"buffer",
".",
"$",
"buffer",
"->",
"getBinary",
"(",
")",
";",
"$",
"this",
"->",
"size"... | Buffer::concat()
Concatenate buffers
@param \NEM\Core\Buffer $buffer1
@return \NEM\Core\Buffer | [
"Buffer",
"::",
"concat",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L559-L565 |
evias/nem-php | src/Core/Buffer.php | Buffer.sort | public function sort(array $items, callable $convertToBuffer = null)
{
if (null == $convertToBuffer) {
$convertToBuffer = function ($value) {
if ($value instanceof Buffer) {
return $value;
}
if ($value instanceof Serializable) {
return $value->getBuffer();
}
throw new RuntimeException('Requested to sort unknown buffer type');
};
}
usort($items, function ($a, $b) use ($convertToBuffer) {
$av = $convertToBuffer($a)->getBinary();
$bv = $convertToBuffer($b)->getBinary();
return $av == $bv ? 0 : $av > $bv ? 1 : -1;
});
return $items;
} | php | public function sort(array $items, callable $convertToBuffer = null)
{
if (null == $convertToBuffer) {
$convertToBuffer = function ($value) {
if ($value instanceof Buffer) {
return $value;
}
if ($value instanceof Serializable) {
return $value->getBuffer();
}
throw new RuntimeException('Requested to sort unknown buffer type');
};
}
usort($items, function ($a, $b) use ($convertToBuffer) {
$av = $convertToBuffer($a)->getBinary();
$bv = $convertToBuffer($b)->getBinary();
return $av == $bv ? 0 : $av > $bv ? 1 : -1;
});
return $items;
} | [
"public",
"function",
"sort",
"(",
"array",
"$",
"items",
",",
"callable",
"$",
"convertToBuffer",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"==",
"$",
"convertToBuffer",
")",
"{",
"$",
"convertToBuffer",
"=",
"function",
"(",
"$",
"value",
")",
"{",
"... | Buffer::sort()
Sorting multiple buffers.
The default behaviour should be, take a list of Buffers/SerializableInterfaces, and
sort their binary representation.
If an anonymous function is provided, we completely defer the conversion of values to
Buffer to the $convertToBuffer callable.
This is to allow anonymous functions which are responsible for converting the item to a buffer,
and which optionally type-hint the items in the array.
@param array $items Array of buffers to sort
@param callable $convertToBuffer (Optional) closure for converting `items` entries to a Buffer instance
@return array
@throws \RuntimeException On unknown value type (cannot be converted to Buffer) | [
"Buffer",
"::",
"sort",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L586-L609 |
evias/nem-php | src/Core/Buffer.php | Buffer.hash | public function hash($algorithm = "sha512")
{
if (! in_array($algorithm, hash_algos())) {
throw new InvalidArgumentException("Hash algorithm '" . $algorithm . "' not supported.");
}
$byteSize = false !== strpos($algorithm, "512") ? 64 : 32;
if ($algorithm === "sha1") $byteSize = 20;
$hashed = new Buffer(hash($algorithm, $this->getBinary(), true), $byteSize);
//$hashed = Buffer::fromHex(hash($algorithm, $this->getHex()));
return $hashed->getHex();
} | php | public function hash($algorithm = "sha512")
{
if (! in_array($algorithm, hash_algos())) {
throw new InvalidArgumentException("Hash algorithm '" . $algorithm . "' not supported.");
}
$byteSize = false !== strpos($algorithm, "512") ? 64 : 32;
if ($algorithm === "sha1") $byteSize = 20;
$hashed = new Buffer(hash($algorithm, $this->getBinary(), true), $byteSize);
//$hashed = Buffer::fromHex(hash($algorithm, $this->getHex()));
return $hashed->getHex();
} | [
"public",
"function",
"hash",
"(",
"$",
"algorithm",
"=",
"\"sha512\"",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"algorithm",
",",
"hash_algos",
"(",
")",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Hash algorithm '\"",
".",
"... | Buffer::hash()
Create HMAC out of buffer using said `algorithm`.
Currently supported algorithm include, but are not limited to:
- sha256 (32 bytes)
- sha512 (64 bytes)
- sha1 (20 bytes)
@param string $algorithm Hash algorithm (Example: sha512)
@return \NEM\Core\Buffer | [
"Buffer",
"::",
"hash",
"()"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L625-L637 |
evias/nem-php | src/Core/Buffer.php | Buffer.clampBits | static public function clampBits($unsafeSecret, $bytes = 64)
{
if ($unsafeSecret instanceof Buffer) {
// copy-construct to avoid malformed and wrong size
$toBuffer = new Buffer($unsafeSecret->getBinary(), $bytes);
}
elseif (! ctype_xdigit($unsafeSecret)) {
// build from binary
$toBuffer = new Buffer($unsafeSecret, $bytes);
}
else {
$toBuffer = Buffer::fromHex($unsafeSecret, $bytes);
}
// clamping bits
$clampSecret = $toBuffer->toUInt8();
$clampSecret[0] &= 0xf8; // 248
$clampSecret[31] &= 0x7f; // 127
$clampSecret[31] |= 0x40; // 64
// build Buffer object from UInt8 and return byte-level representation
$encoder = new Encoder;
$safeSecret = $encoder->ua2bin($clampSecret);
return $safeSecret;
} | php | static public function clampBits($unsafeSecret, $bytes = 64)
{
if ($unsafeSecret instanceof Buffer) {
// copy-construct to avoid malformed and wrong size
$toBuffer = new Buffer($unsafeSecret->getBinary(), $bytes);
}
elseif (! ctype_xdigit($unsafeSecret)) {
// build from binary
$toBuffer = new Buffer($unsafeSecret, $bytes);
}
else {
$toBuffer = Buffer::fromHex($unsafeSecret, $bytes);
}
// clamping bits
$clampSecret = $toBuffer->toUInt8();
$clampSecret[0] &= 0xf8; // 248
$clampSecret[31] &= 0x7f; // 127
$clampSecret[31] |= 0x40; // 64
// build Buffer object from UInt8 and return byte-level representation
$encoder = new Encoder;
$safeSecret = $encoder->ua2bin($clampSecret);
return $safeSecret;
} | [
"static",
"public",
"function",
"clampBits",
"(",
"$",
"unsafeSecret",
",",
"$",
"bytes",
"=",
"64",
")",
"{",
"if",
"(",
"$",
"unsafeSecret",
"instanceof",
"Buffer",
")",
"{",
"// copy-construct to avoid malformed and wrong size",
"$",
"toBuffer",
"=",
"new",
"... | Convert 64 Bytes Keccak SHA3-512 Hashes into a Secret Key.
@param string $unsafeSecret A 64 bytes (512 bits) Keccak hash produced from a KeyPair's Secret Key.
@return string Byte-level representation of the Secret Key. | [
"Convert",
"64",
"Bytes",
"Keccak",
"SHA3",
"-",
"512",
"Hashes",
"into",
"a",
"Secret",
"Key",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Buffer.php#L645-L669 |
evias/nem-php | src/Infrastructure/Mosaic.php | Mosaic.getMosaicDefinitionsPage | public function getMosaicDefinitionsPage($namespace, $id = null, $pageSize = null)
{
$params = ["namespace" => $namespace]
+ ($id !== null ? ["id" => $id] : [])
+ ($pageSize !== null ? ["pageSize" => $pageSize] : []);
$apiUrl = $this->getPath('definition/page', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createBaseCollection($object["data"]);
} | php | public function getMosaicDefinitionsPage($namespace, $id = null, $pageSize = null)
{
$params = ["namespace" => $namespace]
+ ($id !== null ? ["id" => $id] : [])
+ ($pageSize !== null ? ["pageSize" => $pageSize] : []);
$apiUrl = $this->getPath('definition/page', $params);
$response = $this->api->getJSON($apiUrl);
//XXX include Error checks
$object = json_decode($response, true);
return $this->createBaseCollection($object["data"]);
} | [
"public",
"function",
"getMosaicDefinitionsPage",
"(",
"$",
"namespace",
",",
"$",
"id",
"=",
"null",
",",
"$",
"pageSize",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"\"namespace\"",
"=>",
"$",
"namespace",
"]",
"+",
"(",
"$",
"id",
"!==",
"null"... | XXX
@param namespace
@param id - The topmost mosaic definition database id up to which root mosaic definitions are returned.
The parameter is optional. If not supplied the most recent mosaic definitiona are returned.
@param pageSize - The number of mosaic definition objects to be returned for each request. The parameter is
optional. The default value is 25, the minimum value is 5 and hte maximum value is 100. | [
"XXX"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Mosaic.php#L38-L50 |
evias/nem-php | src/Infrastructure/Network.php | Network.fromAddress | static public function fromAddress($address)
{
if ($address instanceof Address) {
$addr = $address->toClean();
$prefix = substr($addr, 0, 1);
}
elseif (is_string($address)) {
$prefix = substr($address, 0, 1);
}
else {
throw new \InvalidArgumentException("Could not identify address format: " . var_export($address, true));
}
foreach (self::$networkInfos as $name => $spec) {
$netChar = $spec['char'];
if ($prefix == $netChar)
return $spec["id"];
}
throw new \InvalidArgumentException("Could not identify network from provided address: " . var_export($address, true));
} | php | static public function fromAddress($address)
{
if ($address instanceof Address) {
$addr = $address->toClean();
$prefix = substr($addr, 0, 1);
}
elseif (is_string($address)) {
$prefix = substr($address, 0, 1);
}
else {
throw new \InvalidArgumentException("Could not identify address format: " . var_export($address, true));
}
foreach (self::$networkInfos as $name => $spec) {
$netChar = $spec['char'];
if ($prefix == $netChar)
return $spec["id"];
}
throw new \InvalidArgumentException("Could not identify network from provided address: " . var_export($address, true));
} | [
"static",
"public",
"function",
"fromAddress",
"(",
"$",
"address",
")",
"{",
"if",
"(",
"$",
"address",
"instanceof",
"Address",
")",
"{",
"$",
"addr",
"=",
"$",
"address",
"->",
"toClean",
"(",
")",
";",
"$",
"prefix",
"=",
"substr",
"(",
"$",
"add... | Load a NetworkInfo object from an `address`.
@param string|\NEM\Models\Address $address
@return \NEM\Models\Model
@throws \InvalidArgumentException On invalid address format or unrecognized address first character. | [
"Load",
"a",
"NetworkInfo",
"object",
"from",
"an",
"address",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Network.php#L69-L90 |
evias/nem-php | src/Infrastructure/Network.php | Network.getPrefixFromId | static public function getPrefixFromId($networkId)
{
foreach (self::$networkInfos as $name => $spec) {
if ($networkId === $spec['id'])
return $spec['hex'];
}
throw new NISInvalidNetworkId("Network Id '" . $networkId . "' is invalid.");
} | php | static public function getPrefixFromId($networkId)
{
foreach (self::$networkInfos as $name => $spec) {
if ($networkId === $spec['id'])
return $spec['hex'];
}
throw new NISInvalidNetworkId("Network Id '" . $networkId . "' is invalid.");
} | [
"static",
"public",
"function",
"getPrefixFromId",
"(",
"$",
"networkId",
")",
"{",
"foreach",
"(",
"self",
"::",
"$",
"networkInfos",
"as",
"$",
"name",
"=>",
"$",
"spec",
")",
"{",
"if",
"(",
"$",
"networkId",
"===",
"$",
"spec",
"[",
"'id'",
"]",
... | Helper to get a network address prefix hexadecimal representation
from a network id.
@param integer $networkId
@return string | [
"Helper",
"to",
"get",
"a",
"network",
"address",
"prefix",
"hexadecimal",
"representation",
"from",
"a",
"network",
"id",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Network.php#L99-L107 |
evias/nem-php | src/Infrastructure/Network.php | Network.getFromId | static public function getFromId($networkId, $field = "name")
{
foreach (self::$networkInfos as $name => $spec) {
if ($spec["id"] !== (int) $networkId) continue;
if ($field === "name")
return $name;
elseif (in_array($field, array_keys($spec)))
return $spec[$field];
else
// Field not recognized
return null;
}
// Network ID not recognized
return null;
} | php | static public function getFromId($networkId, $field = "name")
{
foreach (self::$networkInfos as $name => $spec) {
if ($spec["id"] !== (int) $networkId) continue;
if ($field === "name")
return $name;
elseif (in_array($field, array_keys($spec)))
return $spec[$field];
else
// Field not recognized
return null;
}
// Network ID not recognized
return null;
} | [
"static",
"public",
"function",
"getFromId",
"(",
"$",
"networkId",
",",
"$",
"field",
"=",
"\"name\"",
")",
"{",
"foreach",
"(",
"self",
"::",
"$",
"networkInfos",
"as",
"$",
"name",
"=>",
"$",
"spec",
")",
"{",
"if",
"(",
"$",
"spec",
"[",
"\"id\""... | Helper to load a network field from a given `networkId`.
@param integer $networkId
@param string $field Defaults to "name".
@return null|string|integer | [
"Helper",
"to",
"load",
"a",
"network",
"field",
"from",
"a",
"given",
"networkId",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Network.php#L116-L132 |
evias/nem-php | src/Models/MosaicDefinitions.php | MosaicDefinitions.create | static public function create(MosaicAttachments $mosaics = null, $networkId = 104)
{
if (! self::$definitions) {
self::$definitions = new static([
Registry::getDefinition("nem:xem")
]);
}
if ($mosaics === null) {
return self::$definitions; // only contains nem:xem
}
$object = new static;
// for each attached mosaic, we need the mosaic definition
foreach ($mosaics as $attachment) {
$mosaicId = is_array($attachment) ? $attachment["mosaicId"] : $attachment->mosaicId();
$mosaic = $object->prepareMosaic($mosaicId);
$definition = self::$definitions->getDefinition($mosaic);
if (false !== $definition) {
// definition found for current attached mosaic
continue;
}
// try to use Registry
$definition = Registry::getDefinition($mosaic);
if (false !== $definition) {
// mosaic definition *morphed* with Registry.
self::$definitions->push($definition);
continue;
}
// need network fetch
// all definitions fetched will be stored in `self::$definitions`
$definition = self::fetch($mosaic, $networkId);
if (false === $definition) {
throw new \InvalidArgumentException("Mosaic '" . $mosaic->getFQN() . "' does not exist on network: " . $networkId);
}
}
return self::$definitions;
} | php | static public function create(MosaicAttachments $mosaics = null, $networkId = 104)
{
if (! self::$definitions) {
self::$definitions = new static([
Registry::getDefinition("nem:xem")
]);
}
if ($mosaics === null) {
return self::$definitions; // only contains nem:xem
}
$object = new static;
// for each attached mosaic, we need the mosaic definition
foreach ($mosaics as $attachment) {
$mosaicId = is_array($attachment) ? $attachment["mosaicId"] : $attachment->mosaicId();
$mosaic = $object->prepareMosaic($mosaicId);
$definition = self::$definitions->getDefinition($mosaic);
if (false !== $definition) {
// definition found for current attached mosaic
continue;
}
// try to use Registry
$definition = Registry::getDefinition($mosaic);
if (false !== $definition) {
// mosaic definition *morphed* with Registry.
self::$definitions->push($definition);
continue;
}
// need network fetch
// all definitions fetched will be stored in `self::$definitions`
$definition = self::fetch($mosaic, $networkId);
if (false === $definition) {
throw new \InvalidArgumentException("Mosaic '" . $mosaic->getFQN() . "' does not exist on network: " . $networkId);
}
}
return self::$definitions;
} | [
"static",
"public",
"function",
"create",
"(",
"MosaicAttachments",
"$",
"mosaics",
"=",
"null",
",",
"$",
"networkId",
"=",
"104",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"definitions",
")",
"{",
"self",
"::",
"$",
"definitions",
"=",
"new",
"sta... | Class method to create a MosaicDefinitions *array*.
This array will *always* contain MosaicDefinition objects
for the mosaics that are pre-configured.
@return \NEM\Models\MosaicDefinitions | [
"Class",
"method",
"to",
"create",
"a",
"MosaicDefinitions",
"*",
"array",
"*",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicDefinitions.php#L50-L95 |
evias/nem-php | src/Models/MosaicDefinitions.php | MosaicDefinitions.getDefinition | public function getDefinition($mosaic)
{
if (! $this->count()) {
return false;
}
$mosaic = $this->prepareMosaic($mosaic);
foreach ($this->all() as $definition) {
if ($mosaic->getFQN() != $definition->id()->getFQN()) {
continue;
}
return $definition;
}
return false;
} | php | public function getDefinition($mosaic)
{
if (! $this->count()) {
return false;
}
$mosaic = $this->prepareMosaic($mosaic);
foreach ($this->all() as $definition) {
if ($mosaic->getFQN() != $definition->id()->getFQN()) {
continue;
}
return $definition;
}
return false;
} | [
"public",
"function",
"getDefinition",
"(",
"$",
"mosaic",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"count",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"mosaic",
"=",
"$",
"this",
"->",
"prepareMosaic",
"(",
"$",
"mosaic",
")",
";",
... | This method will find a said `MosaicDefinition` for the
given `mosaic` in the current definitions collection.
@param string|\NEM\Models\Mosaic $mosaic
@return false|\NEM\Models\MosaicDefinition | [
"This",
"method",
"will",
"find",
"a",
"said",
"MosaicDefinition",
"for",
"the",
"given",
"mosaic",
"in",
"the",
"current",
"definitions",
"collection",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicDefinitions.php#L152-L168 |
evias/nem-php | src/Models/MosaicDefinitions.php | MosaicDefinitions.prepareMosaic | protected function prepareMosaic($mosaic)
{
if ($mosaic instanceof Mosaic) {
return $mosaic;
}
elseif (is_string($mosaic)) {
return Mosaic::create($mosaic);
}
elseif (is_array($mosaic)) {
$fqmn = $mosaic["namespaceId"] . ":" . $mosaic["name"];
return Mosaic::create($fqmn);
}
throw new InvalidArgumentException("Unsupported mosaic argument type provided to \\NEM\\Models\\MosaicDefinitions: ", var_export($mosaic));
} | php | protected function prepareMosaic($mosaic)
{
if ($mosaic instanceof Mosaic) {
return $mosaic;
}
elseif (is_string($mosaic)) {
return Mosaic::create($mosaic);
}
elseif (is_array($mosaic)) {
$fqmn = $mosaic["namespaceId"] . ":" . $mosaic["name"];
return Mosaic::create($fqmn);
}
throw new InvalidArgumentException("Unsupported mosaic argument type provided to \\NEM\\Models\\MosaicDefinitions: ", var_export($mosaic));
} | [
"protected",
"function",
"prepareMosaic",
"(",
"$",
"mosaic",
")",
"{",
"if",
"(",
"$",
"mosaic",
"instanceof",
"Mosaic",
")",
"{",
"return",
"$",
"mosaic",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"mosaic",
")",
")",
"{",
"return",
"Mosaic",
":... | Internal helper to wrap a mosaic FQN into a
\NEM\Models\Mosaic instance.
@param string|\NEM\Models\Mosaic $mosaic
@return \NEM\Models\Mosaic | [
"Internal",
"helper",
"to",
"wrap",
"a",
"mosaic",
"FQN",
"into",
"a",
"\\",
"NEM",
"\\",
"Models",
"\\",
"Mosaic",
"instance",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicDefinitions.php#L177-L191 |
evias/nem-php | src/Models/MosaicProperty.php | MosaicProperty.toDTO | public function toDTO($filterByKey = null)
{
$value = (string) $this->value;
if (in_array($this->name, ["supplyMutable", "transferable"])) {
$value = ($value !== "false" && (bool) $value) ? "true" : "false";
}
elseif (empty($value) || 0 > (int) $value) {
$value = "0";
}
return [
"name" => $this->name,
"value" => $value,
];
} | php | public function toDTO($filterByKey = null)
{
$value = (string) $this->value;
if (in_array($this->name, ["supplyMutable", "transferable"])) {
$value = ($value !== "false" && (bool) $value) ? "true" : "false";
}
elseif (empty($value) || 0 > (int) $value) {
$value = "0";
}
return [
"name" => $this->name,
"value" => $value,
];
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"$",
"value",
"=",
"(",
"string",
")",
"$",
"this",
"->",
"value",
";",
"if",
"(",
"in_array",
"(",
"$",
"this",
"->",
"name",
",",
"[",
"\"supplyMutable\"",
",",
"\"trans... | Address DTO automatically cleans address representation.
@return array Associative array with key `address` containing a NIS *compliable* address representation. | [
"Address",
"DTO",
"automatically",
"cleans",
"address",
"representation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicProperty.php#L49-L63 |
evias/nem-php | src/Models/MosaicProperty.php | MosaicProperty.serialize | public function serialize($parameters = null)
{
$nisData = $this->toDTO();
// shortcuts
$serializer = $this->getSerializer();
$serializedName = $serializer->serializeString($nisData["name"]);
$serializedValue = $serializer->serializeString($nisData["value"]);
return $serializer->aggregate($serializedName, $serializedValue);
} | php | public function serialize($parameters = null)
{
$nisData = $this->toDTO();
// shortcuts
$serializer = $this->getSerializer();
$serializedName = $serializer->serializeString($nisData["name"]);
$serializedValue = $serializer->serializeString($nisData["value"]);
return $serializer->aggregate($serializedName, $serializedValue);
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
")",
";",
"// shortcuts",
"$",
"serializer",
"=",
"$",
"this",
"->",
"getSerializer",
"(",
")",
";",
"$",
"serialize... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *Mosaic Definition Properties* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"Mosaic",
"Definition",
"Properties",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicProperty.php#L73-L83 |
evias/nem-php | src/Models/Transaction/Signature.php | Signature.toDTO | public function toDTO($filterByKey = null)
{
$baseMeta = $this->meta();
$baseEntity = [
"timeStamp" => $this->timeStamp()->toDTO(),
"fee" => $this->fee()->toMicro(),
"otherHash" => [
"data" => $this->getAttribute("otherHash"),
],
"otherAccount" => $this->otherAccount()->address()->toClean(),
// transaction type specialization
"type" => TransactionType::MULTISIG_SIGNATURE,
"version" => $this->getAttribute("version") ?: Transaction::VERSION_1,
];
// extend entity data in sub class
// @see \NEM\Models\Transaction\MosaicTransfer
$entity = array_merge($baseEntity, $this->extend());
// deadline set to +1 hour if none set
$deadline = $this->getAttribute("deadline");
if (! $deadline || $deadline <= 0) {
$txTime = $entity["timeStamp"];
$deadline = $txTime + 3600;
$this->setAttribute("deadline", $deadline);
}
// do we have optional fields
$optionals = ["signer", "signature"];
foreach ($optionals as $field) {
$data = $this->getAttribute($field);
if (null !== $data) {
$entity[$field] = $data;
}
}
// push validated input
$entity["deadline"] = $deadline;
return $entity;
} | php | public function toDTO($filterByKey = null)
{
$baseMeta = $this->meta();
$baseEntity = [
"timeStamp" => $this->timeStamp()->toDTO(),
"fee" => $this->fee()->toMicro(),
"otherHash" => [
"data" => $this->getAttribute("otherHash"),
],
"otherAccount" => $this->otherAccount()->address()->toClean(),
// transaction type specialization
"type" => TransactionType::MULTISIG_SIGNATURE,
"version" => $this->getAttribute("version") ?: Transaction::VERSION_1,
];
// extend entity data in sub class
// @see \NEM\Models\Transaction\MosaicTransfer
$entity = array_merge($baseEntity, $this->extend());
// deadline set to +1 hour if none set
$deadline = $this->getAttribute("deadline");
if (! $deadline || $deadline <= 0) {
$txTime = $entity["timeStamp"];
$deadline = $txTime + 3600;
$this->setAttribute("deadline", $deadline);
}
// do we have optional fields
$optionals = ["signer", "signature"];
foreach ($optionals as $field) {
$data = $this->getAttribute($field);
if (null !== $data) {
$entity[$field] = $data;
}
}
// push validated input
$entity["deadline"] = $deadline;
return $entity;
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"$",
"baseMeta",
"=",
"$",
"this",
"->",
"meta",
"(",
")",
";",
"$",
"baseEntity",
"=",
"[",
"\"timeStamp\"",
"=>",
"$",
"this",
"->",
"timeStamp",
"(",
")",
"->",
"toDTO"... | Overload of the toDTO() logic to skip "meta" and "transaction"
sub-dto pairing.
@return array Associative array containing a NIS *compliable* account representation. | [
"Overload",
"of",
"the",
"toDTO",
"()",
"logic",
"to",
"skip",
"meta",
"and",
"transaction",
"sub",
"-",
"dto",
"pairing",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/Signature.php#L55-L95 |
evias/nem-php | src/Models/Transaction/Signature.php | Signature.serialize | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->toDTO();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
$binHash = hex2bin($nisData["otherHash"]["data"]);
// serialize specialized fields
$uint8_hashLen = $serializer->serializeInt(4 + strlen($binHash));
$uint8_hash = $serializer->serializeString($binHash);
$uint8_acct = $serializer->serializeString($nisData["otherAccount"]);
// concatenate the UInt8 representation
$output = array_merge(
$uint8_hashLen,
$uint8_hash,
$uint8_acct);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | php | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->toDTO();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
$binHash = hex2bin($nisData["otherHash"]["data"]);
// serialize specialized fields
$uint8_hashLen = $serializer->serializeInt(4 + strlen($binHash));
$uint8_hash = $serializer->serializeString($binHash);
$uint8_acct = $serializer->serializeString($nisData["otherAccount"]);
// concatenate the UInt8 representation
$output = array_merge(
$uint8_hashLen,
$uint8_hash,
$uint8_acct);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
")",
";",
"// shortcuts",
"$",
... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *Signature transaction* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"Signature",
"transaction",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/Signature.php#L105-L128 |
evias/nem-php | src/Models/Message.php | Message.toDTO | public function toDTO($filterByKey = null)
{
// CryptoHelper will store a KeyPair when necessary
// to allow encryption (needs private + public keys)
$helper = new CryptoHelper();
$plain = $this->getPlain();
if (empty($plain) || !isset($this->type))
$this->type = Message::TYPE_SIMPLE;
if ($this->type == Message::TYPE_HEX) {
if (! ctype_xdigit($plain)) {
throw new RuntimeException("Invalid hexadecimal representation. Use Message::TYPE_SIMPLE instead of Message::TYPE_HEX.");
}
// hexadecimal message content
$payload = "fe" . $plain;
$this->type = Message::TYPE_SIMPLE;
}
elseif ($this->type == Message::TYPE_SIMPLE) {
// simple message, unencrypted
if (empty($plain)) {
$plain = $this->toPlain();
$payload = $this->payload;
}
else {
$payload = $this->toHex();
}
}
elseif ($this->type == Message::TYPE_ENCRYPTED) {
// encrypted message
$payload = $helper->encrypt($plain);
//XXX HW Trezor include "publicKey" to DTO.
}
return [
"payload" => $payload,
"type" => $this->type,
];
} | php | public function toDTO($filterByKey = null)
{
// CryptoHelper will store a KeyPair when necessary
// to allow encryption (needs private + public keys)
$helper = new CryptoHelper();
$plain = $this->getPlain();
if (empty($plain) || !isset($this->type))
$this->type = Message::TYPE_SIMPLE;
if ($this->type == Message::TYPE_HEX) {
if (! ctype_xdigit($plain)) {
throw new RuntimeException("Invalid hexadecimal representation. Use Message::TYPE_SIMPLE instead of Message::TYPE_HEX.");
}
// hexadecimal message content
$payload = "fe" . $plain;
$this->type = Message::TYPE_SIMPLE;
}
elseif ($this->type == Message::TYPE_SIMPLE) {
// simple message, unencrypted
if (empty($plain)) {
$plain = $this->toPlain();
$payload = $this->payload;
}
else {
$payload = $this->toHex();
}
}
elseif ($this->type == Message::TYPE_ENCRYPTED) {
// encrypted message
$payload = $helper->encrypt($plain);
//XXX HW Trezor include "publicKey" to DTO.
}
return [
"payload" => $payload,
"type" => $this->type,
];
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"// CryptoHelper will store a KeyPair when necessary",
"// to allow encryption (needs private + public keys)",
"$",
"helper",
"=",
"new",
"CryptoHelper",
"(",
")",
";",
"$",
"plain",
"=",
"$"... | Account DTO represents NIS API's [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair).
@see [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair)
@return array Associative array containing a NIS *compliable* account representation. | [
"Account",
"DTO",
"represents",
"NIS",
"API",
"s",
"[",
"AccountMetaDataPair",
"]",
"(",
"https",
":",
"//",
"bob",
".",
"nem",
".",
"ninja",
"/",
"docs",
"/",
"#accountMetaDataPair",
")",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Message.php#L72-L112 |
evias/nem-php | src/Models/Message.php | Message.toHex | public function toHex($prefixHexContent = false)
{
$chars = $this->getPlain();
if ($prefixHexContent && ctype_xdigit($chars)) {
return "fe" . $chars;
}
$payload = "";
for ($c = 0, $cnt = strlen($chars); $c < $cnt; $c++ ) {
$decimal = ord($chars[$c]);
$hexCode = dechex($decimal);
// payload is built of *hexits*
$payload .= str_pad($hexCode, 2, "0", STR_PAD_LEFT);
}
$this->payload = strtolower($payload);
return $this->payload;
} | php | public function toHex($prefixHexContent = false)
{
$chars = $this->getPlain();
if ($prefixHexContent && ctype_xdigit($chars)) {
return "fe" . $chars;
}
$payload = "";
for ($c = 0, $cnt = strlen($chars); $c < $cnt; $c++ ) {
$decimal = ord($chars[$c]);
$hexCode = dechex($decimal);
// payload is built of *hexits*
$payload .= str_pad($hexCode, 2, "0", STR_PAD_LEFT);
}
$this->payload = strtolower($payload);
return $this->payload;
} | [
"public",
"function",
"toHex",
"(",
"$",
"prefixHexContent",
"=",
"false",
")",
"{",
"$",
"chars",
"=",
"$",
"this",
"->",
"getPlain",
"(",
")",
";",
"if",
"(",
"$",
"prefixHexContent",
"&&",
"ctype_xdigit",
"(",
"$",
"chars",
")",
")",
"{",
"return",
... | Helper to retrieve the hexadecimal representation of a message.
@return string | [
"Helper",
"to",
"retrieve",
"the",
"hexadecimal",
"representation",
"of",
"a",
"message",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Message.php#L119-L137 |
evias/nem-php | src/Models/Message.php | Message.toPlain | public function toPlain($hex = null)
{
if (empty($this->payload) && empty($hex))
return "";
$plain = "";
$payload = $hex ?: $this->payload;
for ($c = 0, $cnt = strlen($payload); $c < $cnt; $c += 2) {
$hex = substr($payload, $c, 2);
$decimal = hexdec($hex);
$plain .= chr($decimal);
}
return ($this->plain = $plain);
} | php | public function toPlain($hex = null)
{
if (empty($this->payload) && empty($hex))
return "";
$plain = "";
$payload = $hex ?: $this->payload;
for ($c = 0, $cnt = strlen($payload); $c < $cnt; $c += 2) {
$hex = substr($payload, $c, 2);
$decimal = hexdec($hex);
$plain .= chr($decimal);
}
return ($this->plain = $plain);
} | [
"public",
"function",
"toPlain",
"(",
"$",
"hex",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"payload",
")",
"&&",
"empty",
"(",
"$",
"hex",
")",
")",
"return",
"\"\"",
";",
"$",
"plain",
"=",
"\"\"",
";",
"$",
"payload",
... | Helper to retrieve the UTF8 representation of a message
payload (hexadecimal representation).
@return string | [
"Helper",
"to",
"retrieve",
"the",
"UTF8",
"representation",
"of",
"a",
"message",
"payload",
"(",
"hexadecimal",
"representation",
")",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Message.php#L145-L159 |
evias/nem-php | src/Core/Encryption.php | Encryption.prepareInputBuffer | protected static function prepareInputBuffer($data)
{
if ($data instanceof Buffer) {
return $data;
}
elseif (is_string($data) && ctype_xdigit($data)) {
return Buffer::fromHex($data);
}
elseif (is_string($data)) {
return new Buffer($data);
}
elseif (is_array($data)) {
// Uint8 provided (serialized data)
return Buffer::fromUInt8($data);
}
return new Buffer((string) $data);
} | php | protected static function prepareInputBuffer($data)
{
if ($data instanceof Buffer) {
return $data;
}
elseif (is_string($data) && ctype_xdigit($data)) {
return Buffer::fromHex($data);
}
elseif (is_string($data)) {
return new Buffer($data);
}
elseif (is_array($data)) {
// Uint8 provided (serialized data)
return Buffer::fromUInt8($data);
}
return new Buffer((string) $data);
} | [
"protected",
"static",
"function",
"prepareInputBuffer",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
"instanceof",
"Buffer",
")",
"{",
"return",
"$",
"data",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"data",
")",
"&&",
"ctype_xdigit",
"(",
... | Helper to prepare a `data` attribute into a \NEM\Core\Buffer
object for easier internal data representations.
@param null|string|\NEM\Core\Buffer $data The data that needs to be added to the returned Buffer.
@return \NEM\Core\Buffer | [
"Helper",
"to",
"prepare",
"a",
"data",
"attribute",
"into",
"a",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Buffer",
"object",
"for",
"easier",
"internal",
"data",
"representations",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L62-L79 |
evias/nem-php | src/Core/Encryption.php | Encryption.derive | public static function derive($algorithm, $password, $salt, $count = 6000, $keyLength = 64) // 6000=NanoWallet, 64=512bits
{
// shortcuts + use Buffer always
$password = self::prepareInputBuffer($password);
$salt = self::prepareInputBuffer($salt);
if ($keyLength < 0) {
throw new InvalidArgumentException('Cannot have a negative key-length for PBKDF2');
}
$algorithm = strtolower($algorithm);
if (!in_array($algorithm, hash_algos(), true)) {
throw new RuntimeException('PBKDF2 ERROR: Invalid hash algorithm');
}
if ($count <= 0 || $keyLength <= 0) {
throw new InvalidArgumentException('PBKDF2 ERROR: Invalid parameters.');
}
// Get binary data of derived key and wrap in Buffer
return new Buffer(\hash_pbkdf2($algorithm, $password->getBinary(), $salt->getBinary(), $count, $keyLength, true), $keyLength);
} | php | public static function derive($algorithm, $password, $salt, $count = 6000, $keyLength = 64) // 6000=NanoWallet, 64=512bits
{
// shortcuts + use Buffer always
$password = self::prepareInputBuffer($password);
$salt = self::prepareInputBuffer($salt);
if ($keyLength < 0) {
throw new InvalidArgumentException('Cannot have a negative key-length for PBKDF2');
}
$algorithm = strtolower($algorithm);
if (!in_array($algorithm, hash_algos(), true)) {
throw new RuntimeException('PBKDF2 ERROR: Invalid hash algorithm');
}
if ($count <= 0 || $keyLength <= 0) {
throw new InvalidArgumentException('PBKDF2 ERROR: Invalid parameters.');
}
// Get binary data of derived key and wrap in Buffer
return new Buffer(\hash_pbkdf2($algorithm, $password->getBinary(), $salt->getBinary(), $count, $keyLength, true), $keyLength);
} | [
"public",
"static",
"function",
"derive",
"(",
"$",
"algorithm",
",",
"$",
"password",
",",
"$",
"salt",
",",
"$",
"count",
"=",
"6000",
",",
"$",
"keyLength",
"=",
"64",
")",
"// 6000=NanoWallet, 64=512bits",
"{",
"// shortcuts + use Buffer always",
"$",
"pas... | PBKDF2 : Password Based Key Derivation Function
For the name of selected hashing algorithms (i.e. md5,
sha256, haval160,4, etc..), see hash_algos() for a list
of supported algorithms.
This method can be used when PBKDF2 must be used, typically with
NEM this is used to derive a Private key off a Password.
@param string $algorithm Which hash algorithm to use for key derivation.
@param string|NEM\Core\Buffer $password Password for key derivation as *Buffer*.
@param string|NEM\Core\Buffer $salt Salt for key derivation as *Buffer*.
@param integer $count Count of Derivation iterations.
@param integer $keyLength Length of produced Key (count of Bytes).
@return NEM\Core\Buffer
@throws RuntimeException On invalid hash algorithm (maybe missing php extension)
@throws InvalidArgumentException On negative *$keyLength* argument.
@throws InvalidArgumentException On invalid derivation iterations *$count* or invalid *$keyLength* arguments. | [
"PBKDF2",
":",
"Password",
"Based",
"Key",
"Derivation",
"Function"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L102-L124 |
evias/nem-php | src/Core/Encryption.php | Encryption.hash | public static function hash($algo, $data, $returnRaw = false)
{
// shortcuts + use Buffer always
$data = self::prepareInputBuffer($data);
if (in_array($algo, hash_algos())) {
// use PHP hash()
$hash = hash($algo, $data->getBinary(), true);
}
elseif (strpos(strtolower($algo), "keccak-") !== false) {
// use Keccak instead of PHP hash()
$hash = KeccakHasher::hash($algo, $data->getBinary(), true);
}
else {
throw new RuntimeException("Unsupported hash algorithm '" . $algo . "'.");
}
if ((bool) $returnRaw) {
return $hash;
}
return new Buffer($hash);
} | php | public static function hash($algo, $data, $returnRaw = false)
{
// shortcuts + use Buffer always
$data = self::prepareInputBuffer($data);
if (in_array($algo, hash_algos())) {
// use PHP hash()
$hash = hash($algo, $data->getBinary(), true);
}
elseif (strpos(strtolower($algo), "keccak-") !== false) {
// use Keccak instead of PHP hash()
$hash = KeccakHasher::hash($algo, $data->getBinary(), true);
}
else {
throw new RuntimeException("Unsupported hash algorithm '" . $algo . "'.");
}
if ((bool) $returnRaw) {
return $hash;
}
return new Buffer($hash);
} | [
"public",
"static",
"function",
"hash",
"(",
"$",
"algo",
",",
"$",
"data",
",",
"$",
"returnRaw",
"=",
"false",
")",
"{",
"// shortcuts + use Buffer always",
"$",
"data",
"=",
"self",
"::",
"prepareInputBuffer",
"(",
"$",
"data",
")",
";",
"if",
"(",
"i... | Helper to hash the provided buffer `data`'s content
with algorithm `algo`.
The hash algorithm can contain `keccak-256` for example.
@param string $algo
@param string|\NEM\Core\Buffer $data
@param boolean $returnRaw
@return \NEM\Core\Buffer | [
"Helper",
"to",
"hash",
"the",
"provided",
"buffer",
"data",
"s",
"content",
"with",
"algorithm",
"algo",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L137-L159 |
evias/nem-php | src/Core/Encryption.php | Encryption.hash_init | public static function hash_init($algorithm)
{
if (in_array($algorithm, hash_algos())) {
// use PHP hash()
$res = hash_init($algorithm);
}
else {
throw new RuntimeException("Unsupported hash algorithm '" . $algo . "'.");
}
//XXX should return Hasher class to keep track of key size
return $res;
} | php | public static function hash_init($algorithm)
{
if (in_array($algorithm, hash_algos())) {
// use PHP hash()
$res = hash_init($algorithm);
}
else {
throw new RuntimeException("Unsupported hash algorithm '" . $algo . "'.");
}
//XXX should return Hasher class to keep track of key size
return $res;
} | [
"public",
"static",
"function",
"hash_init",
"(",
"$",
"algorithm",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"algorithm",
",",
"hash_algos",
"(",
")",
")",
")",
"{",
"// use PHP hash()",
"$",
"res",
"=",
"hash_init",
"(",
"$",
"algorithm",
")",
";",
... | Helper to initialize *a incremental Hasher* for the hashing
algorithm `algorithm`.
This method will return a Resource that can be passed to the
hash_update() method.
@param string $algorithm
@return resource|\NEM\Core\KeccakSponge | [
"Helper",
"to",
"initialize",
"*",
"a",
"incremental",
"Hasher",
"*",
"for",
"the",
"hashing",
"algorithm",
"algorithm",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L171-L183 |
evias/nem-php | src/Core/Encryption.php | Encryption.hash_update | public static function hash_update($hasher, $data)
{
// use Buffer always
$data = self::prepareInputBuffer($data);
//XXX should use Hasher class to keep track of key size
return hash_update($hasher, $data->getBinary());
} | php | public static function hash_update($hasher, $data)
{
// use Buffer always
$data = self::prepareInputBuffer($data);
//XXX should use Hasher class to keep track of key size
return hash_update($hasher, $data->getBinary());
} | [
"public",
"static",
"function",
"hash_update",
"(",
"$",
"hasher",
",",
"$",
"data",
")",
"{",
"// use Buffer always",
"$",
"data",
"=",
"self",
"::",
"prepareInputBuffer",
"(",
"$",
"data",
")",
";",
"//XXX should use Hasher class to keep track of key size",
"retur... | Helper to update *a incremental Hasher* with some data.
This method will edit the Resource directly.
@param resource|KeccakSponge $hasher
@param string|\NEM\Core\Buffer $data
@return resource|\NEM\Core\KeccakSponge | [
"Helper",
"to",
"update",
"*",
"a",
"incremental",
"Hasher",
"*",
"with",
"some",
"data",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L194-L201 |
evias/nem-php | src/Core/Encryption.php | Encryption.hash_final | public static function hash_final($hasher, $returnRaw = false)
{
$hash = hash_final($hasher, true);
if ((bool) $returnRaw) {
return $hash;
}
//XXX should use Hasher class to keep track of key size
return new Buffer($hash);
} | php | public static function hash_final($hasher, $returnRaw = false)
{
$hash = hash_final($hasher, true);
if ((bool) $returnRaw) {
return $hash;
}
//XXX should use Hasher class to keep track of key size
return new Buffer($hash);
} | [
"public",
"static",
"function",
"hash_final",
"(",
"$",
"hasher",
",",
"$",
"returnRaw",
"=",
"false",
")",
"{",
"$",
"hash",
"=",
"hash_final",
"(",
"$",
"hasher",
",",
"true",
")",
";",
"if",
"(",
"(",
"bool",
")",
"$",
"returnRaw",
")",
"{",
"re... | Helper to finalize *a incremental Hasher*.
This will close the Input Phase of the incremental
hashing mechanism.
@param resource|KeccakSponge $hasher
@param bool $returnRaw
@return \NEM\Core\Buffer|string | [
"Helper",
"to",
"finalize",
"*",
"a",
"incremental",
"Hasher",
"*",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L213-L223 |
evias/nem-php | src/Core/Encryption.php | Encryption.hmac | public static function hmac($algo, $data, $salt)
{
// shortcuts + use Buffer always
$data = self::prepareInputBuffer($data);
$salt = self::prepareInputBuffer($salt);
return new Buffer(hash_hmac($algo, $data->getBinary(), $salt->getBinary(), true));
} | php | public static function hmac($algo, $data, $salt)
{
// shortcuts + use Buffer always
$data = self::prepareInputBuffer($data);
$salt = self::prepareInputBuffer($salt);
return new Buffer(hash_hmac($algo, $data->getBinary(), $salt->getBinary(), true));
} | [
"public",
"static",
"function",
"hmac",
"(",
"$",
"algo",
",",
"$",
"data",
",",
"$",
"salt",
")",
"{",
"// shortcuts + use Buffer always",
"$",
"data",
"=",
"self",
"::",
"prepareInputBuffer",
"(",
"$",
"data",
")",
";",
"$",
"salt",
"=",
"self",
"::",
... | HMAC : Hash based Message Authentication Code
A MAC authenticates a message. It is a signature based on a secret key (salt).
@param string $algorithm Which hash algorithm to use.
@param string|NEM\Core\Buffer $data
@param string|NEM\Core\Buffer $salt
@return NEM\Core\Buffer | [
"HMAC",
":",
"Hash",
"based",
"Message",
"Authentication",
"Code"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L235-L242 |
evias/nem-php | src/Core/Encryption.php | Encryption.checksum | public static function checksum($algo, $data, $checksumLen = 4)
{
// shortcuts + use Buffer always
$data = self::prepareInputBuffer($data);
$hash = self::hash($algo, $data, false)->getBinary();
$out = new Buffer(substr($hash, 0, $checksumLen), $checksumLen);
return $out;
} | php | public static function checksum($algo, $data, $checksumLen = 4)
{
// shortcuts + use Buffer always
$data = self::prepareInputBuffer($data);
$hash = self::hash($algo, $data, false)->getBinary();
$out = new Buffer(substr($hash, 0, $checksumLen), $checksumLen);
return $out;
} | [
"public",
"static",
"function",
"checksum",
"(",
"$",
"algo",
",",
"$",
"data",
",",
"$",
"checksumLen",
"=",
"4",
")",
"{",
"// shortcuts + use Buffer always",
"$",
"data",
"=",
"self",
"::",
"prepareInputBuffer",
"(",
"$",
"data",
")",
";",
"$",
"hash",
... | Generate a checksum of data buffer `data` and of length
`checksumLen`. Default length is 4 bytes.
@param string $algo
@param string|\NEM\Core\Buffer $data
@param integer $checksumLen
@return \NEM\Core\Buffer | [
"Generate",
"a",
"checksum",
"of",
"data",
"buffer",
"data",
"and",
"of",
"length",
"checksumLen",
".",
"Default",
"length",
"is",
"4",
"bytes",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L253-L260 |
evias/nem-php | src/Core/Encryption.php | Encryption.sign | public static function sign(KeyPair $keyPair, $data, $algorithm = "keccak-512")
{
// shortcuts + use Buffer always
$data = self::prepareInputBuffer($data);
// shortcuts
$secretKey = $keyPair->getSecretKey()->getBinary();
$publicKey = $keyPair->getPublicKey()->getBinary();
// use Buffer always
$data = self::prepareInputBuffer($data);
$message = $data->getBinary();
// step 1: crypto_hash_sha512(az, sk, 32);
$privHash = self::hash($algorithm, $keyPair->getSecretKey()->getBinary(), true);
// clamp bits for secret key + size secure
$safePriv = Buffer::clampBits($privHash, 64);
$bufferPriv = new Buffer($safePriv, 64);
// step 2: generate `r` for scalar multiplication
// `r = H(priv[32..64], data)`
$hashData = $bufferPriv->slice(32)->getBinary() . $data->getBinary();
$r = self::hash($algorithm, $hashData, true);
// step 3: generate encoded version of `r` for `s` creation
// `R = rB`
$r = Ed25519::sc_reduce($r);
$encodedR = Ed25519::ge_p3_tobytes(
Ed25519::ge_scalarmult_base($r)
);
// step 4: create `s` with: encodedR || public key || data
// `S = H(R,A,m)`
$hramData = $encodedR . $publicKey . $data->getBinary();
$hramHash = self::hash($algorithm, $hramData, true);
// step 5: safe secret generation for `encodedS` which is the
// HIGH part of the signature in scalar form.
// `S = H(R,A,m)a`
// `S = (r + H(R,A,m)a)`
$hram = Ed25519::sc_reduce($hramHash);
$az = $safePriv;
$encodedS = Ed25519::sc_muladd($hram, $az, $r);
// size secure encodedR and encodedS
$bufferR = new Buffer($encodedR, 32);
$bufferS = new Buffer($encodedS, 32);
// step 6: signature[0:63] = r[0:31] || s[0:31]
$sig = $bufferR->getBinary() . $bufferS->getBinary();
// size secure signature
$bufferSig = new Buffer($sig, 64);
// step 7: check that signature is canonical
// - s != 0
// - ed25519 reduced `s` should be identical to `s`.
// `S = (r + H(R,A,m)a) mod L`
// make sure `s` != 0
$sigZero = new Buffer(null, 32);
if ($encodedS === $sigZero->getBinary()) {
// re-issue signature because `s = 0`
return false;
}
// create 64-bytes size-secured Buffer.
$bufSignature = new Buffer($sig, 64);
return $bufSignature;
} | php | public static function sign(KeyPair $keyPair, $data, $algorithm = "keccak-512")
{
// shortcuts + use Buffer always
$data = self::prepareInputBuffer($data);
// shortcuts
$secretKey = $keyPair->getSecretKey()->getBinary();
$publicKey = $keyPair->getPublicKey()->getBinary();
// use Buffer always
$data = self::prepareInputBuffer($data);
$message = $data->getBinary();
// step 1: crypto_hash_sha512(az, sk, 32);
$privHash = self::hash($algorithm, $keyPair->getSecretKey()->getBinary(), true);
// clamp bits for secret key + size secure
$safePriv = Buffer::clampBits($privHash, 64);
$bufferPriv = new Buffer($safePriv, 64);
// step 2: generate `r` for scalar multiplication
// `r = H(priv[32..64], data)`
$hashData = $bufferPriv->slice(32)->getBinary() . $data->getBinary();
$r = self::hash($algorithm, $hashData, true);
// step 3: generate encoded version of `r` for `s` creation
// `R = rB`
$r = Ed25519::sc_reduce($r);
$encodedR = Ed25519::ge_p3_tobytes(
Ed25519::ge_scalarmult_base($r)
);
// step 4: create `s` with: encodedR || public key || data
// `S = H(R,A,m)`
$hramData = $encodedR . $publicKey . $data->getBinary();
$hramHash = self::hash($algorithm, $hramData, true);
// step 5: safe secret generation for `encodedS` which is the
// HIGH part of the signature in scalar form.
// `S = H(R,A,m)a`
// `S = (r + H(R,A,m)a)`
$hram = Ed25519::sc_reduce($hramHash);
$az = $safePriv;
$encodedS = Ed25519::sc_muladd($hram, $az, $r);
// size secure encodedR and encodedS
$bufferR = new Buffer($encodedR, 32);
$bufferS = new Buffer($encodedS, 32);
// step 6: signature[0:63] = r[0:31] || s[0:31]
$sig = $bufferR->getBinary() . $bufferS->getBinary();
// size secure signature
$bufferSig = new Buffer($sig, 64);
// step 7: check that signature is canonical
// - s != 0
// - ed25519 reduced `s` should be identical to `s`.
// `S = (r + H(R,A,m)a) mod L`
// make sure `s` != 0
$sigZero = new Buffer(null, 32);
if ($encodedS === $sigZero->getBinary()) {
// re-issue signature because `s = 0`
return false;
}
// create 64-bytes size-secured Buffer.
$bufSignature = new Buffer($sig, 64);
return $bufSignature;
} | [
"public",
"static",
"function",
"sign",
"(",
"KeyPair",
"$",
"keyPair",
",",
"$",
"data",
",",
"$",
"algorithm",
"=",
"\"keccak-512\"",
")",
"{",
"// shortcuts + use Buffer always",
"$",
"data",
"=",
"self",
"::",
"prepareInputBuffer",
"(",
"$",
"data",
")",
... | This method lets you sign `data` with a given `keyPair`.
The signature scheme of NEM can be divided in following steps:
- step 1: hash the keypair secret key (byte-level reversed private key) with keccak-512
- step 2: generate `r` with `r = H(priv[32..64], data)`
- step 3: generate encodedR with ED25519 scalar multiplication
- step 4: generate hram with `encodedR || public key || data`
- step 5: generate encodedS with ED25519 scalar mult addition
- step 6: concatenate encodedR and encodedS to obtain 64 bytes signature
- step 7: assert that the signature is canonical or return false
@param \NEM\Core\KeyPair $keyPair The KeyPair used for encryption.
@param string|\NEM\Core\Buffer $data The data that you want to sign.
@param string $algorithm The hash algorithm used for signature creation.
@return false|\NEM\Core\Buffer | [
"This",
"method",
"lets",
"you",
"sign",
"data",
"with",
"a",
"given",
"keyPair",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/Encryption.php#L280-L350 |
evias/nem-php | src/Handlers/GuzzleRequestHandler.php | GuzzleRequestHandler.promiseResponse | protected function promiseResponse(Client $client, Request $request, array $options = [])
{
// Guzzle Promises do not allow Asynchronous Requests Handling,
// I have implemented this feature only because it will
// allow a better Response Time for Paralell Request Handling.
// This will be implemented in later versions.
// Because of this, the following snippet will basically work
// just like a normal Synchronous request, except that the Success
// and Error callbacks can be configured more conveniently.
$successCallback = isset($options["onSuccess"]) && is_callable($options["onSuccess"]) ? $options["onSuccess"] : null;
$errorCallback = isset($options["onError"]) && is_callable($options["onError"]) ? $options["onError"] : null;
$cancelCallback = isset($options["onReject"]) && is_callable($options["onReject"]) ? $options["onReject"] : null;
$promise = $client->sendAsync($request);
$promise->then(
function(ResponseInterface $response)
use ($successCallback)
{
if ($successCallback)
return $successCallback($response);
return $response;
},
function(RequestException $exception)
use ($errorCallback)
{
if ($errorCallback)
return $errorCallback($exception);
return $exception;
}
);
if ($cancelCallback) {
// register promise rejection callback (happens when the
// cancel() method is called on promises.)
$promise->otherwise($cancelCallback);
}
// Guzzle Promises advantages will only be leveraged
// in Parelell request execution mode as all requests
// will be sent in paralell and the handling time goes
// down to the minimum response time of ALL promises.
return $promise->wait();
} | php | protected function promiseResponse(Client $client, Request $request, array $options = [])
{
// Guzzle Promises do not allow Asynchronous Requests Handling,
// I have implemented this feature only because it will
// allow a better Response Time for Paralell Request Handling.
// This will be implemented in later versions.
// Because of this, the following snippet will basically work
// just like a normal Synchronous request, except that the Success
// and Error callbacks can be configured more conveniently.
$successCallback = isset($options["onSuccess"]) && is_callable($options["onSuccess"]) ? $options["onSuccess"] : null;
$errorCallback = isset($options["onError"]) && is_callable($options["onError"]) ? $options["onError"] : null;
$cancelCallback = isset($options["onReject"]) && is_callable($options["onReject"]) ? $options["onReject"] : null;
$promise = $client->sendAsync($request);
$promise->then(
function(ResponseInterface $response)
use ($successCallback)
{
if ($successCallback)
return $successCallback($response);
return $response;
},
function(RequestException $exception)
use ($errorCallback)
{
if ($errorCallback)
return $errorCallback($exception);
return $exception;
}
);
if ($cancelCallback) {
// register promise rejection callback (happens when the
// cancel() method is called on promises.)
$promise->otherwise($cancelCallback);
}
// Guzzle Promises advantages will only be leveraged
// in Parelell request execution mode as all requests
// will be sent in paralell and the handling time goes
// down to the minimum response time of ALL promises.
return $promise->wait();
} | [
"protected",
"function",
"promiseResponse",
"(",
"Client",
"$",
"client",
",",
"Request",
"$",
"request",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"// Guzzle Promises do not allow Asynchronous Requests Handling,",
"// I have implemented this feature only becau... | Use GuzzleHTTP Promises v6 Implementation to send
the request asynchronously. As mentioned in the source
code, this method will only leverage the advantages
of Asynchronous execution in later versions.
The current version uses the Promises but will synchronously
execute the Request and wait for it to response.
Configuring the onSuccess, onError and onReject callbacks
is possible using callables. Following signatures will
apply:
- onSuccess: function(ResponseInterface $response)
- onError: function(RequestException $exception)
- onReject: function(string $reason)
@param Client $client [description]
@param Request $request [description]
@param array $options [description]
@return [type] [description] | [
"Use",
"GuzzleHTTP",
"Promises",
"v6",
"Implementation",
"to",
"send",
"the",
"request",
"asynchronously",
".",
"As",
"mentioned",
"in",
"the",
"source",
"code",
"this",
"method",
"will",
"only",
"leverage",
"the",
"advantages",
"of",
"Asynchronous",
"execution",
... | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Handlers/GuzzleRequestHandler.php#L60-L105 |
evias/nem-php | src/Handlers/GuzzleRequestHandler.php | GuzzleRequestHandler.status | public function status(array $options = [], $usePromises = false)
{
$headers = [];
if (!empty($options["headers"]))
$headers = $options["headers"];
// get generic headers
$headers = $this->normalizeHeaders($headers);
// prepare guzzle request options
$options = array_merge($options, [
"body" => "",
"headers" => $headers,
]);
$client = new Client(["base_uri" => $this->getBaseUrl()]);
$request = new Request("GET", "heartbeat", $options);
if (! $usePromises)
// return the response object when the request is completed.
// this behaviour handles the request synchronously.
return $client->send($request);
return $this->promiseResponse($client, $request, $options);
} | php | public function status(array $options = [], $usePromises = false)
{
$headers = [];
if (!empty($options["headers"]))
$headers = $options["headers"];
// get generic headers
$headers = $this->normalizeHeaders($headers);
// prepare guzzle request options
$options = array_merge($options, [
"body" => "",
"headers" => $headers,
]);
$client = new Client(["base_uri" => $this->getBaseUrl()]);
$request = new Request("GET", "heartbeat", $options);
if (! $usePromises)
// return the response object when the request is completed.
// this behaviour handles the request synchronously.
return $client->send($request);
return $this->promiseResponse($client, $request, $options);
} | [
"public",
"function",
"status",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"usePromises",
"=",
"false",
")",
"{",
"$",
"headers",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"options",
"[",
"\"headers\"",
"]",
")",
")",
"$"... | This method triggers a GET request to the given
Base URL with the URI `/heartbeat` using the GuzzleHttp
client.
Default behaviour disables Promises Features.
Promises Features
- success callback can be configured with $options["onSuccess"],
a ResponseInterface object will be passed to this callable when
the Request Completes.
- error callback can be configured with $options["onError"],
a RequestException object will be passed to this callable when
the Request encounters an error
@see \NEM\Contracts\RequestHandler
@param string $bodyJSON
@param array $options can contain "headers" array, "onSuccess" callable,
"onError" callable and any other GuzzleHTTP request
options.
@param boolean $usePromises
@return [type] | [
"This",
"method",
"triggers",
"a",
"GET",
"request",
"to",
"the",
"given",
"Base",
"URL",
"with",
"the",
"URI",
"/",
"heartbeat",
"using",
"the",
"GuzzleHttp",
"client",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Handlers/GuzzleRequestHandler.php#L130-L153 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.