コード例 #1
0
ファイル: StateReader.py プロジェクト: xizho10/neo-python
    def Blockchain_GetHeader(self, engine):
        data = engine.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.EvaluationStack.PushT(StackItem.FromInterface(header))
        return True
コード例 #2
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
コード例 #3
0
def GatherLoadedContractParams(args, script):
    if len(args) < 5:
        raise Exception(
            "please specify contract properties like {params} {return_type} {needs_storage} {needs_dynamic_invoke} {is_payable}"
        )
    params = parse_param(args[0], ignore_int=True, prefer_hex=False)

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

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

    needs_storage = bool(parse_param(args[2]))
    needs_dynamic_invoke = bool(parse_param(args[3]))
    is_payable = bool(parse_param(args[4]))

    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
コード例 #4
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
コード例 #5
0
ファイル: BuildNRun.py プロジェクト: sgangoly/neo-python
def TestBuild(script,
              invoke_args,
              wallet,
              plist='05',
              ret='05',
              dynamic=False,
              invoke_attrs=None,
              owners=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)
コード例 #6
0
def LoadContract(args):
    if len(args) < 5:
        print(
            "please specify contract to load like such: 'import contract {path} {params} {return_type} {needs_storage} {needs_dynamic_invoke}'"
        )
        return

    path = args[0]
    params = parse_param(args[1], ignore_int=True, prefer_hex=False)

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

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

    needs_storage = bool(parse_param(args[3]))
    needs_dynamic_invoke = bool(parse_param(args[4]))

    contract_properties = 0

    if needs_storage:
        contract_properties += ContractPropertyState.HasStorage

    if needs_dynamic_invoke:
        contract_properties += ContractPropertyState.HasDynamicInvoke

    script = None

    if '.py' in path:
        print("Please load a compiled .avm file")
        return False

    with open(path, 'rb') as f:

        content = f.read()

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

        script = content

    if script is not None:

        plist = params

        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=return_type,
                                     contract_properties=contract_properties)

        return function_code

    print("error loading contract for path %s" % path)
    return None
コード例 #7
0
    def __init__(self,
                 event_type,
                 event_payload,
                 contract_hash,
                 block_number,
                 tx_hash,
                 execution_success=False,
                 test_mode=False):
        super(NotifyEvent, self).__init__(event_type, event_payload,
                                          contract_hash, block_number, tx_hash,
                                          execution_success, test_mode)

        self.is_standard_notify = False

        plen = len(self.event_payload)
        if plen > 0:
            self.notify_type = self.event_payload[0]
            empty = UInt160(data=bytearray(20))
            try:
                if plen == 4 and self.notify_type in [
                        NotifyType.TRANSFER, NotifyType.APPROVE
                ]:
                    if self.event_payload[1] is None:
                        self.addr_from = empty
                    else:
                        self.addr_from = UInt160(
                            data=self.event_payload[1]) if len(
                                self.event_payload[1]) == 20 else empty
                    self.addr_to = UInt160(data=self.event_payload[2]) if len(
                        self.event_payload[2]) == 20 else empty
                    self.amount = int(BigInteger.FromBytes(
                        event_payload[3])) if isinstance(
                            event_payload[3], bytes) else int(event_payload[3])
                    self.is_standard_notify = True

                elif plen == 3 and self.notify_type == NotifyType.REFUND:
                    self.addr_to = UInt160(data=self.event_payload[1]) if len(
                        self.event_payload[1]) == 20 else empty
                    self.amount = int(BigInteger.FromBytes(
                        event_payload[2])) if isinstance(
                            event_payload[2], bytes) else int(event_payload[2])
                    self.addr_from = self.contract_hash
                    self.is_standard_notify = True
            except Exception as e:
                logger.info("Could not determine notify event: %s %s" %
                            (e, self.event_payload))
コード例 #8
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)
コード例 #9
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)

        #        logger.debug("Could not create stack item for vaule %s %s " % (typ, value))
        return value
