Ejemplo n.º 1
0
    def test_network_addrtime(self):

        addr = "55.15.69.104"
        port = 10333
        ts = int(datetime.now().timestamp())
        services = 0

        nawt = NetworkAddressWithTime(addr, port, services, ts)

        ms = StreamManager.GetStream()
        writer = BinaryWriter(ms)

        nawt.Serialize(writer)

        arr = ms.ToArray()
        arhex = binascii.unhexlify(arr)

        StreamManager.ReleaseStream(ms)

        ms = StreamManager.GetStream(arhex)
        reader = BinaryReader(ms)

        nawt2 = NetworkAddressWithTime()
        nawt2.Deserialize(reader)

        StreamManager.ReleaseStream(ms)

        #        self.assertEqual(nawt.Address, nawt2.Address)
        self.assertEqual(nawt.Services, nawt2.Services)
        self.assertEqual(nawt.Port, nawt2.Port)
        self.assertEqual(nawt.Timestamp, nawt2.Timestamp)
    def FromJson(jsn, isMultiSig=True):
        try:
            parsed = json.loads(jsn)
            if parsed['type'] == 'Neo.Core.ContractTransaction':
                verifiable = ContractTransaction()
                ms = StreamManager.GetStream(binascii.unhexlify(parsed['hex']))
                r = BinaryReader(ms)
                verifiable.DeserializeUnsigned(r)
                StreamManager.ReleaseStream(ms)
                context = ContractParametersContext(verifiable,
                                                    isMultiSig=isMultiSig)
                for key, value in parsed['items'].items():
                    if "0x" in key:
                        key = key[2:]
                    key = key.encode()
                    parameterbytes = []
                    for pt in value['parameters']:
                        if pt['type'] == 'Signature':
                            parameterbytes.append(0)
                    contract = Contract.Create(value['script'], parameterbytes,
                                               key)
                    context.ContextItems[key] = ContextItem(contract)
                    if 'signatures' in value:
                        context.ContextItems[key].Signatures = value[
                            'signatures']

                return context
            else:
                raise ("Unsupported transaction type in JSON")

        except Exception as e:
            logger.error(
                "Failed to import ContractParametersContext from JSON: {}".
                format(e))
Ejemplo n.º 3
0
    def DeserializeFromBufer(buffer, offset=0):
        mstream = StreamManager.GetStream(buffer)
        reader = BinaryReader(mstream)
        tx = Transaction.DeserializeFrom(reader)

        StreamManager.ReleaseStream(mstream)
        return tx
Ejemplo n.º 4
0
    def FromTrimmedData(byts):
        """
        Deserialize a block from raw bytes.

        Args:
            byts:

        Returns:
            Block:
        """
        block = Block()
        block.__is_trimmed = True
        ms = StreamManager.GetStream(byts)
        reader = BinaryReader(ms)

        block.DeserializeUnsigned(reader)
        reader.ReadByte()
        witness = Witness()
        witness.Deserialize(reader)
        block.Script = witness

        block.Transactions = reader.ReadHashes()

        StreamManager.ReleaseStream(ms)

        return block
