Exemplo n.º 1
0
class BoaTest(WalletFixtureTestCase):

    dirname = None

    FIXTURE_REMOTE_LOC = 'https://s3.us-east-2.amazonaws.com/cityofzion/fixtures/fixtures_v7.tar.gz'
    FIXTURE_FILENAME = 'fixtures/empty_fixture.tar.gz'

    wallet_1_script_hash = UInt160(
        data=b'S\xefB\xc8\xdf!^\xbeZ|z\xe8\x01\xcb\xc3\xac/\xacI)')

    wallet_1_addr = 'APRgMZHZubii29UXF9uFa6sohrsYupNAvx'

    _wallet1 = None

    @classmethod
    def setUpClass(cls):

        cls.dirname = '/'.join(os.path.abspath(__file__).split('/')[:-3])

        super(BoaTest, cls).setUpClass()

    @classmethod
    def GetWallet1(cls, recreate=False):
        if cls._wallet1 is None or recreate:
            cls._wallet1 = UserWallet.Open(BoaTest.wallet_1_dest(),
                                           to_aes_key(BoaTest.wallet_1_pass()))
        return cls._wallet1
Exemplo n.º 2
0
def hex2address(input):
    try:
        output = Crypto.ToAddress(
            UInt160(data=binascii.unhexlify(bytearray(input.encode("utf8")))))
    except:
        output = None
    return output
Exemplo n.º 3
0
    def Blockchain_GetAccount(self, engine):
        hash = UInt160(data=engine.EvaluationStack.Pop().GetByteArray())
        address = Crypto.ToAddress(hash).encode('utf-8')

        account = self.Accounts.GetOrAdd(address, new_instance=AccountState(script_hash=hash))
        engine.EvaluationStack.PushT(StackItem.FromInterface(account))
        return True
Exemplo n.º 4
0
    def CheckDynamicInvoke(self):
        cx = self.CurrentContext

        if cx.InstructionPointer >= len(cx.Script):
            return True

        opcode = cx.NextInstruction

        if opcode == APPCALL:
            opreader = cx.OpReader
            # read the current position of the stream
            start_pos = opreader.stream.tell()

            # normal app calls are stored in the op reader
            # we read ahead past the next instruction 1 the next 20 bytes
            script_hash = opreader.ReadBytes(21)[1:]

            # then reset the position
            opreader.stream.seek(start_pos)

            for b in script_hash:
                # if any of the bytes are greater than 0, this is a normal app call
                if b > 0:
                    return True

            # if this is a dynamic app call, we will arrive here
            # get the current executing script hash
            current = UInt160(data=cx.ScriptHash())
            current_contract_state = self._Table.GetContractState(current.ToBytes())

            # if current contract state cant do dynamic calls, return False
            return current_contract_state.HasDynamicInvoke

        return True
Exemplo n.º 5
0
    def Contract_Destroy(self, engine):
        hash = UInt160(data=engine.CurrentContext.ScriptHash())

        contract = self._contracts.TryGet(hash.ToBytes())

        if contract is not None:

            self._contracts.Remove(hash.ToBytes())

            if contract.HasStorage:

                for pair in self._storages.Find(hash.ToBytes()):
                    self._storages.Remove(pair.Key)

        self.events_to_dispatch.append(
            SmartContractEvent(SmartContractEvent.CONTRACT_DESTROY,
                               ContractParameter(
                                   ContractParameterType.InteropInterface,
                                   contract),
                               hash,
                               Blockchain.Default().Height + 1,
                               engine.ScriptContainer.Hash
                               if engine.ScriptContainer else None,
                               test_mode=engine.testMode))
        return True
Exemplo n.º 6
0
    def execute(self, arguments):
        wallet = PromptData.Wallet

        if len(arguments) != 1:
            print("Please specify the required parameter")
            return False

        hash_string = arguments[0]
        try:
            script_hash = UInt160.ParseString(hash_string)
        except Exception:
            # because UInt160 throws a generic exception. Should be fixed in the future
            print("Invalid script hash")
            return False

        # try to find token and collect some data
        try:
            token = ModelNEP5Token.get(ContractHash=script_hash)
        except peewee.DoesNotExist:
            print(f"Could not find a token with script_hash {arguments[0]}")
            return False

        success = wallet.DeleteNEP5Token(script_hash)
        if success:
            print(f"Token {token.Symbol} with script_hash {arguments[0]} deleted")
        else:
            # probably unreachable to due token check earlier. Better safe than sorrow
            print(f"Could not find a token with script_hash {arguments[0]}")

        return success
