Beispiel #1
0
def test_inference(value, expected):
    if expected is not None:
        inferred = infer_sedes(value)
        assert inferred == expected
        expected.serialize(value)
    else:
        with pytest.raises(TypeError):
            infer_sedes(value)
Beispiel #2
0
def test_serializable():
    class Test1(Serializable):
        fields = (
            ('field1', big_endian_int),
            ('field2', binary),
            ('field3', List((big_endian_int, binary)))
        )

    class Test2(Serializable):
        fields = (
            ('field1', Test1),
            ('field2', List((Test1, Test1))),
        )

    t1a_data = (5, 'a', (0, ''))
    t1b_data = (9, 'b', (2, ''))
    test1a = Test1(*t1a_data)
    test1b = Test1(*t1b_data)
    test2 = Test2(test1a, [test1a, test1b])

    # equality
    assert test1a == test1a
    assert test1b == test1b
    assert test2 == test2
    assert test1a != test1b
    assert test1b != test2
    assert test2 != test1a

    with pytest.raises(SerializationError):
        Test1.serialize(test2)
    with pytest.raises(SerializationError):
        Test2.serialize(test1a)
    with pytest.raises(SerializationError):
        Test2.serialize(test1b)

    # inference
    assert infer_sedes(test1a) == Test1
    assert infer_sedes(test1b) == Test1
    assert infer_sedes(test2) == Test2

    # serialization
    serial_1a = Test1.serialize(test1a)
    serial_1b = Test1.serialize(test1b)
    serial_2 = Test2.serialize(test2)
    assert serial_1a == [b'\x05', b'a', [b'', b'']]
    assert serial_1b == [b'\x09', b'b', [b'\x02', b'']]
    assert serial_2 == [serial_1a, [serial_1a, serial_1b]]

    # deserialization
    assert Test1.deserialize(serial_1a) == test1a
    assert Test1.deserialize(serial_1b) == test1b
    assert Test2.deserialize(serial_2) == test2

    # encoding and decoding
    assert decode(encode(test1a), Test1) == test1a
    assert decode(encode(test1b), Test1) == test1b
    assert decode(encode(test2), Test2) == test2
Beispiel #3
0
def test_serializable():
    class Test1(Serializable):
        fields = (('field1', big_endian_int), ('field2', binary),
                  ('field3', List((big_endian_int, binary))))

    class Test2(Serializable):
        fields = (
            ('field1', Test1),
            ('field2', List((Test1, Test1))),
        )

    t1a_data = (5, 'a', (0, ''))
    t1b_data = (9, 'b', (2, ''))
    test1a = Test1(*t1a_data)
    test1b = Test1(*t1b_data)
    test2 = Test2(test1a, [test1a, test1b])
    t2_data = (t1a_data, (t1a_data, t1b_data))

    # equality
    assert test1a == test1a
    assert test1b == test1b
    assert test2 == test2
    assert test1a != test1b
    assert test1b != test2
    assert test2 != test1a

    with pytest.raises(SerializationError):
        Test1.serialize(test2)
    with pytest.raises(SerializationError):
        Test2.serialize(test1a)
    with pytest.raises(SerializationError):
        Test2.serialize(test1b)

    # inference
    assert infer_sedes(test1a) == Test1
    assert infer_sedes(test1b) == Test1
    assert infer_sedes(test2) == Test2

    # serialization
    serial_1a = Test1.serialize(test1a)
    serial_1b = Test1.serialize(test1b)
    serial_2 = Test2.serialize(test2)
    assert serial_1a == ['\x05', 'a', ['', '']]
    assert serial_1b == ['\x09', 'b', ['\x02', '']]
    assert serial_2 == [serial_1a, [serial_1a, serial_1b]]

    # deserialization
    assert Test1.deserialize(serial_1a) == test1a
    assert Test1.deserialize(serial_1b) == test1b
    assert Test2.deserialize(serial_2) == test2

    # encoding and decoding
    assert decode(encode(test1a), Test1) == test1a
    assert decode(encode(test1b), Test1) == test1b
    assert decode(encode(test2), Test2) == test2
 def pubkey(self):
     if self.r == 0 and self.s == 0:
         raise eth.transactions.InvalidTransaction(
             "No signature!")
     if self.v in (27, 28):
         vee = self.v
         sighash = eth.utils.sha3(rlp.encode(self, 
                         eth.transactions.UnsignedTransaction))
     elif self.v >= 37:
         vee = self.v - self.network_id * 2 - 8
         assert vee in (27, 28)
         rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[
                                 :-3] + [self.network_id, '', ''])
         sighash = eth.utils.sha3(rlpdata)
     else:
         raise eth.transactions.InvalidTransaction("Invalid V value")
     if self.r >= eth.transactions.secpk1n or \
         self.s >= eth.transactions.secpk1n or \
         self.r == 0 or self.s == 0:
         raise eth.transactions.InvalidTransaction("Invalid signature values!")
     pub = eth.utils.ecrecover_to_pub(sighash, vee, self.r, self.s)
     if pub == b'\x00' * 64:
         raise eth.transactions.InvalidTransaction(
             "Invalid signature (zero privkey cannot sign)")
     return pub
