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

        if not self.Completed:
            raise Exception("Signature Context not complete")

        scripts = []

        for i in range(0, len(self.ScriptHashes)):

            item = self.ContextItems[self.ScriptHashes[i].ToBytes()]
            print("GETTING SCRIPTS, item is %s " % item)

            sb = ScriptBuilder()

            plist = list(item.ContractParameters)
            plist.reverse()

            for p in plist:
                sb.push(p.Value)

            vscript = bytearray(0)

            if item.Script is not None:
                vscript = item.Script

            witness = Witness(
                invocation_script=sb.ToArray(),
                verification_script=vscript
            )

            scripts.append(witness)


        return scripts
Ejemplo n.º 2
0
    def Query(self):
        """
        Query the smart contract for its token information (name, symbol, decimals).

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.

        Returns:
            None: if the NEP5Token instance `Name` is already set.
            True: if all information was retrieved.
            False: if information retrieval failed.
        """
        if self.name is not None:
            # don't query twice
            return

        sb = ScriptBuilder()
        sb.EmitAppCallWithOperation(self.ScriptHash, 'name')
        sb.EmitAppCallWithOperation(self.ScriptHash, 'symbol')
        sb.EmitAppCallWithOperation(self.ScriptHash, 'decimals')

        engine = ApplicationEngine.Run(sb.ToArray())
        results = engine.EvaluationStack.Items

        try:
            self.name = results[0].GetString()
            self.symbol = results[1].GetString()
            self.decimals = results[2].GetBigInteger()
            if len(self.name) > 1 and self.name != 'Stack Item' \
                    and len(self.symbol) > 1 and self.symbol != 'Stack Item'\
                    and self.decimals < 10:
                return True
        except Exception as e:
            logger.info("could not query token %s " % e)
        return False
Ejemplo n.º 3
0
    def GetBalance(self, wallet, address, as_string=False):
        """
        Get the token balance.

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.
            address (str): public address of the account to get the token balance of.
            as_string (bool): whether the return value should be a string. Default is False, returning an integer.

        Returns:
            int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed.
        """
        addr = parse_param(address, wallet)
        if isinstance(addr, UInt160):
            addr = addr.Data
        sb = ScriptBuilder()
        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr])

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        try:
            val = results[0].GetBigInteger()
            precision_divisor = pow(10, self.decimals)
            balance = Decimal(val) / Decimal(precision_divisor)
            if as_string:
                formatter_str = '.%sf' % self.decimals
                balance_str = format(balance, formatter_str)
                return balance_str
            return balance
        except Exception as e:
            logger.error("could not get balance: %s " % e)
            traceback.print_stack()

        return 0
Ejemplo n.º 4
0
def runRawTransaction(operation, args):
    invocation_tx = InvocationTransaction()

    smartcontract_scripthash = UInt160.ParseString(CONTRACT_HASH)
    sb = ScriptBuilder()
    sb.EmitAppCallWithOperationAndArgs(
        smartcontract_scripthash,
        operation,
        args)
    invocation_tx.Script = binascii.unhexlify(sb.ToArray())

    wallet = UserWallet.Create(
        'neo-privnet.wallet', to_aes_key('coz'), generate_default_key=False)
    private_key = KeyPair.PrivateKeyFromWIF(
        "KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr")

    wallet.CreateKey(private_key)
    context = ContractParametersContext(invocation_tx)
    wallet.Sign(context)

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

    payload = {"jsonrpc": "2.0", "id": 1,
               "method": "sendrawtransaction",
               "params": [raw_tx.decode("ascii")]}

    res = requests.post(
        "http://neo-nodes:30333/testNeoConnection", json=payload)
    print("received POST result")
    print(res.status_code)
    result = res.text
    print(result)
    return result
Ejemplo n.º 5
0
    def Transfer(self, wallet, from_addr, to_addr, amount, tx_attributes=None):
        """
        Transfer a specified amount of the NEP5Token to another address.

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.
            from_addr (str): public address of the account to transfer the given amount from.
            to_addr (str): public address of the account to transfer the given amount to.
            amount (int): quantity to send.
            tx_attributes (list): a list of TransactionAtribute objects.

        Returns:
            tuple:
                InvocationTransaction: the transaction.
                int: the transaction fee.
                list: the neo VM evaluationstack results.
        """
        if not tx_attributes:
            tx_attributes = []

        sb = ScriptBuilder()
        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'transfer',
                                           [parse_param(from_addr, wallet), parse_param(to_addr, wallet),
                                            parse_param(amount)])

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [], from_addr=from_addr, invoke_attrs=tx_attributes)

        return tx, fee, results