Exemplo n.º 7
0
    def execute(self, arguments):
        item = get_arg(arguments)
        if item is not None:
            if item.lower() == "all":
                contracts = Blockchain.Default().ShowAllContracts()
                contractlist = []
                for contract in contracts:
                    state = Blockchain.Default().GetContract(contract.decode('utf-8')).ToJson()
                    contract_dict = {state['name']: state['hash']}
                    contractlist.append(contract_dict)
                print(json.dumps(contractlist, indent=4))
                return contractlist

            try:
                hash = UInt160.ParseString(item).ToBytes()
            except Exception:
                print("Could not find contract from args: %s" % arguments)
                return

            contract = Blockchain.Default().GetContract(hash)

            if contract is not None:
                contract.DetermineIsNEP5()
                print(json.dumps(contract.ToJson(), indent=4))
                return contract.ToJson()
            else:
                print("Contract %s not found" % item)
                return
        else:
            print('Please specify the required parameter')
            return
    def get_by_contract(self, contract_hash):
        """
        Look up a set of notifications by the contract they are associated with
        Args:
            contract_hash (UInt160 or str): hash of contract for notifications to be retreived

        Returns:
            list: a list of notifications
        """
        hash = contract_hash
        if isinstance(contract_hash, str) and len(contract_hash) == 40:
            hash = UInt160.ParseString(contract_hash)

        if not isinstance(hash, UInt160):
            raise Exception("Incorrect address format")

        contractlist_snapshot = self.db.prefixed_db(
            NotificationPrefix.PREFIX_CONTRACT).snapshot()
        results = []

        for val in contractlist_snapshot.iterator(prefix=bytes(hash.Data),
                                                  include_key=False):
            if len(val) > 4:
                try:
                    event = SmartContractEvent.FromByteArray(val)
                    results.append(event)
                except Exception as e:
                    logger.error("could not parse event: %s %s" % (e, val))
        return results
Exemplo n.º 9
0
    def Storage_Delete(self, engine):

        context = engine.EvaluationStack.Pop().GetInterface()

        if not self.CheckStorageContext(context):
            return False

        key = engine.EvaluationStack.Pop().GetByteArray()

        storage_key = StorageKey(script_hash=context.ScriptHash, key=key)

        keystr = key
        if len(key) == 20:
            keystr = Crypto.ToAddress(UInt160(data=key))

        self.events_to_dispatch.append(
            SmartContractEvent(SmartContractEvent.STORAGE_DELETE, [keystr],
                               context.ScriptHash,
                               Blockchain.Default().Height + 1,
                               engine.ScriptContainer.Hash
                               if engine.ScriptContainer else None,
                               test_mode=engine.testMode))

        self._storages.Remove(storage_key.ToArray())

        return True
    def Runtime_Notify(self, engine):

        state = engine.EvaluationStack.Pop()

        # Build and emit smart contract event
        state_py = stack_item_to_py(state)
        payload = state_py if isinstance(state_py, list) else [
            state_py
        ]  # Runtime.Notify payload must be a list

        args = NotifyEventArgs(
            engine.ScriptContainer,
            UInt160(data=engine.CurrentContext.ScriptHash()), payload)

        message = payload[0] if len(payload) > 0 else payload
        engine.write_log(str(message))

        self.notifications.append(args)

        if settings.emit_notify_events_on_sc_execution_error:
            # emit Notify events even if the SC execution might fail.
            tx_hash = engine.ScriptContainer.Hash
            height = Blockchain.Default().Height
            success = None
            self.events_to_dispatch.append(
                NotifyEvent(SmartContractEvent.RUNTIME_NOTIFY, args.State,
                            args.ScriptHash, height, tx_hash, success,
                            engine.testMode))

        return True
Exemplo n.º 11
0
    def ToScriptHash(self, address):
        """
        Retrieve the script_hash based from an address.

        Args:
            address (str): a base58 encoded address.

        Raises:
            ValuesError: if an invalid address is supplied or the coin version is incorrect
            Exception: if the address string does not start with 'A' or the checksum fails

        Returns:
            UInt160: script hash.
        """
        if len(address) == 34:
            if address[0] == 'A':
                data = b58decode(address)
                if data[0] != self.AddressVersion:
                    raise ValueError('Not correct Coin Version')

                checksum = Crypto.Default().Hash256(data[:21])[:4]
                if checksum != data[21:]:
                    raise Exception('Address format error')
                return UInt160(data=data[1:21])
            else:
                raise Exception('Address format error')
        else:
            raise ValueError('Not correct Address, wrong length.')
