Python从头实现以太坊(三):解码引导节点的响应

Python从头实现以太坊系列索引:
一、Ping
二、Pinging引导节点
三、解码引导节点的响应
四、查找邻居节点
五、类-Kademlia协议
六、Routing

这是我写的从头完整实现以太坊协议系列的第三部分(第一部分,第二部分)。我们目前已经实现了以太坊发现协议——用于查找其他可以与之进行区块链同步的节点的算法。我们已经能够ping通引导节点——写在源代码里面的,用于查找其他节点的起始端点。节点响应了一条消息,但是我们还未对它进行解码。今天我们就要来解码这个引导节点响应的消息。

到https://github.com/HuangFJ/pyeth下载本项目代码:
git clone https://github.com/HuangFJ/pyeth

数据解包

这一节,我们将写一些函数用来将RLP编码的PingNodePong消息解包为Python对象。这些方法将在哈希和签名验证后,读取消息数据。我们已经定义了PingNode类,现在要实现Pong类。

在RLPx规范中,Pong被定义成:

Pong packet-type: 0x02
struct Pong
{
    Endpoint to;
    h256 echo;
    uint32_t timestamp;
};

让我们在pyeth/discovery.py里写一个此结构相对应的类:

class Pong(object):
    packet_type = '\x02'

    def __init__(self, to, echo, timestamp):
        self.to = to
        self.echo = echo
        self.timestamp = timestamp

    def __str__(self):
        return "(Pong " + str(self.to) + "  " + str(self.timestamp) + ")"

    def pack(self):
        return [
            self.to.pack(),
            self.echo,
            struct.pack(">I", self.timestamp)]

    @classmethod
    def unpack(cls, packed):
        to = EndPoint.unpack(packed[0])
        echo = packed[1]
        timestamp = struct.unpack(">I", packed[2])[0]
        return cls(to, echo, timestamp)

这个类把包结构编码为Python对象,packet_type作为类字段,并将toechotimestamp传递给构造函数。我添加了一个__str__方法用于打印对象,这里要用到to,它是一个EndPoint对象,它也要一个__str__方法。我们定义为:

class EndPoint(object):
    ...    
    def __str__(self):
        return "(EP " + self.address.exploded + " " + str(self.udpPort) + " " +  str(self.tcpPort)  + ")"
    ...

回到Pong类。就如第一部分以及RLP规范所述,pack方法把对象转为item格式供rlp.encode消费,item是二进制字符串或者多个item的列表。我们需要编码toechotimestamp。对于to,我们可以用to.pack(),因为item的定义是递归的。接着,echo已经是字符串,因此它不需要再转化。最后,我用带有>I参数的struct.packtimestamp编码为大端无符号32位整型。

unpack方法是pack的逆过程。对于to,我们用下面定义的EndPoint unpack来解码:

class EndPoint(object):
    ...
    @classmethod
    def unpack(cls, packed):
        udpPort = struct.unpack(">H", packed[1])[0]
        tcpPort = struct.unpack(">H", packed[2])[0]
        return cls(packed[0], udpPort, tcpPort)

tcpPortudpPortstruct.unpack取回,IP地址以字符串格式传递,由ip_address的构造函数处理。

因为echo被定义为h256,256字节的哈希,它可以解包成自己本身。timestamp被用struct.unpack解包成大端32位整型。

我们还需要定义PingNode__str__unpack方法,如下:

class PingNode(object):
    packet_type = '\x01';
    version = '\x03';
    def __init__(self, endpoint_from, endpoint_to, timestamp):
        self.endpoint_from = endpoint_from
        self.endpoint_to = endpoint_to
        self.timestamp = timestamp

    def __str__(self):
        return "(Ping " + str(ord(self.version)) + " " + str(self.endpoint_from) + " " + str(self.endpoint_to) + " " +  str(self.timestamp) + ")"


    def pack(self):
        return [self.version,
                self.endpoint_from.pack(),
                self.endpoint_to.pack(),
                struct.pack(">I", self.timestamp)]

    @classmethod
    def unpack(cls, packed):
        assert(packed[0] == cls.version)
        endpoint_from = EndPoint.unpack(packed[1])
        endpoint_to = EndPoint.unpack(packed[2])
        return cls(endpoint_from, endpoint_to)

PingNode构造函数的修改会牵涉到PingServerping方法,此处也应做相应修改:

def ping(self, endpoint):
    ping = PingNode(self.endpoint, endpoint, time.time() + 60)
    message = self.wrap_packet(ping)
    print "sending " + str(ping)
    self.sock.sendto(message, (endpoint.address.exploded, endpoint.udpPort))

解码响应消息

回顾一下我们第一部分讨论的在RLPx规范中的消息排列(||是连接符号):
hash || signature || packet-type || packet-data

在这一节,我们检查消息的哈希和签名,如果都有效,才根据packet-type解码不同类型的消息。在pyeth/discovery.py中,我们的包监听函数udp_listen被定义在PingServer里面:

def udp_listen(self):
    def receive_ping():
        print "listening..."
        data, addr = self.sock.recvfrom(1024)
        print "received message[", addr, "]"

    return threading.Thread(target = receive_ping)

我将把receive_ping拆分为更通用的函数,名称叫做receive,它将用于包解码:

def udp_listen(self):
    return threading.Thread(target = self.receive)

def receive(self):
    print "listening..."
    data, addr = self.sock.recvfrom(1024)
    print "received message[", addr, "]"

    ## decode packet below

现在我们要填充## decode packet below这一行以下的代码,从解码哈希开始。我们把下面的代码添加到receive函数:

## verify hash
msg_hash = data[:32]
if msg_hash != keccak256(data[32:]):
    print " First 32 bytes are not keccak256 hash of the rest."
    return
else:
    print " Verified message hash."

第二步就是验证secp256k1签名。首先我们用secp256k1库把签名反系列化成对象,然后我们从签名里面取回公钥,然后我们用公钥来验证签名。为了反系列化,我们使用服务器私钥priv_keyecdsa_recoverable_deserialize方法。我们之前用sig_serialized[0] + chr(sig_serialized[1])编码签名,第一项是64字节,第二项是1字节。因此我们需要抓取哈希之后的65字节,接着把签名分成64字节和1字节的参数并对最后一个字节使用ord函数——chr的逆过程。

## verify signature
signature = data[32:97]
signed_data = data[97:]
deserialized_sig = self.priv_key.ecdsa_recoverable_deserialize(signature[:64],
                                                               ord(signature[64]))

为了取回公钥,我们使用ecdsa_recover。还记得我们之前用raw = True告诉算法我们使用自己的keccak256哈希算法替代函数默认的哈希算法吗。

remote_pubkey = self.priv_key.ecdsa_recover(keccak256(signed_data),
                                            deserialized_sig,
                                            raw = True)

现在我们创建PublicKey对象来存储公钥。我们要在文件头部引入这个类:
from secp256k1 import PrivateKey, PublicKey
回到receive,我们继续编写:

pub = PublicKey()
pub.public_key = remote_pubkey

现在我们可以使用ecdsa_verify验证signed_data是否被deserialized_sig签名过:

verified = pub.ecdsa_verify(keccak256(signed_data),
                            pub.ecdsa_recoverable_convert(deserialized_sig),
                            raw = True)

if not verified:
    print " Signature invalid"
    return
else:
    print " Verified signature."

最后一步就是解包消息。具体用什么函数由packet_type字节确定。

response_types = {
    PingNode.packet_type : self.receive_ping,
    Pong.packet_type : self.receive_pong
}

try:
    packet_type = data[97]
    dispatch = response_types[packet_type]
except KeyError:
    print " Unknown message type: " + data[97]
    return

payload = data[98:]
dispatch(payload)

我们将receive_pingreceive_pong保持简单,就如PingServer的其他函数。

def receive_pong(self, payload):
    print " received Pong"
    print "", Pong.unpack(rlp.decode(payload))

def receive_ping(self, payload):
    print " received Ping"
    print "", PingNode.unpack(rlp.decode(payload))

让我们运行python send_ping.py检查一下看看程序如何运行。你应该会看到:

sending (Ping 3 (EP 52.4.20.183 30303 30303) (EP 13.93.211.84 30303 30303) 1501093574.21)
listening...
received message[ ('13.93.211.84', 30303) ]:
 Verified message hash.
 Verified signature.
 received Pong
 (Pong (EP 52.4.20.183 30303 30303)  1501093534)

我们已经成功验证和解码了Pong消息。下次,我们将实现FindNeighbors消息和Neighbors响应消息。

参考:https://ocalog.com/post/20/

你可能感兴趣的:(Python从头实现以太坊(三):解码引导节点的响应)