Ejemplo n.º 5
0
    def test_2_serialize_notify_no_payload(self):

        sc = SmartContractEvent(
            SmartContractEvent.RUNTIME_NOTIFY,
            ContractParameter(ContractParameterType.Array, []),
            self.contract_hash, 99, self.event_tx, True, False)

        stream = StreamManager.GetStream()
        writer = BinaryWriter(stream)
        sc.Serialize(writer)

        out = bytes(stream.getvalue())

        self.assertEqual(
            out,
            b'\x1cSmartContract.Runtime.Notify\x11\xc4\xd1\xf4\xfb\xa6\x19\xf2b\x88p\xd3n:\x97s\xe8tp[c\x00\x00\x00\x90\xe4\xf1\xbbb\x8e\xf1\x07\xde\xe9\xf0\xd2\x12\xd1w\xbco\x844\x07=\x1b\xa7\x1f\xa7\x94`\x0b\xb4\x88|K'
        )

        StreamManager.ReleaseStream(stream)
        new_event = SmartContractEvent.FromByteArray(out)

        self.assertEqual(new_event.event_type, sc.event_type)
        self.assertEqual(new_event.contract_hash, sc.contract_hash)
        self.assertEqual(new_event.test_mode, sc.test_mode)
        self.assertEqual(new_event.tx_hash, sc.tx_hash)
        self.assertEqual(new_event.block_number, sc.block_number)
    def test_5_serialize_full_refund_payload(self):

        sc = NotifyEvent(SmartContractEvent.RUNTIME_NOTIFY,
                         [b'refund', self.addr_to,
                          BigInteger(123000)], self.contract_hash, 91349,
                         self.event_tx, True, False)

        stream = StreamManager.GetStream()
        writer = BinaryWriter(stream)
        sc.Serialize(writer)

        out = bytes(stream.getvalue())

        StreamManager.ReleaseStream(stream)
        new_event = SmartContractEvent.FromByteArray(out)

        self.assertEqual(new_event.event_type, sc.event_type)
        self.assertEqual(new_event.contract_hash, sc.contract_hash)
        self.assertEqual(new_event.test_mode, sc.test_mode)
        self.assertEqual(new_event.tx_hash, sc.tx_hash)
        self.assertEqual(new_event.block_number, sc.block_number)

        self.assertEqual(new_event.notify_type, b'refund')
        self.assertEqual(new_event.AddressTo,
                         'AKZmSGPD7ytJBbxpRPmobYGLNxdWH3Jiqs')
        self.assertEqual(new_event.addr_from, sc.contract_hash)
        self.assertEqual(new_event.Amount, 123000)
        self.assertEqual(new_event.is_standard_notify, True)
    def OnAddHeader(self, header):

        hHash = header.Hash.ToBytes()

        if hHash not in self._header_index:
            self._header_index.append(hHash)

        while header.Index - 2000 >= self._stored_header_count:
            ms = StreamManager.GetStream()
            w = BinaryWriter(ms)
            headers_to_write = self._header_index[
                self._stored_header_count:self._stored_header_count + 2000]
            w.Write2000256List(headers_to_write)
            out = ms.ToArray()
            StreamManager.ReleaseStream(ms)
            with self._db.write_batch() as wb:
                wb.put(
                    DBPrefix.IX_HeaderHashList +
                    self._stored_header_count.to_bytes(4, 'little'), out)

            self._stored_header_count += 2000

            logger.debug("Trimming stored header index %s" %
                         self._stored_header_count)

        with self._db.write_batch() as wb:
            wb.put(DBPrefix.DATA_Block + hHash, bytes(8) + header.ToArray())
            wb.put(DBPrefix.SYS_CurrentHeader,
                   hHash + header.Index.to_bytes(4, 'little'))
Ejemplo n.º 8
0
 def ToByteArray(self):
     stream = StreamManager.GetStream()
     writer = BinaryWriter(stream)
     self.Serialize(writer)
     out = stream.getvalue()
     StreamManager.ReleaseStream(stream)
     return out