Exemplo n.º 12
0
def ImportWatchAddr(wallet, addr):

    if wallet is None:
        print("Please open a wallet")
        return False

    script_hash = None
    try:
        script_hash = wallet.ToScriptHash(addr)
    except Exception as e:
        pass

    if not script_hash:
        try:
            data = bytearray(binascii.unhexlify(addr.encode('utf-8')))
            data.reverse()
            script_hash = UInt160(data=data)
        except Exception as e:
            pass

    if script_hash:
        wallet.AddWatchOnly(script_hash)
        print("added watch address")
    else:
        print("incorrect format for watch address")
Exemplo n.º 13
0
class UserWalletTestCaseBase(WalletFixtureTestCase):
    wallet_1_script_hash = UInt160(data=b'\x1c\xc9\xc0\\\xef\xff\xe6\xcd\xd7\xb1\x82\x81j\x91R\xec!\x8d.\xc0')
    wallet_1_addr = 'AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3'
    _wallet1 = None

    wallet_2_script_hash = UInt160(data=b'\x08t/\\P5\xac-\x0b\x1c\xb4\x94tIyBu\x7f1*')
    wallet_2_addr = 'AGYaEi3W6ndHPUmW7T12FFfsbQ6DWymkEm'
    _wallet2 = None

    import_watch_addr = UInt160(data=b'\x08t/\\P5\xac-\x0b\x1c\xb4\x94tIyBu\x7f1*')
    watch_addr_str = 'AGYaEi3W6ndHPUmW7T12FFfsbQ6DWymkEm'

    @property
    def GAS(self):
        return Blockchain.Default().SystemCoin().Hash

    @property
    def NEO(self):
        return Blockchain.Default().SystemShare().Hash

    @classmethod
    def GetWallet1(cls, recreate=False):
        if cls._wallet1 is None or recreate:
            shutil.copyfile(cls.wallet_1_path(), cls.wallet_1_dest())
            cls._wallet1 = UserWallet.Open(UserWalletTestCase.wallet_1_dest(),
                                           to_aes_key(UserWalletTestCase.wallet_1_pass()))
        return cls._wallet1

    @classmethod
    def GetWallet2(cls, recreate=False):
        if cls._wallet2 is None or recreate:
            shutil.copyfile(cls.wallet_2_path(), cls.wallet_2_dest())
            cls._wallet2 = UserWallet.Open(UserWalletTestCase.wallet_2_dest(),
                                           to_aes_key(UserWalletTestCase.wallet_2_pass()))
        return cls._wallet2

    @classmethod
    def OpenWallet1(cls):
        PromptData.Wallet = cls.GetWallet1(recreate=True)

    @classmethod
    def OpenWallet2(cls):
        PromptData.Wallet = cls.GetWallet2(recreate=True)

    @classmethod
    def tearDown(cls):
        PromptData.Wallet = None