def main3():

    erc20_data = make_data(to='0x401bf316182c792048c75e52ce18cb12ec3c4273',
                           value=Decimal('65.20627410') * (10**18))
    print("erc20_data:{}".format(erc20_data))

    tx = Transaction(
        nonce=58,
        gasprice=10 * (10**9),
        startgas=210000,
        to='0xee8e2882e07f89685430c27e2f77636b08df3c81',
        value=1,
        # data=b''
        data=erc20_data.decode('hex'))
    tx.sender = '0x56e5782c908f69bd46b7e77338349f961fbe55b1'

    # print(tx.hash)
    signed_tx = tx.sign(
        key='63C08FABC252B53B9471E520CE8199971DB8884B5B569CBBBD17BC714E6BB39F',
        network_id=Rinkeby)  # 4:Rinkeby
    print(signed_tx.hash.encode('hex'))
    rlp_data = rlp.encode(rlp.infer_sedes(tx).serialize(tx))
    print(rlp_data.encode('hex'))
    # print(signed_tx)

    pass
Beispiel #6
0
 def sender(self):
     if not self._sender:
         # Determine sender
         if self.r == 0 and self.s == 0:
             self._sender = null_address
         else:
             if self.v in (27, 28):
                 vee = self.v
                 sighash = utils.sha3(rlp.encode(self, UnsignedTransaction))
             elif self.v >= 37:
                 vee = self.v - self.network_id * 2 - 8
                 assert vee in (27, 28)
                 rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[
                                      :-3] + [self.network_id, '', ''])
                 sighash = utils.sha3(rlpdata)
             else:
                 raise InvalidTransaction("Invalid V value")
             if self.r >= secpk1n or self.s >= secpk1n or self.r == 0 or self.s == 0:
                 raise InvalidTransaction("Invalid signature values!")
             pub = ecrecover_to_pub(sighash, vee, self.r, self.s)
             if pub == b'\x00' * 64:
                 raise InvalidTransaction(
                     "Invalid signature (zero privkey cannot sign)")
             self._sender = utils.sha3(pub)[-20:]
     return self._sender
def main():

    erc20_data = make_data(to='0x56e5782c908f69bd46b7e77338349f961fbe55b1',
                           value=Decimal('2019.08281809') * (10**18))
    print("erc20_data:{}".format(erc20_data))

    tx = Transaction(
        nonce=120,
        gasprice=10 * (10**9),
        startgas=210000,
        to='0x130fc2749d35fe026f32427f60dd3f2ecb6c2f33',
        value=0,
        # data=b''
        data=erc20_data.decode('hex'))
    tx.sender = '0x954d1a58c7abd4ac8ebe05f59191cf718eb0cb89'

    # print(tx.hash)
    signed_tx = tx.sign(
        key='DBBAD2A5682517E4FF095F948F721563231282CA4179AE0DFEA1C76143BA9607',
        network_id=Rinkeby)  # 4:Rinkeby
    print(signed_tx.hash.encode('hex'))
    rlp_data = rlp.encode(rlp.infer_sedes(tx).serialize(tx))
    print(rlp_data.encode('hex'))
    # print(signed_tx)

    pass
Beispiel #8
0
    def signer(self):
        if not self._signer:
            if self.r == 0 and self.s == 0:
                if self.header.number == 0:
                    pub = b"\x00" * 64
                    self._signer = sha3(pub)[-20:]
                    print("GENESIS BLOCK")
                self._signer = null_address
            else:
                if self.v in (27, 28):
                    vee = self.v
                    sighash = sha3(rlp.encode(self, UnsignedBlock))
                elif self.v >= 37:
                    vee = self.v - self.network_id * 2 - 8
                    assert vee in (27, 28)
                    rlpdata = rlp.encode(
                        rlp.infer_sedes(self).serialize(self)[:-3] +
                        [self.network_id, '', ''])
                    sighash = sha3(rlpdata)
                if self.r >= secpk1n or self.s >= secpk1n or self.r == 0 or self.s == 0:
                    raise InvalidBlock("Invalid signature values!")

                pub = ecrecover_to_pub(sighash, self.v, self.r, self.s)
                if pub == b"\x00" * 64:
                    raise InvalidBlock(
                        "Invalid signature (zero privkey cannot sign)")
                self._signer = sha3(pub)[-20:]
        return self._signer
 def sender(self):
     if not self._sender:
         # Determine sender
         if self.r == 0 and self.s == 0:
             self._sender = null_address
         else:
             if self.v in (27, 28):
                 vee = self.v
                 sighash = utils.sha3(rlp.encode(self, UnsignedTransaction))
             elif self.v >= 37:
                 vee = self.v - self.network_id * 2 - 8
                 assert vee in (27, 28)
                 rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[
                                      :-3] + [self.network_id, '', ''])
                 sighash = utils.sha3(rlpdata)
             else:
                 raise InvalidTransaction("Invalid V value")
             if self.r >= secpk1n or self.s >= secpk1n or self.r == 0 or self.s == 0:
                 raise InvalidTransaction("Invalid signature values!")
             pub = ecrecover_to_pub(sighash, vee, self.r, self.s)
             if pub == b'\x00' * 64:
                 raise InvalidTransaction(
                     "Invalid signature (zero privkey cannot sign)")
             self._sender = utils.sha3(pub)[-20:]
     return self._sender
