区块链 区块链技术 比特币公众号手机端

继 WEB3.php bytes[] 类型 编码结果错误的后续

liumuhui 2年前 (2023-06-28) 阅读数 207 #技术
文章标签 phpbytes

最近在项目中需要和智能合约进行交互,使用了 web3p/web3.php 进行编码和解码,但是发现与 remixd 的结果有些差异。参考了本站上的相关问题的解答,但并未完全解决问题。

针对这个问题,可以修改 SolidityType.php 中的 encod 方法。具体修改如下:

public function encode($value, $name)
    {

        if ($this->isDynamicArray($name)) {
            $length = count($value);

            $nestedName = $this->nestedName($name);
            $result = [];
            $result[] = IntegerFormatter::format($length);
            //解决 encode

            if ($this->isDynamicType($nestedName)){
                $start = 0;
                foreach ($value as $k => $val) {
                    if ($start == 0){
                        $l = $length * 32;
                    }else{
                        //FIXME: 修改这行即可
                        //$v_1 = Utils::toHex($value[$k-1]);
                        $v_1 = $this->inputFormat($value[$k-1], $nestedName);
                        $l = (floor((mb_strlen($v_1) + 63) / 64)+1)==2?((floor((mb_strlen($v_1) + 63) / 64)+1) * 32):((floor((mb_strlen($v_1) + 63) / 64)) * 32);

                    }

                    $start += $l;

                    $result[] = IntegerFormatter::format($start);
                }
            }

            foreach ($value as $val) {
                $result[] = $this->encode($val, $nestedName);
            }
            return $result;
        } elseif ($this->isStaticArray($name)) {
            $length = $this->staticArrayLength($name);
            $nestedName = $this->nestedName($name);
            $result = [];

            foreach ($value as $val) {
                $result[] = $this->encode($val, $nestedName);
            }
            return $result;
        }
        return $this->inputFormat($value, $name);
    }

Bytes[]数组属于变长类型的数据,编码规则如下:

(数组元素个数) (Value1 开始位置)(Value2 开始的位置)……  (Value1 的长度 + Value1) (Value2 的长度 + Value2) ……

这里点赞翻译小组的逆向EVM系列的文章,深受启发,有兴趣的可以看下逆向 EVM - 解析原始Calldata数据。

版权声明

本文仅代表作者观点,不代表区块链技术网立场。
本文系作者授权本站发表,未经许可,不得转载。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门