Exemplo n.º 1
0
    def test_big_integer_div(self):
        b1 = BigInteger(55055055055055)
        b2 = BigInteger(55055055)

        b3 = b1 / b2
        self.assertIsInstance(b3, BigInteger)
        self.assertEqual(b3, 1000000)
Exemplo n.º 2
0
    def test_4(self):

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='Boolean')

        self.assertEqual(fn.ReturnType, 1)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(1))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=True)

        self.assertEqual(fn.ReturnType, 1)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(1))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=1)

        self.assertEqual(fn.ReturnType, 1)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(1))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='1')

        self.assertEqual(fn.ReturnType, 1)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(1))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=b'1')

        self.assertEqual(fn.ReturnType, 1)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(1))
Exemplo n.º 3
0
    def test_big_integer_frombytes(self):
        b1 = BigInteger(8972340892734890723)
        ba = b1.ToByteArray()

        b2 = BigInteger.FromBytes(ba)
        self.assertEqual(b1, b2)
        self.assertTrue(b1.Equals(b2))
Exemplo n.º 4
0
    def test_3(self):

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=0)

        self.assertEqual(fn.ReturnType, 0)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(0))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=False)

        self.assertEqual(fn.ReturnType, 0)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(0))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='0')

        self.assertEqual(fn.ReturnType, 0)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(0))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=b'0')

        self.assertEqual(fn.ReturnType, 0)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(0))

        fn = FunctionCode(script=b'abcd',
                          param_list=[],
                          return_type='Signature')

        self.assertEqual(fn.ReturnType, 0)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(0))
Exemplo n.º 5
0
    def test_2(self):

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='ff')

        self.assertEqual(fn.ReturnType, 255)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(255))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=b'ff')

        self.assertEqual(fn.ReturnType, 255)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(255))

        fn = FunctionCode(script=b'abcd',
                          param_list=[],
                          return_type=bytearray(b'\xff'))

        self.assertEqual(fn.ReturnType, 255)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(255))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=255)

        self.assertEqual(fn.ReturnType, 255)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(255))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='Void')

        self.assertEqual(fn.ReturnType, 255)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(255))
Exemplo n.º 6
0
    def test_big_integer_float(self):
        b1 = BigInteger(5505.001)
        b2 = BigInteger(55055.999)

        b3 = b1 + b2

        self.assertIsInstance(b3, BigInteger)
        self.assertEqual(b3, 60560)
Exemplo n.º 7
0
    def test_big_integer_mul(self):
        b1 = BigInteger(55055055055055)
        b2 = BigInteger(55055055055)

        b3 = b1 * b2

        self.assertIsInstance(b3, BigInteger)
        self.assertEqual(b3, 3031059087112109081053025)
Exemplo n.º 8
0
    def test_big_integer_add(self):
        b1 = BigInteger(10)
        b2 = BigInteger(20)

        b3 = b1 + b2

        self.assertIsInstance(b3, BigInteger)
        self.assertEqual(b3, 30)
Exemplo n.º 9
0
    def test_big_integer_sub(self):
        b1 = BigInteger(5505505505505505050505)
        b2 = BigInteger(5505505505505505000000)

        b3 = b1 - b2

        self.assertIsInstance(b3, BigInteger)
        self.assertEqual(b3, 50505)
Exemplo n.º 10
0
    def GetHashCodeBytes(self):
        """
        Get the hash code in bytes.

        Returns:
            bytes:
        """
        bigint = BigInteger(self.GetHashCode())
        return bigint.ToByteArray()
Exemplo n.º 11
0
    def test_big_integer_div2(self):
        b1 = BigInteger(41483775933600000000)
        b2 = BigInteger(414937759336)

        b3 = b1 / b2
        b4 = b1 // b2
        self.assertIsInstance(b3, BigInteger)
        self.assertEqual(b3, 99975899)
        self.assertEqual(b4, b3)
Exemplo n.º 12
0
    def test_negative_shifting(self):
        # C#'s BigInteger changes a left shift with a negative shift index,
        # to a right shift with a positive index.

        b1 = BigInteger(8)
        b2 = BigInteger(-3)
        # shift against BigInteger
        self.assertEqual(1, b1 << b2)
        # shift against integer
        self.assertEqual(1, b1 << -3)

        # the same as above but for right shift
        self.assertEqual(64, b1 >> b2)
        self.assertEqual(64, b1 >> -3)