Exemplo n.º 14
0
class BoaFixtureTest(WalletFixtureTestCase):

    dirname = None

    FIXTURE_REMOTE_LOC = 'https://s3.us-east-2.amazonaws.com/cityofzion/fixtures/fixtures_v5.tar.gz'
    FIXTURE_FILENAME = './fixtures/fixtures_v5.tar.gz'

    wallet_1_script_hash = UInt160(data=b'S\xefB\xc8\xdf!^\xbeZ|z\xe8\x01\xcb\xc3\xac/\xacI)')

    wallet_1_addr = 'APRgMZHZubii29UXF9uFa6sohrsYupNAvx'

    _wallet1 = None

    wallet_2_script_hash = UInt160(data=b'4\xd0=k\x80TF\x9e\xa8W\x83\xfa\x9eIv\x0b\x9bs\x9d\xb6')

    wallet_2_addr = 'ALb8FEhEmtSqv97fuNVuoLmcmrSKckffRf'

    _wallet2 = None

    wallet_3_script_hash = UInt160(data=b'\xa6\xc5\x9d\xeb\xf0\xd7(\xbd\x14\x89\xcd\xb9\xd9{\xd1\x90\xcb\x0b\xdch')

    wallet_3_addr = 'AWygZ1B5c3GDiLL6u5bHSVU45Ya1SVGX9P'

    _wallet3 = None

    @classmethod
    def setUpClass(cls):
        super(BoaFixtureTest, cls).setUpClass()
        cls.dirname = '/'.join(os.path.abspath(__file__).split('/')[:-3])

    @classmethod
    def GetWallet1(cls, recreate=False):
        if cls._wallet1 is None or recreate:
            cls._wallet1 = UserWallet.Open(BoaFixtureTest.wallet_1_dest(), to_aes_key(BoaFixtureTest.wallet_1_pass()))
        return cls._wallet1

    @classmethod
    def GetWallet2(cls, recreate=False):
        if cls._wallet2 is None or recreate:
            cls._wallet2 = UserWallet.Open(BoaFixtureTest.wallet_2_dest(), to_aes_key(BoaFixtureTest.wallet_2_pass()))
        return cls._wallet2

    @classmethod
    def GetWallet3(cls, recreate=False):
        if cls._wallet3 is None or recreate:
            cls._wallet3 = UserWallet.Open(BoaFixtureTest.wallet_3_dest(), to_aes_key(BoaFixtureTest.wallet_3_pass()))
        return cls._wallet3
def create_raw_sc_method_call_tx(
    source_address,
    source_address_wif,
    smartcontract_scripthash,
    smartcontract_method,
    smartcontract_method_args,
):
    source_script_hash = address_to_scripthash(source_address)

    # start by creating a base InvocationTransaction
    # the inputs, outputs and Type do not have to be set anymore.
    invocation_tx = InvocationTransaction()

    # often times smart contract developers use the function ``CheckWitness`` to determine if the transaction is signed by somebody eligible of calling a certain method
    # in order to pass that check you want to add the corresponding script_hash as a transaction attribute (this is generally the script_hash of the public key you use for signing)
    # Note that for public functions like the NEP-5 'getBalance' and alike this would not be needed, but it doesn't hurt either
    invocation_tx.Attributes.append(
        TransactionAttribute(usage=TransactionAttributeUsage.Script,
                             data=source_script_hash))

    smartcontract_scripthash = UInt160.ParseString(smartcontract_scripthash)
    # next we need to build a 'script' that gets executed against the smart contract.
    # this is basically the script that calls the entry point of the contract with the necessary parameters
    sb = ScriptBuilder()

    # call the method on the contract (assumes contract address is a NEP-5 token)
    sb.EmitAppCallWithOperationAndArgs(
        smartcontract_scripthash,
        smartcontract_method,
        smartcontract_method_args,
    )
    invocation_tx.Script = binascii.unhexlify(sb.ToArray())

    # at this point we've build our unsigned transaction and it's time to sign it before we get the raw output that we can send to the network via RPC
    # we need to create a Wallet instance for helping us with signing
    wallet = UserWallet.Create('path',
                               to_aes_key('mypassword'),
                               generate_default_key=False)

    # if you have a WIF use the following
    # this WIF comes from the `neo-test1-w.wallet` fixture wallet
    private_key = KeyPair.PrivateKeyFromWIF(source_address_wif)

    # if you have a NEP2 encrypted key use the following instead
    # private_key = KeyPair.PrivateKeyFromNEP2("NEP2 key string", "password string")

    # we add the key to our wallet
    wallet.CreateKey(private_key)

    # and now we're ready to sign
    context = ContractParametersContext(invocation_tx)
    wallet.Sign(context)

    invocation_tx.scripts = context.GetScripts()
    raw_tx = invocation_tx.ToArray()

    print(raw_tx)

    return raw_tx.decode()
Exemplo n.º 16
0
    def ReadUInt160(self):
        """
        Read a UInt160 value from the stream.

        Returns:
            UInt160:
        """
        return UInt160(data=bytearray(self.ReadBytes(20)))
Exemplo n.º 17
0
 def test_get_contract_state_0x(self):
     contract_hash = '0x%s' % UInt160(data=bytearray(
         b'\x11\xc4\xd1\xf4\xfb\xa6\x19\xf2b\x88p\xd3n:\x97s\xe8tp[')
                                      ).ToString()
     req = self._gen_rpc_req("getcontractstate", params=[contract_hash])
     mock_req = mock_request(json.dumps(req).encode("utf-8"))
     res = json.loads(self.app.home(mock_req))
     self.assertEqual(res['result']['code_version'], '3')
