如何验证以太坊PHP / Laravel的地址?

时间:2017-08-25 04:52:21

标签: php laravel validation laravel-5 ethereum

如何检查Laravel输入中的以太坊地址在格式方面是否有效?

2 个答案:

答案 0 :(得分:1)

这是一个Laravel custom validation rule,用于根据EIP 55规范验证以太坊地址。有关其工作原理的详细信息,请仔细阅读。

<?php

namespace App\Rules;

use kornrunner\Keccak; // composer require greensea/keccak
use Illuminate\Contracts\Validation\Rule;

class ValidEthereumAddress implements Rule
{
    /**
     * @var Keccak
     */
    protected $hasher;

    public function __construct(Keccak $hasher)
    {
        $this->keccak = $hasher;
    }

    public function passes($attribute, $value)
    {
        // See: https://github.com/ethereum/web3.js/blob/7935e5f/lib/utils/utils.js#L415
        if ($this->matchesPattern($value)) {
            return $this->isAllSameCaps($value) ?: $this->isValidChecksum($value);
        }

        return false;
    }

    public function message()
    {
        return 'The :attribute must be a valid Ethereum address.';
    }

    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 = $this->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;
    }
}

依赖关系

要验证校验和地址,我们需要一个Keccac实现,内置hash()函数不支持该实现。您需要this pure PHP implementation才能使上述规则生效。

答案 1 :(得分:0)

任何42字符串以0x开头,后跟0-9,A-F,a-f(有效的十六进制字符)代表有效的以太坊地址。

您可以找到有关小写和部分大写(用于添加校验和)的更多信息以太网地址格式here