コード例 #10
0
    def __init__(self, event_type, event_payload, contract_hash, block_number, tx_hash, execution_success=False, test_mode=False):
        super(NotifyEvent, self).__init__(event_type, event_payload, contract_hash, block_number, tx_hash, execution_success, test_mode)

        self.is_standard_notify = False

        if self.event_payload.Type == ContractParameterType.Array and len(self.event_payload.Value) > 0:

            payload = self.event_payload.Value
            plen = len(payload)

            self.notify_type = payload[0].Value

            empty = UInt160(data=bytearray(20))
            try:
                if plen == 4 and self.notify_type in [NotifyType.TRANSFER, NotifyType.APPROVE]:
                    if payload[1].Value is None:
                        self.addr_from = empty
                        logger.debug("Using contract addr from address %s " % self.event_payload)
                    elif payload[1].Value is False:
                        logger.debug("Using contract addr from address %s " % self.event_payload)
                        self.addr_from = empty
                    else:
                        self.addr_from = UInt160(data=payload[1].Value) if len(payload[1].Value) == 20 else empty
                    self.addr_to = UInt160(data=payload[2].Value) if len(payload[2].Value) == 20 else empty
                    self.amount = int(BigInteger.FromBytes(payload[3].Value)) if isinstance(payload[3].Value, (bytes, bytearray)) else int(payload[3].Value)
                    self.is_standard_notify = True

                elif self.notify_type == NotifyType.REFUND and plen >= 3:  # Might have more arguments
                    self.addr_to = UInt160(data=payload[1].Value) if len(payload[1].Value) == 20 else empty
                    self.amount = int(BigInteger.FromBytes(payload[2].Value)) if isinstance(payload[2].Value, (bytes, bytearray)) else int(payload[2].Value)
                    self.addr_from = self.contract_hash
                    self.is_standard_notify = True

                elif self.notify_type == NotifyType.MINT and plen == 3:
                    self.addr_to = UInt160(data=payload[1].Value) if len(payload[1].Value) == 20 else empty
                    self.amount = int(BigInteger.FromBytes(payload[2].Value)) if isinstance(payload[2].Value, (bytes, bytearray)) else int(payload[2].Value)
                    self.addr_from = self.contract_hash
                    self.is_standard_notify = True

            except Exception as e:
                logger.debug("Could not determine notify event: %s %s" % (e, self.event_payload))

        elif self.event_payload.Type == ContractParameterType.String:
            self.notify_type = self.event_payload.Value
コード例 #11
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)
コード例 #12
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}")
コード例 #13
0
def parse_param(p, wallet=None, ignore_int=False, prefer_hex=True):

    # first, we'll try to parse an array

    try:
        items = eval(p)
        if len(items) > 0 and type(items) is list:

            parsed = []
            for item in items:
                parsed.append(parse_param(item, wallet))
            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)

        if type(val) is bytearray:
            return val.hex()

        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 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
コード例 #14
0
    def test_should_persist_mint_event(self):
        sc = NotifyEvent(
            SmartContractEvent.RUNTIME_NOTIFY,
            [b'mint', self.addr_to, BigInteger(123000)], self.contract_hash,
            91349, self.event_tx, True, False)

        ndb = NotificationDB.instance()
        ndb.on_smart_contract_event(sc)

        self.assertEqual(len(ndb.current_events), 1)
        ndb.on_persist_completed(None)
コード例 #15
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
コード例 #16
0
ファイル: simple_recorder.py プロジェクト: wy/neo-futures
def sc_notify(event):
    logger.info("SmartContract Runtime.Notify event: %s", event)

    # Make sure that the event payload list has at least one element.
    if not len(event.event_payload):
        return

    # The event payload list has at least one element. As developer of the smart contract
    # you should know what data-type is in the bytes, and how to decode it. In this example,
    # it's just a string, so we decode it with utf-8:
    byte_array = event.event_payload[0]
    tuple = bytes(byte_array).split(b'SEPARATOR')
    ts = BigInteger.FromBytes(tuple[0])
    n_correct = BigInteger.FromBytes(tuple[1])
    prediction = BigInteger.FromBytes(tuple[2])

    logger.info("TS: {}".format(ts))
    logger.info("n_correct: {}".format(n_correct))
    logger.info("prediction: {}".format(prediction))
    with open("../../webapp/CMC_Blockchain.txt", "w+") as f:
        f.write("{},{},{}".format(ts, n_correct, prediction))