Ejemplo n.º 9
0
    def test_4_serialize_full_transfer_notify_payload(self):

        payload = ContractParameter(ContractParameterType.Array, [
            ContractParameter(ContractParameterType.String, b'transfer'),
            ContractParameter(ContractParameterType.ByteArray, self.addr_to),
            ContractParameter(ContractParameterType.ByteArray, self.addr_from),
            ContractParameter(ContractParameterType.Integer, 123000)
        ])

        sc = NotifyEvent(SmartContractEvent.RUNTIME_NOTIFY, payload, self.contract_hash, 91349, self.event_tx, True, False)

        stream = StreamManager.GetStream()
        writer = BinaryWriter(stream)
        sc.Serialize(writer)

        out = bytes(stream.getvalue())

        StreamManager.ReleaseStream(stream)
        new_event = SmartContractEvent.FromByteArray(out)

        self.assertEqual(new_event.event_type, sc.event_type)
        self.assertEqual(new_event.contract_hash, sc.contract_hash)
        self.assertEqual(new_event.test_mode, sc.test_mode)
        self.assertEqual(new_event.tx_hash, sc.tx_hash)
        self.assertEqual(new_event.block_number, sc.block_number)

        self.assertEqual(new_event.notify_type, b'transfer')
        self.assertEqual(new_event.AddressTo, 'ALb8FEhEmtSqv97fuNVuoLmcmrSKckffRf')
        self.assertEqual(new_event.AddressFrom, 'AKZmSGPD7ytJBbxpRPmobYGLNxdWH3Jiqs')
        self.assertEqual(new_event.Amount, 123000)
        self.assertEqual(new_event.is_standard_notify, True)
    def test_3_serialize_single_transfer_notify_payload(self):

        sc = NotifyEvent(SmartContractEvent.RUNTIME_NOTIFY, [b'transfer'],
                         self.contract_hash, 99, self.event_tx, True, False)

        stream = StreamManager.GetStream()
        writer = BinaryWriter(stream)
        sc.Serialize(writer)

        out = bytes(stream.getvalue())

        StreamManager.ReleaseStream(stream)
        new_event = SmartContractEvent.FromByteArray(out)

        self.assertEqual(new_event.event_type, sc.event_type)
        self.assertEqual(new_event.contract_hash, sc.contract_hash)
        self.assertEqual(new_event.test_mode, sc.test_mode)
        self.assertEqual(new_event.tx_hash, sc.tx_hash)
        self.assertEqual(new_event.block_number, sc.block_number)

        self.assertEqual(new_event.notify_type, b'transfer')
        self.assertEqual(new_event.AddressFrom, None)
        self.assertEqual(new_event.AddressTo, None)
        self.assertEqual(new_event.Amount, 0)
        self.assertEqual(new_event.is_standard_notify, False)
        self.assertEqual(new_event.ShouldPersist, False)
Ejemplo n.º 11
0
    def FromTrimmedData(byts, index=None, transaction_method=None):
        """
        Deserialize a block from raw bytes.

        Args:
            byts:
            index: UNUSED
            transaction_method: UNUSED

        Returns:
            Block:
        """
        block = Block()
        block.__is_trimmed = True
        ms = StreamManager.GetStream(byts)
        reader = BinaryReader(ms)

        block.DeserializeUnsigned(reader)
        reader.ReadByte()
        witness = Witness()
        witness.Deserialize(reader)
        block.witness = witness

        block.Transactions = reader.ReadHashes()

        StreamManager.ReleaseStream(ms)

        return block
Ejemplo n.º 12
0
    def FromTrimmedData(byts):
        """
        Deserialize a block from raw bytes.

        Args:
            byts:

        Returns:
            Block:
        """
        block = Block()
        block.__is_trimmed = True
        ms = StreamManager.GetStream(byts)
        reader = BinaryReader(ms)

        block.DeserializeUnsigned(reader)
        reader.ReadByte()
        witness = Witness()
        witness.Deserialize(reader)
        block.Script = witness

        bc = GetBlockchain()
        tx_list = []
        for tx_hash in reader.ReadHashes():
            tx = bc.GetTransaction(tx_hash)[0]
            if not tx:
                raise Exception("Could not find transaction!\n Are you running code against a valid Blockchain instance?\n Tests that accesses transactions or size of a block but inherit from NeoTestCase instead of BlockchainFixtureTestCase will not work.")
            tx_list.append(tx)

        block.Transactions = tx_list

        StreamManager.ReleaseStream(ms)

        return block