Ejemplo n.º 6
0
    def Query(self, wallet):
        """
        Query the smart contract for its token information (name, symbol, decimals).

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.

        Returns:
            None: if the NEP5Token instance `Name` is already set.
            True: if all information was retrieved.
            False: if information retrieval failed.
        """
        if self.name is not None:
            # don't query twice
            return

        sb = ScriptBuilder()
        sb.EmitAppCallWithOperation(self.ScriptHash, 'name')
        sb.EmitAppCallWithOperation(self.ScriptHash, 'symbol')
        sb.EmitAppCallWithOperation(self.ScriptHash, 'decimals')

        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        try:
            self.name = results[0].GetString()
            self.symbol = results[1].GetString()
            self.decimals = results[2].GetBigInteger()
            return True
        except Exception as e:
            logger.error("could not query token %s " % e)
        return False
Ejemplo n.º 7
0
    def CreateMultiSigRedeemScript(m, publicKeys):

        if m < 1:
            raise Exception(
                "Minimum required signature count is 1, specified {}.".format(
                    m))

        if m > len(publicKeys):
            raise Exception(
                "Invalid public key count. Minimum required signatures is bigger than supplied public keys count."
            )

        if len(publicKeys) > 1024:
            raise Exception(
                "Supplied public key count ({}) exceeds maximum of 1024.".
                format(len(publicKeys)))

        sb = ScriptBuilder()
        sb.push(m)

        pkeys = [point for point in publicKeys]
        pkeys.sort()
        keys = [p.encode_point().decode() for p in pkeys]

        for key in keys:
            sb.push(key)

        sb.push(len(publicKeys))
        sb.add(CHECKMULTISIG)

        return sb.ToArray()