コード例 #17
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))
コード例 #18
0
def create_tx(contract_hash, address_from, address_to, tnc_amount, gas_change,
              input_txid, preIndex):

    nep5TokenId = get_nep5token_id(contract_hash)
    scripthash_from = ToScriptHash(address_from)
    scripthash_to = ToScriptHash(address_to)
    f8amount = amount_from_string(nep5TokenId, tnc_amount)
    f8amount_change = Fixed8.TryParse(gas_change, require_positive=True)
    assetId = get_asset_id("gas")
    preHash = UInt256(data=binascii.unhexlify(hex_reverse(input_txid)))

    input = TransactionInput(prevHash=preHash, prevIndex=preIndex)
    output = TransactionOutput(AssetId=assetId,
                               Value=f8amount_change,
                               script_hash=scripthash_from)

    tx = InvocationTransaction(outputs=[output], inputs=[input])
    tx.Version = 1
    context = ContractParametersContext(tx)
    tx.scripts = context.GetScripts()

    invoke_args = [
        nep5TokenId.ScriptHash, 'transfer',
        [
            bytearray.fromhex(hex_reverse(scripthash_from.ToString())),
            bytearray.fromhex(hex_reverse(scripthash_to.ToString())),
            BigInteger(f8amount)
        ]
    ]
    sb = ScriptBuilder()
    invoke_args.reverse()
    for item in invoke_args[:2]:
        if type(item) is list:
            item.reverse()
            listlength = len(item)
            for listitem in item:
                sb.push(listitem)
            sb.push(listlength)
            sb.Emit(PACK)
        else:
            sb.push(binascii.hexlify(item.encode()))

    sb.EmitAppCall(nep5TokenId.ScriptHash.ToArray())

    op_data = sb.ToArray().decode()
    tx.Script = binascii.unhexlify(op_data)
    tx_data = get_tx_data(tx)[:-2]
    print("tx_data:", tx_data)
    signstr = binascii.hexlify(
        Crypto.Sign(message=tx_data, private_key=private_key)).decode()
    rawtx_data = tx_data + "014140" + signstr + "2321" + public_key + "ac"
    return rawtx_data
コード例 #19
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)
コード例 #20
0
    def test_4_should_persist(self):

        ndb = NotificationDB.instance()

        self.assertEqual(len(ndb.current_events), 0)
        sc = NotifyEvent(
            SmartContractEvent.RUNTIME_NOTIFY,
            [b'transfer', self.addr_to, self.addr_from,
             BigInteger(123000)], self.contract_hash, 91349, self.event_tx,
            True, True)

        ndb.on_smart_contract_event(sc)

        self.assertEqual(len(ndb.current_events), 0)
コード例 #21
0
def sc_log(event):
    logger.info(Wallet.AddressVersion)
    logger.info("SmartContract Runtime.Notify event: %s", event)

    # Make sure that the event payload list has at least one element.
    if not len(event.event_payload):
        return

    # Make sure not test mode
    if event.test_mode:
        return

    # The event payload list has at least one element. As developer of the smart contract
    # you should know what data-type is in the bytes, and how to decode it. In this example,
    # it's just a string, so we decode it with utf-8:
    logger.info("- payload part 1: %s", event.event_payload[0])
    game = event.event_payload[0]
    #args = ['ef254dc68e36de6a3a5d2de59ae1cdff3887938f','submit',[game,2,wallet_hash]]
    #x = random.randint(1, 9)
    latest_price = BigInteger(float(buffer[-1][1]) * 1000)

    live_ts = BigInteger(buffer[-1][0])
    remainder = live_ts % normalisation
    ts = live_ts - remainder

    args = [
        smart_contract_hash, 'submit_prediction',
        [game, ts, latest_price, wallet_arr]
    ]
    #bytearray(b'\xceG\xc5W\xb8\xb8\x906S\x06F\xa6\x18\x9b\x8c\xb1\x94\xc4\xda\xad')]]

    # Start a thread with custom code
    d = threading.Thread(target=test_invoke_contract, args=[args])
    d.setDaemon(
        True
    )  # daemonizing the thread will kill it when the main thread is quit
    d.start()
コード例 #22
0
    def sc_log(event):
        logger.info("SmartContract Runtime.Notify event: %s", event)

        # Make sure that the event payload list has at least one element.
        if not len(event.event_payload):
            return

        # Make sure not test mode
        if event.test_mode:
            return

        # The event payload list has at least one element. As developer of the smart contract
        # you should know what data-type is in the bytes, and how to decode it. In this example,
        # it's just a string, so we decode it with utf-8:
        logger.info("- payload part 1: %s", event.event_payload[0])
        price = BigInteger.FromBytes(event.event_payload[0])
        USD_price = float(price) / 1000.0
        print(USD_price)
コード例 #23
0
def construct_opdata(addressFrom,addressTo,value,assetId):
    op_data=""
    value=binascii.hexlify(BigInteger(value*pow(10,8)).ToByteArray()).decode()
    scripthash_from=ToScriptHash(addressFrom).ToString2()
    scripthash_to=ToScriptHash(addressTo).ToString2()
    method=binascii.hexlify("transfer".encode()).decode()
    invoke_args=[value,scripthash_to,scripthash_from]
    for item in invoke_args:
        op_data+="".join([int_to_hex(len(item)/2),item])

    op_data+="53"     #PUSH3
    op_data+="c1"     #PACK
    op_data+=int_to_hex(len(method)/2)
    op_data+=method
    op_data+="67"                      #APPCALL
    op_data+=hex_reverse(assetId)
    op_data+= "f1"                      # maybe THROWIFNOT

    return op_data
