gpt4 book ai didi

php - 如何在 PHP 中验证以太坊地址

转载 作者:可可西里 更新时间:2023-11-01 13:39:48 24 4
gpt4 key购买 nike

我正在使用 PHP 和 curl 与 json 来与我的 geth 服务器交互。

除了一件事,我可以做我想做的一切:根据以太坊钱包格式检查用户输入的地址是否有效。

我看到了一个 javascript 函数 here ,但我主要使用 PHP,我根本不喜欢 JS。

关于如何在 PHP 中验证以太坊地址有什么想法吗?

最佳答案

这是针对 EIP 55 的以太坊地址验证的 PHP 实现规范。有关其工作原理的详细信息,请阅读评论。

<?php

use kornrunner\Keccak; // composer require greensea/keccak

class EthereumValidator
{
public function isAddress(string $address): bool
{
// See: https://github.com/ethereum/web3.js/blob/7935e5f/lib/utils/utils.js#L415
if ($this->matchesPattern($address)) {
return $this->isAllSameCaps($address) ?: $this->isValidChecksum($address);
}

return false;
}

protected function matchesPattern(string $address): int
{
return preg_match('/^(0x)?[0-9a-f]{40}$/i', $address);
}

protected function isAllSameCaps(string $address): bool
{
return preg_match('/^(0x)?[0-9a-f]{40}$/', $address) || preg_match('/^(0x)?[0-9A-F]{40}$/', $address);
}

protected function isValidChecksum($address)
{
$address = str_replace('0x', '', $address);
$hash = Keccak::hash(strtolower($address), 256);

// See: https://github.com/web3j/web3j/pull/134/files#diff-db8702981afff54d3de6a913f13b7be4R42
for ($i = 0; $i < 40; $i++ ) {
if (ctype_alpha($address{$i})) {
// Each uppercase letter should correlate with a first bit of 1 in the hash char with the same index,
// and each lowercase letter with a 0 bit.
$charInt = intval($hash{$i}, 16);

if ((ctype_upper($address{$i}) && $charInt <= 7) || (ctype_lower($address{$i}) && $charInt > 7)) {
return false;
}
}
}

return true;
}
}

依赖

为了验证校验和地址,我们需要一个 keccak-256内置 hash() 不支持的实现功能。您需要要求 greensea/keccak composer package作为依赖。


感谢@WebSpanner 指出了 SHA3 哈希问题。

关于php - 如何在 PHP 中验证以太坊地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com