Exemplo n.º 18
0
    def Storage_GetReadOnlyContext(self, engine: ExecutionEngine):
        hash = UInt160(data=engine.CurrentContext.ScriptHash())
        context = StorageContext(script_hash=hash, read_only=True)

        engine.CurrentContext.EvaluationStack.PushT(
            StackItem.FromInterface(context))

        return True
Exemplo n.º 19
0
 def Blockchain_GetContract(self, engine):
     hash = UInt160(data=engine.EvaluationStack.Pop().GetByteArray())
     contract = self.Contracts.TryGet(hash.ToBytes())
     if contract is None:
         engine.EvaluationStack.PushT(bytearray(0))
     else:
         engine.EvaluationStack.PushT(StackItem.FromInterface(contract))
     return True
Exemplo n.º 20
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))
Exemplo n.º 21
0
    def Storage_GetContext(self, engine):

        hash = UInt160(data=engine.CurrentContext.ScriptHash())
        context = StorageContext(script_hash=hash)

        engine.EvaluationStack.PushT(StackItem.FromInterface(context))

        return True
Exemplo n.º 22
0
 def get_by_contract(self, request, contract_hash):
     request.setHeader('Content-Type', 'application/json')
     try:
         hash = UInt160.ParseString(contract_hash)
         notifications = self.notif.get_by_contract(hash)
     except Exception as e:
         logger.info("Could not get notifications for contract %s " % contract_hash)
         return self.format_message("Could not get notifications for contract hash %s because %s" % (contract_hash, e))
     return self.format_notifications(request, notifications)
Exemplo n.º 23
0
    def test_accountstate_ToJson(self):

        hash = UInt160(data=self.ac2_h)
        account = AccountState(script_hash=hash)

        res = account.ToJson()

        self.assertEqual(res['address'], account.Address)
        self.assertEqual(res['script_hash'], str(hash))
Exemplo n.º 24
0
    def Blockchain_GetContract(self, engine):
        hash = UInt160(data=engine.EvaluationStack.Pop().GetByteArray())
        contract = None

        if Blockchain.Default() is not None:
            contract = Blockchain.Default().GetContract(hash)

        engine.EvaluationStack.PushT(StackItem.FromInterface(contract))
        return True
    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
    def test_wallet_import_contract_addr(self):
        # test with no wallet open
        with patch('sys.stdout', new=StringIO()) as mock_print:
            args = ['import', 'contract_addr', 'contract_hash', 'pubkey']
            res = CommandWallet().execute(args)
            self.assertIsNone(res)
            self.assertIn("open a wallet", mock_print.getvalue())

        self.OpenWallet1()

        # test with not enough arguments (must have 2 arguments)
        with patch('sys.stdout', new=StringIO()) as mock_print:
            args = ['import', 'contract_addr']
            res = CommandWallet().execute(args)
            self.assertIsNone(res)
            self.assertIn("specify the required parameters", mock_print.getvalue())

        # test with too many arguments (must have 2 arguments)
        with patch('sys.stdout', new=StringIO()) as mock_print:
            args = ['import', 'contract_addr', 'arg1', 'arg2', 'arg3']
            res = CommandWallet().execute(args)
            self.assertIsNone(res)
            self.assertIn("specify the required parameters", mock_print.getvalue())

        # test with invalid contract hash
        with patch('sys.stdout', new=StringIO()) as mock_print:
            args = ['import', 'contract_addr', 'invalid_contract_hash', '03cbb45da6072c14761c9da545749d9cfd863f860c351066d16df480602a2024c6']
            res = CommandWallet().execute(args)
            self.assertIsNone(res)
            self.assertIn("Invalid contract hash", mock_print.getvalue())

        # test with valid contract hash but that doesn't exist
        with patch('sys.stdout', new=StringIO()) as mock_print:
            args = ['import', 'contract_addr', '31730cc9a1844891a3bafd1aa929000000000000', '03cbb45da6072c14761c9da545749d9cfd863f860c351066d16df480602a2024c6']
            res = CommandWallet().execute(args)
            self.assertIsNone(res)
            self.assertIn("Could not find contract", mock_print.getvalue())

        # test with invalid pubkey
        with patch('sys.stdout', new=StringIO()) as mock_print:
            args = ['import', 'contract_addr', '31730cc9a1844891a3bafd1aa929a4142860d8d3', 'invalid_pubkey']
            res = CommandWallet().execute(args)
            self.assertIsNone(res)
            self.assertIn("Invalid pubkey", mock_print.getvalue())

        # test with valid arguments
        contract_hash = UInt160.ParseString('31730cc9a1844891a3bafd1aa929a4142860d8d3')

        with patch('sys.stdout', new=StringIO()) as mock_print:
            self.assertIsNone(PromptData.Wallet.GetContract(contract_hash))

            args = ['import', 'contract_addr', '31730cc9a1844891a3bafd1aa929a4142860d8d3', '03cbb45da6072c14761c9da545749d9cfd863f860c351066d16df480602a2024c6']
            res = CommandWallet().execute(args)
            self.assertIsInstance(res, Contract)
            self.assertTrue(PromptData.Wallet.GetContract(contract_hash))
            self.assertIn("Added contract address", mock_print.getvalue())