def main2():

    erc20_data = make_data(to='0xdf88522B56B85d4F0Bb08a7494b97E017BC6CB31',
                           value=Decimal('656340.20627410') * (10**18))
    print("erc20_data:{}".format(erc20_data))

    tx = Transaction(
        nonce=51,
        gasprice=10 * (10**9),
        startgas=210000,
        to='0x130fc2749d35fe026f32427f60dd3f2ecb6c2f33',
        value=1 * (10**16),
        # data=b''
        data=erc20_data.decode('hex'))
    tx.sender = '0x56e5782c908f69bd46b7e77338349f961fbe55b1'

    # print(tx.hash)
    signed_tx = tx.sign(
        key='63C08FABC252B53B9471E520CE8199971DB8884B5B569CBBBD17BC714E6BB39F',
        network_id=Rinkeby)  # 4:Rinkeby
    print(signed_tx.hash.encode('hex'))
    rlp_data = rlp.encode(rlp.infer_sedes(tx).serialize(tx))
    print(rlp_data.encode('hex'))
    # print(signed_tx)

    pass
Beispiel #11
0
def test_transfer_ERC20_USDT():

    #rinkeby 合约地址:  0x0f38e3426de0f7afdf7e641633b287f462f346f2

    erc20_data = make_data(
        to='0xC4d2e23807d176441221248fCbC03170e40B37d1',  #代币接收地址
        value=Decimal('1000001.123456') * (10**6))

    print("erc20_data:{}".format(erc20_data))

    tx = Transaction(
        nonce=420,
        gasprice=20 * (10**9),
        startgas=210000,
        to='0xeca059f3d6de135e520e789cdfeecbf5ceca3770',  #合约地址
        value=0,
        # data=b''
        data=unhexlify(erc20_data))

    tx.sender = '0x954d1a58c7abd4ac8ebe05f59191Cf718eb0cB89'  #源地址
    signed_tx = tx.sign(
        key=
        'DBBAD2A5682517E4FF095F948F721563231282CA4179AE0DFEA1C76143BA9607',  #源地址的私钥
        network_id=None)  # 4:Rinkeby

    rlp_data = rlp.encode(rlp.infer_sedes(signed_tx).serialize(signed_tx))

    print(hexlify(rlp_data))  #交易数据

    pass
Beispiel #12
0
def test_decode(name, in_out):
    msg_format = 'Test {} failed (decoded {} to {} instead of {})'
    rlp_string = in_out['out'].decode('hex')
    decoded = decode(rlp_string)
    assert decoded == evaluate(decode_lazy(rlp_string))
    expected = in_out['in']
    sedes = infer_sedes(expected)
    data = sedes.deserialize(decoded)
    assert data == decode(rlp_string, sedes)
    if data != expected:
        pytest.fail(msg_format.format(name, rlp_string, decoded, expected))
Beispiel #13
0
 def rlpdata(self, network_id: int = None):
     if network_id is None:
         rlpdata = rlp.encode(unsigned_tx_from_tx(self),
                              UnsignedTransaction)
         # rawhash = utils.sha3(rlpdata)
     else:
         assert 1 <= network_id < 2**63 - 18
         rlpdata = rlp.encode(
             rlp.infer_sedes(self).serialize(self)[:-3] +
             [network_id, b'', b''])
     return rlpdata
Beispiel #14
0
def test_inference():
    obj_sedes_pairs = (
        (5, big_endian_int),
        (0, big_endian_int),
        (-1, None),
        (b'', binary),
        (b'asdf', binary),
        (b'\xe4\xf6\xfc\xea\xe2\xfb', binary),
        ([], List()),
        ([1, 2, 3], List((big_endian_int, ) * 3)),
        ([[], b'asdf'], List(([], binary))),
    )

    for obj, sedes in obj_sedes_pairs:
        if sedes is not None:
            inferred = infer_sedes(obj)
            assert inferred == sedes
            sedes.serialize(obj)
        else:
            with pytest.raises(TypeError):
                infer_sedes(obj)