Exemplo n.º 13
0
    def Blockchain_GetHeader(self, engine: ExecutionEngine):
        data = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()

        header = None

        if len(data) <= 5:

            height = BigInteger.FromBytes(data)

            if Blockchain.Default() is not None:

                header = Blockchain.Default().GetHeaderBy(height_or_hash=height)

            elif height == 0:

                header = Blockchain.GenesisBlock().Header

        elif len(data) == 32:

            hash = UInt256(data=data)

            if Blockchain.Default() is not None:

                header = Blockchain.Default().GetHeaderBy(height_or_hash=hash)

            elif hash == Blockchain.GenesisBlock().Hash:

                header = Blockchain.GenesisBlock().Header

        engine.CurrentContext.EvaluationStack.PushT(StackItem.FromInterface(header))
        return True
Exemplo n.º 14
0
 def GetBigInteger(self):
     try:
         b = BigInteger(int.from_bytes(self._value, 'little', signed=True))
         return b
     except Exception as e:
         pass
     return self._value
Exemplo n.º 15
0
    def test_7(self):

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='String')

        self.assertEqual(fn.ReturnType, 7)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(7))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='7')

        self.assertEqual(fn.ReturnType, 7)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(7))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=b'07')

        self.assertEqual(fn.ReturnType, 7)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(7))
Exemplo n.º 16
0
def GatherLoadedContractParams(args, script):
    if len(args) < 5:
        raise Exception("please specify contract properties like {needs_storage} {needs_dynamic_invoke} {is_payable} {params} {return_type}")
    params = parse_param(args[3], ignore_int=True, prefer_hex=False)

    if type(params) is str:
        params = params.encode('utf-8')

    try:
        for p in binascii.unhexlify(params):
            if p == ContractParameterType.Void.value:
                raise ValueError("Void is not a valid input parameter type")
    except binascii.Error:
        pass

    return_type = BigInteger(ContractParameterType.FromString(args[4]).value)

    needs_storage = bool(parse_param(args[0]))
    needs_dynamic_invoke = bool(parse_param(args[1]))
    is_payable = bool(parse_param(args[2]))

    contract_properties = 0

    if needs_storage:
        contract_properties += ContractPropertyState.HasStorage

    if needs_dynamic_invoke:
        contract_properties += ContractPropertyState.HasDynamicInvoke

    if is_payable:
        contract_properties += ContractPropertyState.Payable

    out = generate_deploy_script(script, contract_properties=contract_properties, return_type=return_type, parameter_list=params)

    return out
Exemplo n.º 17
0
def parse_param(p, wallet=None, ignore_int=False, prefer_hex=True, parse_addr=True):
    # first, we'll try to parse an array
    try:
        items = eval(p, {"__builtins__": {'list': list}}, {})
        if len(items) > 0 and type(items) is list:

            parsed = []
            for item in items:
                parsed.append(parse_param(item, wallet, parse_addr=parse_addr))
            return parsed

    except Exception as e:
        #        print("Could not eval items as array %s " % e)
        pass

    if not ignore_int:
        try:
            val = int(p)
            out = BigInteger(val)
            return out
        except Exception as e:
            pass

    try:
        val = eval(p, {"__builtins__": {'bytearray': bytearray, 'bytes': bytes, 'list': list}}, {})
        if type(val) is bytearray:
            return val
        elif type(val) is bytes:
            # try to unhex
            try:
                val = binascii.unhexlify(val)
            except Exception as e:
                pass
            # now it should be unhexxed no matter what, and we can hex it
            return val.hex().encode('utf-8')
        elif type(val) is bool:
            return val

    except Exception as e:
        pass

    if type(p) is str:

        if wallet is not None:
            for na in wallet.NamedAddr:
                if na.Title == p:
                    return bytearray(na.ScriptHash)

        # check for address strings like 'ANE2ECgA6YAHR5Fh2BrSsiqTyGb5KaS19u' and
        # convert them to a bytearray
        if parse_addr and len(p) == 34 and p[0] == 'A':
            addr = Helper.AddrStrToScriptHash(p).Data
            return addr

        if prefer_hex:
            return binascii.hexlify(p.encode('utf-8'))
        else:
            return p.encode('utf-8')

    return p
Exemplo n.º 18
0
def TestBuild(script,
              invoke_args,
              wallet,
              plist='05',
              ret='05',
              dynamic=False,
              invoke_attrs=None,
              owners=None,
              snapshot=None):
    properties = ContractPropertyState.HasStorage

    if dynamic:
        properties += ContractPropertyState.HasDynamicInvoke

    if not isinstance(ret, bytearray):
        ret = bytearray(binascii.unhexlify(str(ret).encode('utf-8')))

    script = generate_deploy_script(script,
                                    contract_properties=int(properties),
                                    parameter_list=plist,
                                    return_type=BigInteger.FromBytes(ret))

    return test_deploy_and_invoke(script,
                                  invoke_args,
                                  wallet,
                                  invoke_attrs=invoke_attrs,
                                  owners=owners,
                                  snapshot=snapshot)