コード例 #24
0
def create_opdata(address_from, address_to, value, contract_hash):
    op_data = ""
    value = int(value)
    value = binascii.hexlify(BigInteger(value).ToByteArray()).decode()
    scripthash_from = ToAddresstHash(address_from).ToString2()
    scripthash_to = ToAddresstHash(address_to).ToString2()
    method = binascii.hexlify("transfer".encode()).decode()
    invoke_args = [value, scripthash_to, scripthash_from]
    for item in invoke_args:
        op_data += "".join([int_to_hex(len(item) / 2), item])

    op_data += "53"  # PUSH3
    op_data += "c1"  # PACK
    op_data += int_to_hex(len(method) / 2)
    op_data += method
    op_data += "67"  # APPCALL
    op_data += hex_reverse(contract_hash)
    op_data += "f1"  # maybe THROWIFNOT

    return op_data
コード例 #25
0
    def DeserializeStackItem(reader):
        stype = reader.ReadUInt8()
        if stype == StackItemType.ByteArray:
            return ByteArray(reader.ReadVarBytes())
        elif stype == StackItemType.Boolean:
            return Boolean(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:
            logger.error("Could not deserialize stack item with type: %s " %
                         stype)
        return None
コード例 #26
0
    def Blockchain_GetBlock(self, engine):

        data = engine.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.EvaluationStack.PushT(StackItem.FromInterface(block))
        return True
コード例 #27
0
 def GetBigInteger(self):
     return BigInteger(
         int.from_bytes(self.GetByteArray(), 'little', signed=True))
コード例 #28
0
ファイル: faucet.py プロジェクト: jhwinter/nep5-faucet
    def _make_tx(self, address_to):
        """
        Function that creates the parameters for the NEP-5 transfer function and then calls it,
        returning the transaction info

        :param address_to: address to send the tokens to
        :return:
            transaction info
        """
        drip_amount = BigInteger(10000)
        amount = BigInteger(
            drip_amount * 100000000
        )  # must multiply by Fixed8.D and must be BigInteger object
        self.invoke_args.clear()
        self.params.clear(
        )  # make sure that invoke_args and params lists are empty
        scripthash_from = Helper.AddrStrToScriptHash(
            address=self.faucet_wallet_addr).ToArray()
        scripthash_to = address_to

        self.invoke_args.append(scripthash_from)
        self.invoke_args.append(scripthash_to)
        self.invoke_args.append(amount)
        self.params = [
            self.token_script_hash.encode('utf-8'), self.OPERATION,
            self.invoke_args
        ]
        nonce = struct.pack('>i',
                            int(time()))  # convert the int to a big endian int
        # the int(time()) is the time in seconds since the epoch (01/01/1970 for UNIX systems)
        # the nonce was used to append to the TransactionAttribute so that each transaction has slightly
        # different data. Otherwise, each transaction would constantly be given the same transaction hash because
        # all of their parameters are the same
        # TransactionAttributeUsage.Remark is b'\xf0' = 240
        invoke_attributes = [
            TransactionAttribute(usage=TransactionAttributeUsage.Remark,
                                 data=nonce)
        ]
        # the following test invokes the contract (useful to ensure that noting is wrong)
        tx, fee, results, num_ops = TestInvokeContract(
            wallet=self.wallet,
            args=self.params,
            from_addr=self.faucet_wallet_addr,
            min_fee=Fixed8.Zero(),
            invoke_attrs=invoke_attributes)

        # the following is just used for logging info
        if tx is not None and results is not None:
            logger.info('\n------------------------')
            for item in results:
                logger.info(f'Results: {str(item)}')
                if not len(str(item)) % 2:
                    try:
                        logger.info(
                            f'Hex decode: {binascii.unhexlify(str(item))}')
                    except Exception:
                        logger.warning('Not hex encoded')
            logger.info(f'Invoke TX gas cost: {(tx.Gas.value / Fixed8.D)}')
            logger.info(f'Invoke TX Fee: {(fee.value / Fixed8.D)}')
            logger.info('Relaying invocation tx now')
            logger.info('------------------------\n')

        # invoke the contract
        self.sent_tx = InvokeContract(wallet=self.wallet,
                                      tx=tx,
                                      fee=Fixed8.Zero(),
                                      from_addr=self.faucet_wallet_addr)
        sleep(
            3
        )  # allow a few seconds for the contract to be invoked and return the tx info is actually passed
        return self.sent_tx
コード例 #29
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
コード例 #30
0
 def ReturnTypeBigInteger(self):
     return BigInteger(self.ReturnType)