Ejemplo n.º 8
0
def generate_deploy_script(script,
                           name='test',
                           version='test',
                           author='test',
                           email='test',
                           description='test',
                           needs_storage=False,
                           return_type=b'\xff',
                           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.WriteBool(needs_storage)
    sb.push(return_type)
    sb.push(plist)
    sb.WriteVarData(script)
    sb.EmitSysCall("Neo.Contract.Create")
    script = sb.ToArray()

    return script
Ejemplo n.º 9
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
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()
Ejemplo n.º 11
0
    def VerifyScripts(verifiable):
        """
        Verify the scripts of the provided `verifiable` object.

        Args:
            verifiable (neo.IO.Mixins.VerifiableMixin):

        Returns:
            bool: True if verification is successful. False otherwise.
        """
        try:
            hashes = verifiable.GetScriptHashesForVerifying()
        except Exception as e:
            logger.error("couldn't get script hashes %s " % e)
            return False

        if len(hashes) != len(verifiable.Scripts):
            return False

        blockchain = GetBlockchain()

        for i in range(0, len(hashes)):
            verification = verifiable.Scripts[i].VerificationScript

            if len(verification) == 0:
                sb = ScriptBuilder()
                sb.EmitAppCall(hashes[i].Data)
                verification = sb.ToArray()

            else:
                verification_hash = Crypto.ToScriptHash(verification,
                                                        unhex=False)
                if hashes[i] != verification_hash:
                    return False

            state_reader = GetStateReader()
            engine = ApplicationEngine(TriggerType.Verification, verifiable,
                                       blockchain, state_reader, Fixed8.Zero())
            engine.LoadScript(verification, False)
            invoction = verifiable.Scripts[i].InvocationScript
            engine.LoadScript(invoction, True)

            try:
                success = engine.Execute()
                state_reader.ExecutionCompleted(engine, success)
            except Exception as e:
                state_reader.ExecutionCompleted(engine, False, e)

            if engine.EvaluationStack.Count != 1 or not engine.EvaluationStack.Pop(
            ).GetBoolean():
                Helper.EmitServiceEvents(state_reader)
                return False

            Helper.EmitServiceEvents(state_reader)

        return True
Ejemplo n.º 12
0
def GetWithdrawalBalance(wallet, contract_hash, from_addr, asset_type):
    sb = ScriptBuilder()
    sb.EmitAppCallWithOperationAndData(contract_hash, 'balance_%s' % asset_type, from_addr)

    try:
        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        return results[0].GetBigInteger()
    except Exception as e:
        print("could not get balance: %s " % e)
Ejemplo n.º 13
0
def TestInvokeContract(wallet, args, withdrawal_tx=None, from_addr=None,
                       min_fee=DEFAULT_MIN_FEE, invoke_attrs=None, owners=None):
    BC = GetBlockchain()

    contract = BC.GetContract(args[0])

    if contract:
        #
        params = args[1:] if len(args) > 1 else []

        params, neo_to_attach, gas_to_attach = PromptUtils.get_asset_attachments(params)
        params, parse_addresses = PromptUtils.get_parse_addresses(params)
        params.reverse()

        if '--i' in params:
            params = []
            for index, iarg in enumerate(contract.Code.ParameterList):
                param, abort = PromptUtils.gather_param(index, iarg)
                if abort:
                    return None, None, None, None, False
                params.append(param)
            params.reverse()

        sb = ScriptBuilder()

        for p in params:
            process_params(sb, p, wallet, parse_addresses)

        sb.EmitAppCall(contract.Code.ScriptHash().Data)

        out = sb.ToArray()

        outputs = []

        if neo_to_attach:
            output = TransactionOutput(AssetId=Blockchain.SystemShare().Hash,
                                       Value=neo_to_attach,
                                       script_hash=contract.Code.ScriptHash(),
                                       )
            outputs.append(output)

        if gas_to_attach:
            output = TransactionOutput(AssetId=Blockchain.SystemCoin().Hash,
                                       Value=gas_to_attach,
                                       script_hash=contract.Code.ScriptHash())

            outputs.append(output)

        return test_invoke(out, wallet, outputs, withdrawal_tx, from_addr, min_fee, invoke_attrs=invoke_attrs, owners=owners)

    else:

        print("Contract %s not found" % args[0])

    return None, None, None, None, False
Ejemplo n.º 14
0
def example2():
    source_address = "AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3"
    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()

    # Since we are building a raw transaction, we will add the raw_tx flag

    invocation_tx.raw_tx = True

    # 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))

    # 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
    smartcontract_scripthash = UInt160.ParseString(
        "31730cc9a1844891a3bafd1aa929a4142860d8d3")
    sb = ScriptBuilder()
    # call the NEP-5 `name` method on the contract (assumes contract address is a NEP-5 token)
    sb.EmitAppCallWithOperation(smartcontract_scripthash, 'name')
    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(
        "Ky94Rq8rb1z8UzTthYmy1ApbZa9xsKTvQCiuGUZJZbaDJZdkvLRV")

    # 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()

    return raw_tx
Ejemplo n.º 15
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
Ejemplo n.º 16
0
    def VerifyScripts(verifiable):

        try:
            hashes = verifiable.GetScriptHashesForVerifying()
        except Exception as e:
            logger.error("couldn't get script hashes %s " % e)
            return False

        if len(hashes) != len(verifiable.Scripts):
            return False

        state_reader = GetStateReader()
        blockchain = GetBlockchain()

        for i in range(0, len(hashes)):
            verification = verifiable.Scripts[i].VerificationScript

            if len(verification) == 0:
                #                logger.info("VERIFICATION IS 0, EMITTING APP CALL")
                sb = ScriptBuilder()
                sb.EmitAppCall(hashes[i].Data)
                verification = sb.ToArray()

            else:
                verification_hash = Crypto.ToScriptHash(verification,
                                                        unhex=False)
                if hashes[i] != verification_hash:
                    return False

            engine = ApplicationEngine(TriggerType.Verification, verifiable,
                                       blockchain, state_reader, Fixed8.Zero())
            engine.LoadScript(verification, False)
            invoction = verifiable.Scripts[i].InvocationScript
            engine.LoadScript(invoction, True)

            try:
                success = engine.Execute()
                state_reader.ExecutionCompleted(engine, success)

            except Exception as e:
                state_reader.ExecutionCompleted(engine, False, e)

#            pdb.set_trace()
            if engine.EvaluationStack.Count != 1 or not engine.EvaluationStack.Pop(
            ).GetBoolean():
                return False

        return True
Ejemplo n.º 17
0
    def VerifyScripts(verifiable):

        try:
            hashes = verifiable.GetScriptHashesForVerifying()
        except Exception as e:
            print("couldng get script hashes %s " % e)
            return False

        if len(hashes) != len(verifiable.Scripts):
            print("hashes not same length as verifiable scripts")
            return False
        print("hello!!!! %s " % hashes)

        for i in range(0, len(hashes)):
            verification = verifiable.Scripts[i].VerificationScript

            print("verifying script: %s %s " % (hashes[i], verification))

            if len(verification) == 0:
                sb = ScriptBuilder()
                sb.EmitAppCall(hashes[i].Data)
                verification = sb.ToArray()

            else:
                if hashes[i] != verification:
                    print("hashes not equal to script hash!")
                    return False

            engine = ApplicationEngine(TriggerType.Verification, verifiable,
                                       GetBlockchain(), GetStateReader(),
                                       Fixed8.Zero())
            engine.LoadScript(verification, False)
            engine.LoadScript(verifiable.Scripts[i].InvocationScript, True)

            res = engine.Execute()
            if not res:
                print("engine did not execune")
                return False
            else:

                print("engine did execute!")

            if engine.EvaluationStack.Count != 1 or not engine.EvaluationStack.Pop(
            ).GetBoolean():
                print("stack not one, or stack false")
                return False

        return True
Ejemplo n.º 18
0
    def Query(self):
        """
        Query the smart contract for its token information (name, symbol, decimals).

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.

        Returns:
            None: if the NEP5Token instance `Name` is already set.
            True: if all information was retrieved.
            False: if information retrieval failed.
        """
        if self.name is not None:
            # don't query twice
            return

        sb = ScriptBuilder()
        sb.EmitAppCallWithOperation(self.ScriptHash, 'name')
        sb.EmitAppCallWithOperation(self.ScriptHash, 'symbol')
        sb.EmitAppCallWithOperation(self.ScriptHash, 'decimals')

        snapshot = GetBlockchain().Default()._db.createSnapshot().Clone()
        engine = None
        try:
            engine = ApplicationEngine.Run(snapshot,
                                           sb.ToArray(),
                                           exit_on_error=True,
                                           gas=Fixed8.FromDecimal(10.0),
                                           test_mode=False)
        except Exception as e:
            traceback.print_exc()
            pass

        if engine and len(engine.ResultStack.Items) == 3:
            results = engine.ResultStack.Items

            try:
                self.name = results[0].GetString()
                self.symbol = results[1].GetString()
                self.decimals = results[2].GetBigInteger()
                if len(self.name) > 1 and self.name != 'Stack Item' \
                        and len(self.symbol) > 1 and self.symbol != 'Stack Item' \
                        and self.decimals < 10:
                    return True
            except Exception as e:
                pass
        return False
Ejemplo n.º 19
0
def CancelWithdrawalHolds(wallet, contract_hash, require_password=True):
    wallet.LoadHolds()
    to_cancel = []
    for hold in wallet._holds:
        if hold.FromAddress == contract_hash:
            to_cancel.append(hold)
    if len(to_cancel) < 1:
        print("No holds to cancel")
        return

    sb = ScriptBuilder()
    for hold in to_cancel:
        sb.EmitAppCallWithOperationAndData(hold.InputHash, 'cancel_hold',
                                           hold.Vin)

    try:
        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        for i in results:
            if not i.GetBoolean():
                print("Error executing hold cleanup")
                return

        if require_password:
            print(
                "\n---------------------------------------------------------------"
            )
            print("Will cancel %s holds" % len(to_cancel))
            print("FEE IS %s " % fee.ToString())
            print("GAS IS %s " % tx.Gas.ToString())
            print(
                "------------------------------------------------------------------\n"
            )

            print("Enter your password to complete this request")

            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return

        result = InvokeContract(wallet, tx, fee)
        return result

    except Exception as e:
        print("could not cancel hold(s): %s " % e)
Ejemplo n.º 20
0
def CleanupCompletedHolds(wallet, require_password=True):

    completed = wallet.LoadCompletedHolds()

    if len(completed) < 1:
        print("No holds to cleanup")
        return False

    sb = ScriptBuilder()
    for hold in completed:
        sb.EmitAppCallWithOperationAndData(hold.InputHash, 'cleanup_hold',
                                           hold.Vin)

    try:
        tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [])

        for i in results:
            if not i.GetBoolean():
                print("Error executing hold cleanup")
                return False

        if require_password:
            print(
                "\n---------------------------------------------------------------"
            )
            print("Will cleanup %s holds" % len(completed))
            print("FEE IS %s " % fee.ToString())
            print("GAS IS %s " % tx.Gas.ToString())
            print(
                "------------------------------------------------------------------\n"
            )

            print("Enter your password to complete this request")

            passwd = prompt("[Password]> ", is_password=True)

            if not wallet.ValidatePassword(passwd):
                print("incorrect password")
                return

        result = InvokeContract(wallet, tx, fee)
        return result

    except Exception as e:
        print("could not cancel hold(s): %s " % e)
    return False