Ejemplo n.º 13
0
    def CheckDataReceived(self):

        if len(self.buffer_in) >= 24:

            mstart = self.buffer_in[:24]
            ms = StreamManager.GetStream(mstart)
            reader = BinaryReader(ms)

            try:
                m = Message()
                m.Magic = reader.ReadUInt32()
                m.Command = reader.ReadFixedString(12).decode('utf-8')
                m.Length = reader.ReadUInt32()
                m.Checksum = reader.ReadUInt32()
                self.pm = m
            except Exception as e:
                self.Log('could not read initial bytes %s ' % e)
            finally:
                StreamManager.ReleaseStream(ms)
                del reader

            try:
                #make this threadsafe
                #                reactor.callFromThread(self.CheckMessageData)
                self.CheckMessageData()
            except RecursionError:
                self.Log("Recursion error!!!")
                self.Disconnect()
    def test_1_serialize_runtime_log(self):

        sc = SmartContractEvent(SmartContractEvent.RUNTIME_LOG, [],
                                self.contract_hash, 99999, self.event_tx, True,
                                False)

        stream = StreamManager.GetStream()
        writer = BinaryWriter(stream)
        sc.Serialize(writer)

        out = bytes(stream.getvalue())

        self.assertEqual(
            out,
            b'\x19SmartContract.Runtime.Log\x11\xc4\xd1\xf4\xfb\xa6\x19\xf2b\x88p\xd3n:\x97s\xe8tp[\x9f\x86\x01\x00\x90\xe4\xf1\xbbb\x8e\xf1\x07\xde\xe9\xf0\xd2\x12\xd1w\xbco\x844\x07=\x1b\xa7\x1f\xa7\x94`\x0b\xb4\x88|K'
        )

        StreamManager.ReleaseStream(stream)
        new_event = SmartContractEvent.FromByteArray(out)

        self.assertEqual(new_event.event_type, sc.event_type)
        self.assertEqual(new_event.contract_hash, sc.contract_hash)
        self.assertEqual(new_event.test_mode, sc.test_mode)
        self.assertEqual(new_event.tx_hash, sc.tx_hash)
        self.assertEqual(new_event.block_number, sc.block_number)
Ejemplo n.º 15
0
 def DeserializeFromDB(buffer):
     m = StreamManager.GetStream(buffer)
     reader = BinaryReader(m)
     v = StorageItem()
     v.Deserialize(reader)
     StreamManager.ReleaseStream(m)
     return v
Ejemplo n.º 16
0
 def __init__(self, engine=None, script=None, push_only=False, break_points=set()):
     self._Engine = engine
     self.Script = script
     self.PushOnly = push_only
     self.__Breakpoints = break_points
     self.__mstream = StreamManager.GetStream(self.Script)
     self.__OpReader = BinaryReader(self.__mstream)
    def test_2_serialize_single_notify_payload(self):

        sc = NotifyEvent(SmartContractEvent.RUNTIME_NOTIFY, [b'hello'],
                         self.contract_hash, 99, self.event_tx, True, False)

        stream = StreamManager.GetStream()
        writer = BinaryWriter(stream)
        sc.Serialize(writer)

        out = bytes(stream.getvalue())

        self.assertEqual(
            out,
            b'\x1cSmartContract.Runtime.Notify\x11\xc4\xd1\xf4\xfb\xa6\x19\xf2b\x88p\xd3n:\x97s\xe8tp[c\x00\x00\x00\x90\xe4\xf1\xbbb\x8e\xf1\x07\xde\xe9\xf0\xd2\x12\xd1w\xbco\x844\x07=\x1b\xa7\x1f\xa7\x94`\x0b\xb4\x88|K\x05hello'
        )

        StreamManager.ReleaseStream(stream)
        new_event = SmartContractEvent.FromByteArray(out)

        self.assertEqual(new_event.event_type, sc.event_type)
        self.assertEqual(new_event.contract_hash, sc.contract_hash)
        self.assertEqual(new_event.test_mode, sc.test_mode)
        self.assertEqual(new_event.tx_hash, sc.tx_hash)
        self.assertEqual(new_event.block_number, sc.block_number)

        self.assertEqual(new_event.notify_type, b'hello')
        self.assertEqual(new_event.AddressFrom, None)
        self.assertEqual(new_event.AddressTo, None)
        self.assertEqual(new_event.Amount, 0)
        self.assertEqual(new_event.is_standard_notify, False)