Exemplo n.º 27
0
    def Contract_Create(self, engine):

        script = engine.EvaluationStack.Pop().GetByteArray()

        if len(script) > 1024 * 1024:
            return False

        param_list = engine.EvaluationStack.Pop().GetByteArray()
        if len(param_list) > 252:
            return False

        return_type = int(engine.EvaluationStack.Pop().GetBigInteger())

        contract_properties = int(engine.EvaluationStack.Pop().GetBigInteger())

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        name = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        code_version = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        author = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 252:
            return False
        email = engine.EvaluationStack.Pop().GetByteArray()

        if len(engine.EvaluationStack.Peek().GetByteArray()) > 65536:
            return False

        description = engine.EvaluationStack.Pop().GetByteArray()

        hash = Crypto.ToScriptHash(script, unhex=False)

        contract = self._contracts.TryGet(hash.ToBytes())

        if contract is None:

            code = FunctionCode(script=script, param_list=param_list, return_type=return_type, contract_properties=contract_properties)

            contract = ContractState(code, contract_properties, name, code_version, author, email, description)

            self._contracts.GetAndChange(code.ScriptHash().ToBytes(), contract)

            self._contracts_created[hash.ToBytes()] = UInt160(data=engine.CurrentContext.ScriptHash())

        engine.EvaluationStack.PushT(StackItem.FromInterface(contract))

        # logger.info("*****************************************************")
        # logger.info("CREATED CONTRACT %s " % hash.ToBytes())
        # logger.info("*****************************************************")
        return True
Exemplo n.º 28
0
 def process_hold_created_event(self, payload):
     if len(payload) == 4:
         vin = payload[0]
         from_addr = UInt160(data=payload[1])
         to_addr = UInt160(data=payload[2])
         amount = int.from_bytes(payload[3], 'little')
         v_index = int.from_bytes(vin[32:], 'little')
         v_txid = UInt256(data=vin[0:32])
         if to_addr.ToBytes() in self._contracts.keys(
         ) and from_addr in self._watch_only:
             hold, created = VINHold.get_or_create(
                 Index=v_index,
                 Hash=v_txid.ToBytes(),
                 FromAddress=from_addr.ToBytes(),
                 ToAddress=to_addr.ToBytes(),
                 Amount=amount,
                 IsComplete=False)
             if created:
                 self.LoadHolds()
Exemplo n.º 29
0
    def test_5_addr_conv(self):

        wallet = self.GetWallet1()
        addr = UInt160(data=b'\xec\xa8\xfc\xf9Nz*\x7f\xc3\xfdT\xae\x0e\xd3\xd3MR\xec%\x90')

        addr_str = 'AdMDZGto3xWozB1HSjjVv27RL3zUM8LzpV'

        to_uint = wallet.ToScriptHash(addr_str)

        self.assertEqual(to_uint, addr)
Exemplo n.º 30
0
def address_to_scripthash(address):
    data = b58decode(address)
    if len(data) != 25:
        raise ValueError('Not correct Address, wrong length.')
    if data[0] != settings.ADDRESS_VERSION:
        raise ValueError('Not correct Coin Version')
    checksum = Crypto.Default().Hash256(data[:21])[:4]
    if checksum != data[21:]:
        raise Exception('Address format error')
    return UInt160(data=data[1:21]).ToBytes()