Ejemplo n.º 21
0
def generate_deploy_script(name, version, author, email, description,
                           needs_storage, return_type, parameter_list, script):
    sb = ScriptBuilder()

    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.WriteBool(needs_storage)
    sb.push(ord(return_type))
    sb.push(binascii.hexlify(parameter_list))
    sb.WriteVarData(script)
    sb.EmitSysCall("Neo.Contract.Create")

    script = sb.ToArray()

    return script
    def GetScripts(self):

        if not self.Completed:
            raise Exception("Signature Context not complete")

        scripts = []

        for i in range(0, len(self.ScriptHashes)):

            item = self.ContextItems[self.ScriptHashes[i].ToBytes()]

            sb = ScriptBuilder()

            plist = list(item.ContractParameters)
            plist.reverse()

            for p in plist:
                if type(p.Value) is list:
                    pa = p.Value
                    pa.reverse()
                    listlength = len(pa)
                    for listitem in pa:
                        sb.push(listitem)
                    sb.push(listlength)
                    sb.Emit(OpCode.PACK)
                else:
                    sb.push(p.Value)

            vscript = bytearray(0)

            if item.Script is not None:
                if type(item.Script) is str:
                    item.Script = item.Script.encode('utf-8')
                vscript = item.Script
#                logger.info("SCRIPT IS %s " % item.Script)

            witness = Witness(
                #                invocation_script='40fdb984faf0a400b6894c1ce5b317cf894ba3eb89b899cefda2ac307b278418b943534ad298884f9200dc4b7e1dc244db16c62a44a830a860060ec11d3e6e9717',
                invocation_script=sb.ToArray(),
                verification_script=vscript)

            scripts.append(witness)

        return scripts
