Exemplo n.º 1
0
    def make_request(self, method, params, packet_type=ChannelPack.TYPE_RPC,
                     response_type=ChannelPack.TYPE_RPC):
        rpc_data = self.encode_rpc_request(method, params)
        self.logger.debug("request rpc_data : {}".format(rpc_data))
        seq = ChannelPack.make_seq32()
        request_pack = ChannelPack(packet_type, seq, 0, rpc_data)
        self.send_pack(request_pack)
        onresponse_emitter_str = ChannelHandler.getEmitterStr(self.onResponsePrefix,
                                                              seq, response_type)
        # register onResponse emitter
        self.lock.acquire()
        self.callbackEmitter.on(onresponse_emitter_str, self.onResponse)
        self.lock.release()
        self.requests.append(onresponse_emitter_str)

        emitter_str = ChannelHandler.getEmitterStr(self.getResultPrefix,
                                                   seq, response_type)

        def resolve_promise(resolve, reject):
            """
            resolve promise
            """
            # register getResult emitter
            self.lock.acquire()
            self.callbackEmitter.on(emitter_str, (lambda result, is_error: resolve(
                result) if is_error is False else reject(result)))
            self.lock.release()
        p = Promise(resolve_promise)
        return p.get()
Exemplo n.º 2
0
 def check_heatbeat(self):
     if time.time() - self.lastheatbeattime < self.heatbeatStamp:
         return
     pack = ChannelPack(ChannelPack.TYPE_HEATBEAT,
                        ChannelPack.make_seq32(), 0, bytes("", "utf-8"))
     self.sendpack(pack)
     self.lastheatbeattime = time.time()
Exemplo n.º 3
0
    def send_hello(self, ):
        # 与服务端建立socket连接
        with socket.create_connection((host, port)) as sock:
            #sock.send(bytes(testreq,"utf-8") )
            # print("sent",testreq)
            #reply = sock.recv(4096)
            # print(reply)
            # 将socket打包成SSL socket
            print("connect {}:{},as socket {}".format(host, port, sock))
            with context.wrap_socket(sock) as ssock:
                print(ssock)
                # 向服务端发送信息
                buffer = ChannelPack.pack_all(ChannelPack.TYPE_RPC, testreq)
                ssock.send(buffer)
                # 接收服务端返回的信息
                responsePack = None
                respbuffer = bytearray()
                for i in [0, 3]:
                    msg = ssock.recv(1024 * 10)
                    respbuffer += msg
                    (code, len,
                     responsePack) = ChannelPack.unpack(bytes(respbuffer))
                    i += 1
                    if code != 0:
                        continue
                    if len > 0:
                        respbuffer = respbuffer[len:]
                        if code == 0:
                            break
                print(responsePack.result, responsePack.data)

                ssock.close()
def register_event_callback(addresses, event_name, indexed_value):
    topics = []
    topic0 = parser.topic_from_event_name(event_name)
    topics.append(topic0)
    event_abi = parser.event_name_map[event_name]
    print("event abi:", event_abi)
    if len(indexed_value) > 0:
        indexedinput = []
        for input in event_abi["inputs"]:
            if input["indexed"] is True:
                indexedinput.append((input['name'], input['type']))
        print(indexedinput)
        i = 0
        for v in indexed_value:
            itype = indexedinput[i][1]
            topic = DatatypeParser.topic_from_type(itype, v)
            if not (topic is None):
                topics.append(topic)
            i = i + 1
    requestJson = format_event_register_request("latest", "latest", addresses,
                                                topics)
    requestbytes = ChannelPack.pack_amop_topic_message("", requestJson)
    client.channel_handler.pushDispacher.add_handler(
        ChannelPack.EVENT_LOG_PUSH, eventHandler01)
    client.channel_handler.pushDispacher.add_handler(
        ChannelPack.EVENT_LOG_PUSH, eventHandler02)
    response = client.channel_handler.make_channel_request(
        requestbytes, ChannelPack.CLIENT_REGISTER_EVENT_LOG,
        ChannelPack.CLIENT_REGISTER_EVENT_LOG)
    (topic, result) = ChannelPack.unpack_amop_topic_message(response)
    dataobj = json.loads(result)
    print("after register ,event_name:{},topic:{},result:{}".format(
        event_name, topic, dataobj['result']))