Beispiel #15
0
def test_inference():
    obj_sedes_pairs = (
        (5, big_endian_int),
        (0, big_endian_int),
        (-1, None),
        ('', binary),
        ('asdf', binary),
        ('\xe4\xf6\xfc\xea\xe2\xfb', binary),
        ([], List()),
        ([1, 2, 3], List((big_endian_int,) * 3)),
        ([[], 'asdf'], List(([], binary))),
    )

    for obj, sedes in obj_sedes_pairs:
        if sedes is not None:
            inferred = infer_sedes(obj)
            assert inferred == sedes
            sedes.serialize(obj)
        else:
            with pytest.raises(TypeError):
                infer_sedes(obj)
Beispiel #16
0
def get_tx_rawhash(tx, network_id=None):
    """Get a tx's rawhash.
       Copied from ethereum.transactions.Transaction.sign
    """
    if network_id is None:
        rawhash = utils.sha3(
            rlp.encode(tx, Transaction.exclude(['v', 'r', 's'])))
    else:
        assert 1 <= network_id < 2**63 - 18
        rlpdata = rlp.encode(
            rlp.infer_sedes(tx).serialize(tx)[:-3] + [network_id, b'', b''])
        rawhash = utils.sha3(rlpdata)
    return rawhash
Beispiel #17
0
def test_decode(name, in_out):
    msg_format = 'Test {} failed (decoded {} to {} instead of {})'
    rlp_string = utils.decode_hex(in_out['out'])
    decoded = decode(rlp_string)
    with pytest.raises(DecodingError):
        decode(rlp_string + b'\x00')
    assert decoded == decode(rlp_string + b'\x00', strict=False)

    assert decoded == evaluate(decode_lazy(rlp_string))
    expected = in_out['in']
    sedes = infer_sedes(expected)
    data = sedes.deserialize(decoded)
    assert data == decode(rlp_string, sedes)

    if data != expected:
        pytest.fail(msg_format.format(name, rlp_string, decoded, expected))
Beispiel #18
0
def test_decode(name, in_out):
    msg_format = 'Test {} failed (decoded {} to {} instead of {})'
    rlp_string = utils.decode_hex(in_out['out'])
    decoded = decode(rlp_string)
    with pytest.raises(DecodingError):
        decode(rlp_string + b'\x00')
    assert decoded == decode(rlp_string + b'\x00', strict=False)

    assert decoded == evaluate(decode_lazy(rlp_string))
    expected = in_out['in']
    sedes = infer_sedes(expected)
    data = sedes.deserialize(decoded)
    assert data == decode(rlp_string, sedes)

    if data != expected:
        pytest.fail(msg_format.format(name, rlp_string, decoded, expected))
Beispiel #19
0
    def sign(self, key, network_id=None):
        if network_id is None:
            rawhash = sha3(rlp.encode(self, UnsignedBlock))
        else:
            assert 1 <= network_id < 2**63 - 18
            rlpdata = rlp.encode(
                rlp.infer_sedes(self).serialize(self)[:-3] +
                [network_id, b'', b''])
            rawhash = sha3(rlpdata)

        key = normalize_key(key)
        self.v, self.r, self.s = ecsign(rawhash, key)
        if network_id is not None:
            self.v += 8 + network_id * 2

        self._signer = privtoaddr(key)
        return self
Beispiel #20
0
    def sign(self, key, network_id=None):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if network_id is None:
            rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))
        else:
            assert 1 <= network_id < 2**63 - 18
            rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[
                                 :-3] + [network_id, b'', b''])
            rawhash = utils.sha3(rlpdata)

        key = normalize_key(key)

        self.v, self.r, self.s = ecsign(rawhash, key)
        if network_id is not None:
            self.v += 8 + network_id * 2

        self._sender = utils.privtoaddr(key)
        return self
    def sign(self, key, network_id=None):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if network_id is None:
            rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))
        else:
            assert 1 <= network_id < 2**63 - 18
            rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[
                                 :-3] + [network_id, b'', b''])
            rawhash = utils.sha3(rlpdata)

        key = normalize_key(key)

        self.v, self.r, self.s = ecsign(rawhash, key)
        if network_id is not None:
            self.v += 8 + network_id * 2

        self._sender = utils.privtoaddr(key)
        return self
Beispiel #22
0
def test_serializable_sedes_inference(type_1_a, type_1_b, type_2):
    assert infer_sedes(type_1_a) == RLPType1
    assert infer_sedes(type_1_b) == RLPType1
    assert infer_sedes(type_2) == RLPType2