Ejemplo n.º 18
0
    def FromTrimmedData(data, index):
        """
        Deserialize into a Header object from the provided data.

        Args:
            data (bytes):
            index: UNUSED

        Returns:
            Header:
        """
        header = Header()

        ms = StreamManager.GetStream(data)

        reader = BinaryReader(ms)
        header.DeserializeUnsigned(reader)
        reader.ReadByte()

        witness = Witness()
        witness.Deserialize(reader)
        header.Script = witness

        StreamManager.ReleaseStream(ms)

        return header
    def test_6_serialize_full_approve_payload(self):

        sc = NotifyEvent(
            SmartContractEvent.RUNTIME_NOTIFY,
            [b'approve', self.addr_to, self.addr_from, b'x\xe0\x01'],
            self.contract_hash, 91349, self.event_tx, True, False)

        stream = StreamManager.GetStream()
        writer = BinaryWriter(stream)
        sc.Serialize(writer)

        out = bytes(stream.getvalue())

        StreamManager.ReleaseStream(stream)
        new_event = SmartContractEvent.FromByteArray(out)

        self.assertEqual(new_event.event_type, sc.event_type)
        self.assertEqual(new_event.contract_hash, sc.contract_hash)
        self.assertEqual(new_event.test_mode, sc.test_mode)
        self.assertEqual(new_event.tx_hash, sc.tx_hash)
        self.assertEqual(new_event.block_number, sc.block_number)

        self.assertEqual(new_event.notify_type, b'approve')
        self.assertEqual(new_event.AddressFrom,
                         'AKZmSGPD7ytJBbxpRPmobYGLNxdWH3Jiqs')
        self.assertEqual(new_event.AddressTo,
                         'ALb8FEhEmtSqv97fuNVuoLmcmrSKckffRf')
        self.assertEqual(new_event.Amount, 123000)
        self.assertEqual(new_event.is_standard_notify, True)
        self.assertEqual(new_event.ShouldPersist, True)
Ejemplo n.º 20
0
 def GetHashData(hashable):
     ms = StreamManager.GetStream()
     writer = BinaryWriter(ms)
     hashable.SerializeUnsigned(writer)
     ms.flush()
     retVal = ms.ToArray()
     StreamManager.ReleaseStream(ms)
     return retVal
 def __init__(self, engine=None, script=None, rvcount=0):
     self.Script = script
     self.__mstream = StreamManager.GetStream(self.Script)
     self.__OpReader = BinaryReader(self.__mstream)
     self._EvaluationStack = RandomAccessStack(name='Evaluation')
     self._AltStack = RandomAccessStack(name='Alt')
     self._RVCount = rvcount
     self.crypto = engine.Crypto
Ejemplo n.º 22
0
    def UpdateInternal(self, key, value):
        if self.batch:
            stream = StreamManager.GetStream()
            bw = BinaryWriter(stream)
            value.Serialize(bw)

            self.batch.put(self.prefix + key, stream.ToArray())
            StreamManager.ReleaseStream(stream)
Ejemplo n.º 23
0
    def DeserializeFromDB(buffer):
        m = StreamManager.GetStream(buffer)
        reader = BinaryReader(m)
        spentcoin = SpentCoinState()
        spentcoin.Deserialize(reader)

        StreamManager.ReleaseStream(m)

        return spentcoin
Ejemplo n.º 24
0
    def __init__(self, stream: Union[bytearray, bytes]) -> None:
        """
        Create an instance.

        Args:
            stream: a stream to operate on.
        """
        super(BinaryWriter, self).__init__()
        self._stream = StreamManager.GetStream(stream)