Exemplo n.º 5
0
    def make_channel_request(self, data, packet_type, response_type=None):
        seq = ChannelPack.make_seq32()
        request_pack = ChannelPack(packet_type, seq, 0, data)
        self.send_pack(request_pack)
        onresponse_emitter_str = ChannelHandler.getEmitterStr(
            self.onResponsePrefix, seq, response_type)
        # register onResponse emitter
        self.lock.acquire()
        self.callbackEmitter.on(onresponse_emitter_str, self.onResponse)
        self.lock.release()
        self.requests.append(onresponse_emitter_str)

        # register onResponse emitter of RPC
        rpc_onresponse_emitter_str = None
        rpc_result_emitter_str = None
        if response_type is ChannelPack.TYPE_TX_COMMITTED \
                or response_type is ChannelPack.CLIENT_REGISTER_EVENT_LOG:
            rpc_onresponse_emitter_str = ChannelHandler.getEmitterStr(
                self.onResponsePrefix, seq, packet_type)
            self.requests.append(rpc_onresponse_emitter_str)
            rpc_result_emitter_str = ChannelHandler.getEmitterStr(
                self.getResultPrefix, seq, packet_type)
            self.lock.acquire()
            self.callbackEmitter.on(rpc_onresponse_emitter_str,
                                    self.onResponse)
            self.lock.release()
        emitter_str = ChannelHandler.getEmitterStr(self.getResultPrefix, seq,
                                                   response_type)

        def resolve_promise(resolve, reject):
            """
            resolve promise
            """
            # register getResult emitter
            self.lock.acquire()
            self.callbackEmitter.on(emitter_str,
                                    (lambda result, is_error: resolve(result)))

            # 1. if send transaction failed, return the error message directly
            #    and erase the registered 0x1002 emitter
            # 2. if send transaction success, remove the registered 0x12 emitter
            if rpc_result_emitter_str is not None:
                self.callbackEmitter.on(
                    rpc_result_emitter_str,
                    (lambda result, is_error: resolve(result) and self.requests
                     .remove(onresponse_emitter_str) if is_error is True else
                     self.requests.remove(rpc_onresponse_emitter_str) if self.
                     requests.count(rpc_onresponse_emitter_str) else None))
            self.lock.release()

        p = Promise(resolve_promise)
        # default timeout is 60s
        return p.get(60)
Exemplo n.º 6
0
 def getBlockNumber(self, groupId):
     """
     get block number notify
     """
     block_notify_emitter = ChannelHandler.getEmitterStr(self.onResponsePrefix,
                                                         ChannelPack.get_seq_zero(),
                                                         ChannelPack.TYPE_TX_BLOCKNUM)
     self.callbackEmitter.on(block_notify_emitter, self.onResponse)
     self.logger.debug("block notify emitter: {}".format(block_notify_emitter))
     self.requests.append(block_notify_emitter)
     seq = ChannelPack.make_seq32()
     topic = json.dumps(["_block_notify_{}".format(groupId)])
     request_pack = ChannelPack(ChannelPack.TYPE_TOPIC_REPORT, seq, 0, topic)
     self.send_pack(request_pack)
Exemplo n.º 7
0
    def make_request(self, method, params, type=ChannelPack.TYPE_RPC):
        stat = StatTool.begin()
        rpc_data = self.encode_rpc_request(method,params)
        self.logger.debug("request rpc_data : {}".format(rpc_data) )
        #print("request rpc_data", rpc_data)
        request_pack   = ChannelPack(type,ChannelPack.make_seq32(), 0,rpc_data)

        res = self.send_pack(request_pack)
        starttime = time.time()
        responsematch = False
        while time.time() - starttime < 10: # spend max 10 sec to wait a correct response
            try:
                theQueue = self.recvThread.getQueue(ChannelPack.TYPE_RPC)
                responsepack = theQueue.get(block=True, timeout=3) # pop msg from queue
            except Empty as e:
                continue
            #print("got a pack from queue, detail:{}".format(responsepack.detail()))
            self.logger.debug("got a pack from queue, detail:{}".format(responsepack.detail()))
            if responsepack.type == ChannelPack.TYPE_RPC and responsepack.seq == request_pack.seq:
                responsematch = True
                break
            else:
                #print("*******SKIP!!!! pack ", responsepack.detail())
                self.logger.debug("*******SKIP!!!! pack {}".format( responsepack.detail() ))
                responsepack = None
                continue
        if responsematch == False:
            raise  BcosError(102,None,"timeout")

        result = responsepack.result
        data = responsepack.data.decode("utf-8")

        msg = "success"
        if(result!=0):
            if result in self.errorMsg:
                msg = "unknow error %d"%result
                msg = self.errorMsg[result]
            raise BcosError(result,msg)
        response =  FriendlyJsonSerde().json_decode(data)
        stat.done()
        stat.debug("make_request:{}".format(method) )
        self.logger.debug("GetResponse. %s, Response: %s",
                           method, response)
        #print("response from server:",response)
        self.logger.debug("response from server: {}".format( response) )
        if "result" not in response:
            tempresp =dict()
            tempresp["result"] = response
            response =tempresp
        return response