Exemplo n.º 19
0
    def Blockchain_GetBlock(self, engine: ExecutionEngine):
        data = engine.CurrentContext.EvaluationStack.Pop()

        if data:
            data = data.GetByteArray()
        else:
            return False

        block = None

        if len(data) <= 5:
            height = BigInteger.FromBytes(data)

            if Blockchain.Default() is not None:

                block = Blockchain.Default().GetBlockByHeight(height)

            elif height == 0:

                block = Blockchain.GenesisBlock()

        elif len(data) == 32:

            hash = UInt256(data=data).ToBytes()

            if Blockchain.Default() is not None:

                block = Blockchain.Default().GetBlockByHash(hash=hash)

            elif hash == Blockchain.GenesisBlock().Hash:

                block = Blockchain.GenesisBlock().Header

        engine.CurrentContext.EvaluationStack.PushT(StackItem.FromInterface(block))
        return True
Exemplo n.º 20
0
    def test_5(self):

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='Array')

        self.assertEqual(fn.ReturnType, 16)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(16))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='10')

        self.assertEqual(fn.ReturnType, 16)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(16))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=b'10')

        self.assertEqual(fn.ReturnType, 16)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(16))
Exemplo n.º 21
0
def generate_deploy_script(script,
                           name='test',
                           version='test',
                           author='test',
                           email='test',
                           description='test',
                           contract_properties=0,
                           return_type=BigInteger(255),
                           parameter_list=[]):
    sb = ScriptBuilder()

    plist = parameter_list
    try:
        plist = bytearray(binascii.unhexlify(parameter_list))
    except Exception as e:
        pass

    sb.push(binascii.hexlify(description.encode('utf-8')))
    sb.push(binascii.hexlify(email.encode('utf-8')))
    sb.push(binascii.hexlify(author.encode('utf-8')))
    sb.push(binascii.hexlify(version.encode('utf-8')))
    sb.push(binascii.hexlify(name.encode('utf-8')))
    sb.push(contract_properties)
    sb.push(return_type)
    sb.push(plist)
    sb.WriteVarData(script)
    sb.EmitSysCall("Neo.Contract.Create")
    script = sb.ToArray()

    return script
Exemplo n.º 22
0
    def test_dunder_methods(self):
        b1 = BigInteger(1)
        b2 = BigInteger(2)
        b3 = BigInteger(3)

        self.assertEqual(abs(b1), 1)
        self.assertEqual(b1 % 1, 0)
        self.assertEqual(-b1, -1)
        self.assertEqual(str(b1), "1")
        self.assertEqual(b3 // b2, 1)

        right_shift = b3 >> b1
        self.assertEqual(right_shift, 1)
        self.assertIsInstance(right_shift, BigInteger)

        left_shift = b1 << b3
        self.assertEqual(left_shift, 8)
        self.assertIsInstance(left_shift, BigInteger)
Exemplo n.º 23
0
    def test_1(self):

        fn = FunctionCode()

        self.assertEqual(fn.ReturnType, 255)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(255))

        self.assertEqual(fn.ParameterList, [])
        self.assertEqual(fn.HasDynamicInvoke, False)
        self.assertEqual(fn.HasStorage, False)
Exemplo n.º 24
0
    def New(value):
        typ = type(value)

        if typ is BigInteger:
            return Integer(value)
        elif typ is int:
            return Integer(BigInteger(value))
        elif typ is float:
            return Integer(BigInteger(int(value)))
        elif typ is bool:
            return Boolean(value)
        elif typ is bytearray or typ is bytes:
            return ByteArray(value)
        elif typ is list:
            return Array(value)
        elif typ is str:
            return ByteArray(bytearray(value.encode()))
        # raise TypeError(f"{typ} is an invalid StackItem type")
        return value
Exemplo n.º 25
0
def LoadContract(path, needs_storage, needs_dynamic_invoke, is_payable,
                 params_str, return_type):
    params = parse_param(params_str, ignore_int=True, prefer_hex=False)

    if type(params) is str:
        params = params.encode('utf-8')

    try:
        for p in binascii.unhexlify(params):
            if p == ContractParameterType.Void.value:
                raise ValueError("Void is not a valid input parameter type")
    except binascii.Error:
        pass

    rtype = BigInteger(ContractParameterType.FromString(return_type).value)

    contract_properties = 0

    if needs_storage:
        contract_properties += ContractPropertyState.HasStorage

    if needs_dynamic_invoke:
        contract_properties += ContractPropertyState.HasDynamicInvoke

    if is_payable:
        contract_properties += ContractPropertyState.Payable

    if '.avm' not in path:
        raise ValueError("Please load a compiled .avm file")

    script = None
    with open(path, 'rb') as f:

        content = f.read()

        try:
            content = binascii.unhexlify(content)
        except Exception as e:
            pass

        script = content

    if script:
        try:
            plist = bytearray(binascii.unhexlify(params))
        except Exception as e:
            plist = bytearray(b'\x10')
        function_code = FunctionCode(script=script,
                                     param_list=bytearray(plist),
                                     return_type=rtype,
                                     contract_properties=contract_properties)

        return function_code
    else:
        raise Exception(f"Error loading contract for path {path}")