Ejemplo n.º 25
0
    def DeserializeFromDB(buffer):
        m = StreamManager.GetStream(buffer)
        reader = BinaryReader(m)
        c = ContractState()
        c.Deserialize(reader)

        StreamManager.ReleaseStream(m)

        return c
Ejemplo n.º 26
0
    def ToByteArray(self):
        ms = StreamManager.GetStream()
        writer = BinaryWriter(ms)
        self.Serialize(writer)

        retval = ms.ToArray()
        StreamManager.ReleaseStream(ms)

        return retval
Ejemplo n.º 27
0
    def DeserializeFromDB(buffer):
        m = StreamManager.GetStream(buffer)
        reader = BinaryReader(m)
        account = AssetState()
        account.Deserialize(reader)

        StreamManager.ReleaseStream(m)

        return account
Ejemplo n.º 28
0
def deploy(from_addr, bytecode, contract_params, return_type, details):
    response = requests.post('http://127.0.0.1:20332',
                             json={
                                 'jsonrpc':
                                 '2.0',
                                 'id':
                                 1,
                                 'method':
                                 'mw_construct_deploy_tx',
                                 'params': [{
                                     'from_addr': from_addr,
                                     'bin': bytecode,
                                     'contract_params': contract_params,
                                     'return_type': return_type,
                                     'details': details,
                                 }]
                             }).json()
    if 'error' in response:
        print(response['error']['message'])
        return
    context = response['result']['context']
    binary_tx = response['result']['tx']
    contract_hash = response['result']['hash']

    tx = ContractTransaction.DeserializeFromBufer(
        binascii.unhexlify(binary_tx))

    scripts = requests.post('http://127.0.0.1:5000/neo_sign/',
                            json={
                                'binary_tx': binary_tx
                            }).json()
    tx.scripts = [
        Witness(
            x['invocation'].encode(),
            x['verification'].encode(),
        ) for x in scripts
    ]

    ms = StreamManager.GetStream()
    writer = BinaryWriter(ms)
    tx.Serialize(writer)
    ms.flush()
    signed_tx = ms.ToArray()

    response = requests.post('http://127.0.0.1:20332',
                             json={
                                 'jsonrpc': '2.0',
                                 'id': 1,
                                 'method': 'sendrawtransaction',
                                 'params': [
                                     signed_tx.decode(),
                                 ]
                             }).json()

    print('contract hash:', contract_hash)
    print(response)
Ejemplo n.º 29
0
 def Trim(self):
     ms = StreamManager.GetStream()
     writer = BinaryWriter(ms)
     self.SerializeUnsigned(writer)
     writer.WriteByte(1)
     self.Script.Serialize(writer)
     writer.WriteHashes([tx.Hash.ToBytes() for tx in self.Transactions])
     retVal = ms.ToArray()
     StreamManager.ReleaseStream(ms)
     return retVal
Ejemplo n.º 30
0
    def test_message_serialization(self):

        message = Message('version', payload=self.payload)

        self.assertEqual(message.Command, 'version')

        ms = StreamManager.GetStream()
        writer = BinaryWriter(ms)

        message.Serialize(writer)


        result = binascii.unhexlify( ms.ToArray())
        StreamManager.ReleaseStream(ms)



        ms = StreamManager.GetStream(result)
        reader = BinaryReader(ms)

        deserialized_message = Message()
        deserialized_message.Deserialize( reader )

        StreamManager.ReleaseStream(ms)

        dm = deserialized_message

        self.assertEqual(dm.Command, 'version')

        self.assertEqual(dm.Magic, Settings.MAGIC)

        checksum = Message.GetChecksum(dm.Payload)

        self.assertEqual(checksum, dm.Checksum)


        deserialized_version = IOHelper.AsSerializableWithType(dm.Payload, 'neo.Network.Payloads.VersionPayload.VersionPayload')


        self.assertEqual(deserialized_version.Port, self.port)
        self.assertEqual(deserialized_version.UserAgent, self.ua)

        self.assertEqual(deserialized_version.Timestamp, self.payload.Timestamp)