Exemplo n.º 8
0
    def read_channel(self):
        # 接收服务端返回的信息
        try:
            self.logger.debug("{} channelHandler.ssock.recv begin.".format(
                self.name))
            msg = self.channelHandler.ssock.recv(1024 * 1024 * 10)
            self.logger.debug("channelHandler.ssock.recv len:{}".format(
                len(msg)))
            if msg is None:
                return -1
            if len(msg) == 0:
                return 0
        except Exception as e:
            self.logger.error("{}:ssock read error {}".format(self.name, e))
            return -1
        self.respbuffer += msg
        # if no enough data even for header ,continue to read
        if len(self.respbuffer) < ChannelPack.getheaderlen():
            return len(msg)

        code = 0
        # decode all packs in buffer from node,maybe got N packs on one read
        # -1 means no enough bytes for decode, should break to  continue read and wait
        while code != -1:
            (code, decodelen,
             responsePack) = ChannelPack.unpack(bytes(self.respbuffer))
            # print("respbuffer:",self.respbuffer)
            if decodelen > 0:
                # cut the buffer from last decode  pos
                self.respbuffer = self.respbuffer[decodelen:]
            if code != -1 and responsePack is not None:  # got a pack
                # print("get a pack from node, put to queue {}".format(responsePack.detail()))
                self.logger.debug(
                    "{}:pack from node, put queue(qsize{}),detail {}".format(
                        self.name, self.recvQueue.qsize(),
                        responsePack.detail()))
                if self.recvQueue.full():
                    self.recvQueue.get(
                    )  # if queue full ,pop the head item ,!! the item LOST
                    self.logger.error(
                        "{}:queue {} FULL pop and LOST: {}".format(
                            self.name, responsePack.type,
                            responsePack.detail()))
                self.recvQueue.put(responsePack)
                # self.print_queue()

        return len(msg)
Exemplo n.º 9
0
 def on_push(self, packmsg: ChannelPack):
     print("EventPushHandler", packmsg.detail())
     strmsg = packmsg.data.decode("utf-8")
     response = json.loads(strmsg)
     print("response filterID:", response['filterID'])
     #print("response:", json.dumps(response,indent=4))
     loglist = parser.parse_event_logs(response["logs"])
     print(json.dumps(loglist, indent=4))
 def on_push(self, packmsg: ChannelPack):
     print(">>>>>>>>>>>>>>>>>>EventPushHandler02", packmsg.detail())
     strmsg = packmsg.data.decode("utf-8")
     response = json.loads(strmsg)
     loglist = parser.parse_event_logs(response["logs"])
     print("FilterID ", response["filterID"])
     print(">>>>>>>>>>>>>>>>>>EventPushHandler02",
           json.dumps(loglist, indent=4))
Exemplo n.º 11
0
 def register_eventlog_filter(
         self,
         eventcallback,
         abiparser,
         addresses,
         event_name,
         indexed_value=None,
         fromblock="latest",
         to_block="latest"):
     topics = []
     if event_name is not None:
         topic0 = abiparser.topic_from_event_name(event_name)
         topics.append(topic0)
         event_abi = abiparser.event_name_map[event_name]
     #print("event abi:", event_abi)
     if indexed_value is not None and len(indexed_value) > 0:
         indexedinput = []
         for event_input in event_abi["inputs"]:
             if event_input["indexed"] is True:
                 indexedinput.append((event_input['name'], event_input['type']))
         # print(indexedinput)
         i = 0
         for v in indexed_value:
             itype = indexedinput[i][1]
             topic = DatatypeParser.topic_from_type(itype, v)
             if not (topic is None):
                 topics.append(topic)
             i = i + 1
     # create new filterid by uuid
     seq = uuid.uuid1()
     filterid = seq.hex
     requestJson = self.format_event_register_request(
         fromblock, to_block, addresses, topics, self.client.groupid, filterid)
     requestbytes = ChannelPack.pack_amop_topic_message("", requestJson)
     response = self.client.channel_handler.make_channel_request(
         requestbytes, ChannelPack.CLIENT_REGISTER_EVENT_LOG, ChannelPack.CLIENT_REGISTER_EVENT_LOG)
     (topic, result) = ChannelPack.unpack_amop_topic_message(response)
     dataobj = json.loads(result)
    # print(dataobj)
     if dataobj["result"] == 0:
         self.ecb_manager.set_callback(filterid, eventcallback)
     return dataobj
Exemplo n.º 12
0
from client.channelpack import ChannelPack
from eth_utils import encode_hex
import json
seq = b"123456789012345678900123456789012"
data = "{\"jsonrpc\":\"2.0\",\"method\":\"getClientVersion\",\"params\":[],\"id\":1}"
json.loads(data)
print("datalen ", len(data))
pack = ChannelPack(0x12, seq, 0, data)
packres = pack.pack()

print(encode_hex(packres))

aa = []
b = dict()
aa.append({"test", 1})
aa.append({"test", 2})
print(b)
print(json.dumps(b))