Exemplo n.º 26
0
    def test_6(self):

        fn = FunctionCode(script=b'abcd',
                          param_list=[],
                          return_type='ByteArray')

        self.assertEqual(fn.ReturnType, 5)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(5))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='05')

        self.assertEqual(fn.ReturnType, 5)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(5))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=b'05')

        self.assertEqual(fn.ReturnType, 5)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(5))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=5)

        self.assertEqual(fn.ReturnType, 5)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(5))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type='5')

        self.assertEqual(fn.ReturnType, 5)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(5))

        fn = FunctionCode(script=b'abcd', param_list=[], return_type=b'5')

        self.assertEqual(fn.ReturnType, 5)
        self.assertEqual(fn.ReturnTypeBigInteger, BigInteger(5))
Exemplo n.º 27
0
    def ToVM(self):
        """
        Used for turning a ContractParameter item into somethnig consumable by the VM

        Returns:

        """
        if self.Type == ContractParameterType.String:
            return str(self.Value).encode('utf-8').hex()
        elif self.Type == ContractParameterType.Integer and isinstance(
                self.Value, int):
            return BigInteger(self.Value)
        return self.Value
Exemplo n.º 28
0
    def test_big_integer_sign(self):
        b1 = BigInteger(3)
        b2 = BigInteger(0)
        b3 = BigInteger(-4)
        self.assertEqual(b1.Sign, 1)
        self.assertEqual(b2.Sign, 0)
        self.assertEqual(b3.Sign, -1)

        c1 = BigInteger(-100)
        c1_bytes = c1.ToByteArray()

        c2 = BigInteger.FromBytes(c1_bytes, signed=True)
        self.assertEqual(c2.Sign, -1)

        c2_unsigned = BigInteger.FromBytes(c1_bytes, signed=False)
        self.assertEqual(c2_unsigned.Sign, 1)
Exemplo n.º 29
0
    def test_big_integer_modulo(self):
        b1 = BigInteger(860593)
        b2 = BigInteger(-201)
        self.assertEqual(112, b1 % b2)

        b1 = BigInteger(20195283520469175757)
        b2 = BigInteger(1048576)
        self.assertEqual(888269, b1 % b2)

        b1 = BigInteger(
            -18224909727634776050312394179610579601844989529623334093909233530432892596607
        )
        b2 = BigInteger(14954691977398614017)
        self.assertEqual(-3100049211437790421, b1 % b2)

        b3 = BigInteger.from_bytes(bytearray(b'+K\x05\xbe\xaai\xfa\xd4'),
                                   'little',
                                   signed=True)
        self.assertEqual(b3, b1 % b2)
Exemplo n.º 30
0
    def DeserializeStackItem(reader):
        stype = reader.ReadUInt8()
        if stype == StackItemType.ByteArray:
            return ByteArray(reader.ReadVarBytes())
        elif stype == StackItemType.Boolean:
            return Boolean(ord(reader.ReadByte()))
        elif stype == StackItemType.Integer:
            return Integer(
                BigInteger.FromBytes(reader.ReadVarBytes(), signed=True))
        elif stype == StackItemType.Array:
            stack_item = Array()
            count = reader.ReadVarInt()
            while count > 0:
                count -= 1
                stack_item.Add(StackItem.DeserializeStackItem(reader))
            return stack_item
        elif stype == StackItemType.Struct:
            stack_item = Struct(value=None)
            count = reader.ReadVarInt()
            while count > 0:
                count -= 1
                stack_item.Add(StackItem.DeserializeStackItem(reader))
            return stack_item
        elif stype == StackItemType.Map:
            stack_item = Map()
            count = reader.ReadVarInt()
            while count > 0:
                count -= 1
                key = StackItem.DeserializeStackItem(reader)
                val = StackItem.DeserializeStackItem(reader)
                stack_item.SetItem(key, val)
            return stack_item

        else:
            raise ValueError(
                "Could not deserialize stack item with type: %s " % stype)