Ejemplo n.º 23
0
    def GetScripts(self):

        if not self.Completed:
            raise Exception("Signature Context not complete")

        scripts = []

        for i in range(0, len(self.ScriptHashes)):

            item = self.ContextItems[self.ScriptHashes[i].ToBytes()]

            sb = ScriptBuilder()

            plist = list(item.ContractParameters)
            plist.reverse()

            for p in plist:
                if type(p.Value) is list:
                    pa = p.Value
                    pa.reverse()
                    listlength = len(pa)
                    for listitem in pa:
                        sb.push(listitem)
                    sb.push(listlength)
                    sb.Emit(OpCode.PACK)
                else:
                    sb.push(p.Value)

            vscript = bytearray(0)

            if item.Script is not None:
                if type(item.Script) is str:
                    item.Script = item.Script.encode('utf-8')
                vscript = item.Script
            #                logger.info("SCRIPT IS %s " % item.Script)

            witness = Witness(
                invocation_script=sb.ToArray(),
                verification_script=vscript
            )

            scripts.append(witness)

        return scripts
Ejemplo n.º 24
0
    def CreateMultiSigRedeemScript(m, publicKeys):

        if m < 2 or m > len(publicKeys) or len(publicKeys) > 1024:
            raise Exception('Invalid keys')

        sb = ScriptBuilder()
        sb.push(m)

        pkeys = [point for point in publicKeys]
        pkeys.sort()
        keys = [p.encode_point().decode() for p in pkeys]

        for key in keys:
            sb.push(key)

        sb.push(len(publicKeys))
        sb.add(CHECKMULTISIG)

        return sb.ToArray()
Ejemplo n.º 25
0
def TestInvokeContract(wallet, args):

    BC = GetBlockchain()

    contract = BC.GetContract(args[0])

    if contract:
        descripe_contract(contract)

        verbose = False

        if 'verbose' in args:
            verbose = True
            args.remove('verbose')

        print("VERBOSE %s " % verbose)

        params = args[1:] if len(args) > 1 else []

        if len(params) > 0 and params[0] == 'describe':
            return

        params.reverse()

        sb = ScriptBuilder()

        for p in params:

            item = parse_param(p)
            sb.push(item)

        sb.EmitAppCall(contract.Code.ScriptHash().Data)

        out = sb.ToArray()

        return test_invoke(out, wallet)

    else:

        print("Contract %s not found" % args[0])

    return None, None
