I'm trying to find a php equivalent for this js function below:
Original JS function:
function getAddrCheckSum(addr: Buffer, isContract? : boolean): Hex {
const addrPre20 = addr.slice(0, 20);
const _checkSum = blake2b(addrPre20, null, ADDR_CHECK_SUM_SIZE);
const checkSum = Buffer.from(_checkSum);
if (!isContract) {
return checkSum.toString('hex');
}
const newCheckSum = [];
checkSum.forEach(function (byte) {
newCheckSum.push(byte ^ 0xFF);
});
return Buffer.from(newCheckSum).toString('hex');
}
PHP implementation:
include_once('./lib/Blake2b.php');
function getAddrCheckSum($address, $isContract) {
$ADDR_CHECK_SUM_SIZE = 5;
$addrPre20 = substr($address, 0, 20);
$blake2b = new Blake2b($ADDR_CHECK_SUM_SIZE); #<- blake object initialized with size=5
$checkSum = $blake2b->hash($addrPre20);
return $checkSum;
if (!isContract) {
return strval($checkSum);
}
How can I rewrite this part below in php?
$newCheckSum = [];
//checkSum.forEach(function (byte) {
// newCheckSum.push(byte ^ 0xFF);
//});
return strval($newCheckSum);
}
Also, am I doing this right by replacing the js toString by php strval? and, do I need to find an equivalent of "Buffer.from(...,'hex')" for php instead of just assigning it to a variable?
bin2hex
is your friend. Assuming that $checkSum
is the hash in binary form and $isContract
is boolean then just XOR $checkSum
with the corresponding number of \xFF
characters.
Here is a verbose version:
if (!$isContract)
{
return bin2hex($checkSum);
}
else
{
$newCheckSum = $checkSum ^ str_pad("", strlen($checkSum), "\xFF");
return bin2hex($newCheckSum);
}
And a short one:
return bin2hex
(
!$isContract ? $checkSum: $checkSum ^ str_pad("", strlen($checkSum), "\xFF")
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.