Ejemplo n.º 26
0
    def GetBalance(self, wallet, address, as_string=False):
        """
        Get the token balance.

        Args:
            wallet (neo.Wallets.Wallet): a wallet instance.
            address (str): public address of the account to get the token balance of.
            as_string (bool): whether the return value should be a string. Default is False, returning an integer.

        Returns:
            int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed.
        """
        addr = PromptUtils.parse_param(address, wallet)
        if isinstance(addr, UInt160):
            addr = addr.Data
        sb = ScriptBuilder()
        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf',
                                           [addr])

        tx, fee, results, num_ops, engine_success = test_invoke(
            sb.ToArray(), wallet, [])
        if engine_success:
            try:
                val = results[0].GetBigInteger()
                precision_divisor = pow(10, self.decimals)
                balance = Decimal(val) / Decimal(precision_divisor)
                if as_string:
                    formatter_str = '.%sf' % self.decimals
                    balance_str = format(balance, formatter_str)
                    return balance_str
                return balance
            except Exception as e:
                logger.error("could not get balance: %s " % e)
                traceback.print_stack()
        else:
            addr_str = Crypto.ToAddress(UInt160(data=addr))
            logger.error(
                f"Could not get balance of address {addr_str} for token contract {self.ScriptHash}. VM execution failed. Make sure the contract exists on the network and that it adheres to the NEP-5 standard"
            )

        return 0
    def GetScripts(self):

        if not self.Completed:
            raise Exception("Signature Context not complete")

        scripts = []

        for i in range(0, len(self.Parameters)):

            sb = ScriptBuilder()

            plist = list(self.Parameters[i])
            plist.reverse()

            for p in plist:
                sb.push(p)

            witness = Witness(invocation_script=sb.ToArray(),
                              verification_script=self.Verifications[i])
            scripts.append(witness)

        return scripts
Ejemplo n.º 28
0
    def get_token_balance(self, request, hash_value, address_contract):
        request.setHeader('Content-Type', 'application/json')
        try:
            print(address_contract)
            addr = parse_param(address_contract)
            if isinstance(addr, UInt160):
                addr = addr.Data
            sb = ScriptBuilder()
            sb.EmitAppCallWithOperationAndArgs(UInt160.ParseString(hash_value),
                                               'balanceOf', [addr])
            response = self.get_invoke_result_balance(sb.ToArray())

            return json.dumps(response)

        except Exception as e:
            #    logger.info("Could not get contract with hash %s because %s " % (contract_hash, e))
            return self.format_message(
                "Could not get balance with hash %s because %s " %
                (hash_value, e))
        # return self.format_notifications(request, notifications)
        return self.format_message(
            "Could not get balance with hash %s because test" % (hash_value))
Ejemplo n.º 29
0
    def CreateMultiSigRedeemScript(m, publicKeys):
        # raise NotImplementedError()

        if m < 2 or m > len(publicKeys) or len(publicKeys) > 1024:
            raise Exception('Invalid keys')

        sb = ScriptBuilder()
        sb.push(m)

        pkeys = [point for point in publicKeys]
        pkeys.sort()
        keys = [p.encode_point().decode() for p in pkeys]

        #for now we dont
        for key in keys:
            sb.push(key)

        sb.push(len(publicKeys))
        sb.add(CHECKMULTISIG)

        toarray = sb.ToArray()
        tastr = toarray.decode('utf8')
        return toarray
Ejemplo n.º 30
0
    def json_rpc_method_handler(self, method, params):

        if method == "getaccountstate":
            acct = Blockchain.Default().GetAccountState(params[0])
            if acct is None:
                try:
                    acct = AccountState(
                        script_hash=Helper.AddrStrToScriptHash(params[0]))
                except Exception as e:
                    raise JsonRpcError(
                        -2146233033,
                        "One of the identified items was in an invalid format."
                    )

            return acct.ToJson()

        elif method == "getassetstate":
            asset_id = UInt256.ParseString(params[0])
            asset = Blockchain.Default().GetAssetState(asset_id.ToBytes())
            if asset:
                return asset.ToJson()
            raise JsonRpcError(-100, "Unknown asset")

        elif method == "getbestblockhash":
            return '0x%s' % Blockchain.Default().CurrentHeaderHash.decode(
                'utf-8')

        elif method == "getblock":
            # this should work for either str or int
            block = Blockchain.Default().GetBlock(params[0])
            if not block:
                raise JsonRpcError(-100, "Unknown block")
            return self.get_block_output(block, params)

        elif method == "getblockcount":
            return Blockchain.Default().Height + 1

        elif method == "getblockhash":
            height = params[0]
            if height >= 0 and height <= Blockchain.Default().Height:
                return '0x%s' % Blockchain.Default().GetBlockHash(
                    height).decode('utf-8')
            else:
                raise JsonRpcError(-100, "Invalid Height")

        elif method == "getblocksysfee":
            height = params[0]
            if height >= 0 and height <= Blockchain.Default().Height:
                return Blockchain.Default().GetSysFeeAmountByHeight(height)
            else:
                raise JsonRpcError(-100, "Invalid Height")

        elif method == "getconnectioncount":
            return len(NodeLeader.Instance().Peers)

        elif method == "getcontractstate":
            script_hash = UInt160.ParseString(params[0])
            contract = Blockchain.Default().GetContract(script_hash.ToBytes())
            if contract is None:
                raise JsonRpcError(-100, "Unknown contract")
            return contract.ToJson()

        elif method == "getrawmempool":
            return list(
                map(lambda hash: "0x%s" % hash.decode('utf-8'),
                    NodeLeader.Instance().MemPool.keys()))

        elif method == "getversion":
            return {
                "port": self.port,
                "nonce": NodeLeader.Instance().NodeId,
                "useragent": settings.VERSION_NAME
            }

        elif method == "getrawtransaction":
            tx_id = UInt256.ParseString(params[0])
            tx, height = Blockchain.Default().GetTransaction(tx_id)
            if not tx:
                raise JsonRpcError(-100, "Unknown Transaction")
            return self.get_tx_output(tx, height, params)

        elif method == "getstorage":
            script_hash = UInt160.ParseString(params[0])
            key = binascii.unhexlify(params[1].encode('utf-8'))
            storage_key = StorageKey(script_hash=script_hash, key=key)
            storage_item = Blockchain.Default().GetStorageItem(storage_key)
            if storage_item:
                return storage_item.Value.hex()
            return None

        elif method == "gettxout":
            hash = params[0].encode('utf-8')
            index = params[1]
            utxo = Blockchain.Default().GetUnspent(hash, index)
            if utxo:
                return utxo.ToJson(index)
            else:
                return None

        elif method == "invoke":
            shash = UInt160.ParseString(params[0])
            contract_parameters = [
                ContractParameter.FromJson(p) for p in params[1]
            ]
            sb = ScriptBuilder()
            sb.EmitAppCallWithJsonArgs(shash, contract_parameters)
            return self.get_invoke_result(sb.ToArray())

        elif method == "invokefunction":
            contract_parameters = []
            if len(params) > 2:
                contract_parameters = [
                    ContractParameter.FromJson(p).ToVM() for p in params[2]
                ]
            sb = ScriptBuilder()
            sb.EmitAppCallWithOperationAndArgs(UInt160.ParseString(params[0]),
                                               params[1], contract_parameters)
            return self.get_invoke_result(sb.ToArray())

        elif method == "invokescript":
            script = params[0].encode('utf-8')
            return self.get_invoke_result(script)

        elif method == "sendrawtransaction":
            tx_script = binascii.unhexlify(params[0].encode('utf-8'))
            transaction = Transaction.DeserializeFromBufer(tx_script)
            result = NodeLeader.Instance().Relay(transaction)
            return result

        elif method == "validateaddress":
            return self.validateaddress(params)

        elif method == "getpeers":
            return self.get_peers()

        elif method == "getbalance":
            if self.wallet:
                return self.get_balance(params)
            else:
                raise JsonRpcError(-400, "Access denied.")

        elif method == "getwalletheight":
            if self.wallet:
                return self.wallet.WalletHeight
            else:
                raise JsonRpcError(-400, "Access denied.")

        elif method == "listaddress":
            if self.wallet:
                return self.list_address()
            else:
                raise JsonRpcError(-400, "Access denied.")

        elif method == "getnewaddress":
            if self.wallet:
                keys = self.wallet.CreateKey()
                account = Account.get(
                    PublicKeyHash=keys.PublicKeyHash.ToBytes())
                return account.contract_set[0].Address.ToString()
            else:
                raise JsonRpcError(-400, "Access denied.")

        raise JsonRpcError.methodNotFound()