예제 #1
0
    def GetSpentCoins(self, tx_hash):

        if type(tx_hash) is not bytes:
            tx_hash = bytes(tx_hash.encode('utf-8'))

        coins = DBInterface(self._db, DBPrefix.ST_SpentCoin, SpentCoinState)
        result = coins.TryGet(keyval=tx_hash)

        return result
예제 #2
0
    def GetContract(self, hash):

        if type(hash) is str:
            try:
                hash = UInt160.ParseString(hash).ToBytes()
            except Exception as e:
                logger.info("could not convert argument to bytes :%s " % e)
                return None

        contracts = DBInterface(self._db, DBPrefix.ST_Contract, ContractState)
        contract = contracts.TryGet(keyval=hash)
        return contract
예제 #3
0
    def GetAssetState(self, assetId):
        if type(assetId) is str:
            try:
                assetId = assetId.encode('utf-8')
            except Exception as e:
                logger.info("could not convert argument to bytes :%s " % e)
                return None

        assets = DBInterface(self._db, DBPrefix.ST_Asset, AssetState)
        asset = assets.TryGet(assetId)

        return asset
예제 #4
0
    def GetAccountState(self, address, print_all_accounts=False):

        if type(address) is str:
            try:
                address = address.encode('utf-8')
            except Exception as e:
                logger.info("could not convert argument to bytes :%s " % e)
                return None

        accounts = DBInterface(self._db, DBPrefix.ST_Account, AccountState)
        acct = accounts.TryGet(keyval=address)

        return acct
예제 #5
0
    def GetUnspent(self, hash, index):

        coins = DBInterface(self._db, DBPrefix.ST_Coin, UnspentCoinState)

        state = coins.TryGet(hash)

        if state is None:
            return None
        if index >= len(state.Items):
            return None
        if state.Items[index] & CoinState.Spent > 0:
            return None
        tx, height = self.GetTransaction(hash)

        return tx.outputs[index]
예제 #6
0
    def GetAllUnspent(self, hash):

        unspents = []

        unspentcoins = DBInterface(self._db, DBPrefix.ST_Coin,
                                   UnspentCoinState)

        state = unspentcoins.TryGet(keyval=hash.ToBytes())

        if state:
            tx, height = self.GetTransaction(hash)

            for index, item in enumerate(state.Items):
                if item & CoinState.Spent == 0:
                    unspents.append(tx.outputs[index])
        return unspents
예제 #7
0
    def GetUnclaimed(self, hash):

        tx, height = self.GetTransaction(hash)

        if tx is None:
            return None

        out = {}
        coins = DBInterface(self._db, DBPrefix.ST_SpentCoin, SpentCoinState)

        state = coins.TryGet(keyval=hash.ToBytes())

        if state:
            for item in state.Items:
                out[item.index] = SpentCoin(tx.outputs[item.index], height,
                                            item.height)

        return out
예제 #8
0
def GetStateMachine():
    from neo.SmartContract.StateMachine import StateMachine
    from neo.Storage.Interface.DBInterface import DBInterface
    from neo.Storage.Common.DBPrefix import DBPrefix
    from neo.Core.State.AccountState import AccountState
    from neo.Core.State.AssetState import AssetState
    from neo.Core.State.ValidatorState import ValidatorState
    from neo.Core.State.ContractState import ContractState
    from neo.Core.State.StorageItem import StorageItem

    bc = GetBlockchain()

    accounts = DBInterface(bc._db, DBPrefix.ST_Account, AccountState)
    assets = DBInterface(bc._db, DBPrefix.ST_Asset, AssetState)
    validators = DBInterface(bc._db, DBPrefix.ST_Validator, ValidatorState)
    contracts = DBInterface(bc._db, DBPrefix.ST_Contract, ContractState)
    storages = DBInterface(bc._db, DBPrefix.ST_Storage, StorageItem)

    return StateMachine(accounts, validators, assets, contracts, storages,
                        None, bc)
예제 #9
0
def test_deploy_and_invoke(deploy_script, invoke_args, wallet,
                           from_addr=None, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True,
                           debug_map=None, invoke_attrs=None, owners=None, enable_debugger=False, snapshot=None):

    if settings.USE_DEBUG_STORAGE:
        debug_storage = DebugStorage.instance()
        storages = DBInterface(debug_storage.db, DBPrefix.ST_Storage, StorageItem)
        storages.DebugStorage = True

    dtx = InvocationTransaction()
    dtx.Version = 1
    dtx.outputs = []
    dtx.inputs = []
    dtx.scripts = []
    dtx.Script = binascii.unhexlify(deploy_script)

    if from_addr is not None:
        from_addr = PromptUtils.lookup_addr_str(wallet, from_addr)

    try:
        dtx = wallet.MakeTransaction(tx=dtx, from_addr=from_addr)
    except (ValueError):
        pass

    context = ContractParametersContext(dtx)
    wallet.Sign(context)
    dtx.scripts = context.GetScripts()

    contract = wallet.GetDefaultContract()
    dtx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash(contract.Script, unhex=False))]
    dtx.Attributes = make_unique_script_attr(dtx.Attributes)

    to_dispatch = []

    if snapshot is None:
        snapshot = GetBlockchain()._db.createSnapshot().Clone()
    engine = ApplicationEngine(
        trigger_type=TriggerType.Application,
        container=dtx,
        snapshot=snapshot,
        gas=dtx.Gas,
        testMode=True
    )

    engine.LoadScript(dtx.Script)

    # first we will execute the test deploy
    # then right after, we execute the test invoke
    if enable_debugger:
        debugger = Debugger(engine)
        d_success = debugger.Execute()
    else:
        d_success = engine.Execute()

    # the old setup provided the same StateMachine object to the ApplicationEngine for deploy and invoke
    # this allowed for a single dispatch of events at the end of the function. Now a new StateMachine is automatically
    # created when creating an ApplicationEngine, thus we have to dispatch events after the deploy to not lose them as
    # testcases expect them
    to_dispatch = to_dispatch + engine._Service.events_to_dispatch
    for event in to_dispatch:
        events.emit(event.event_type, event)
    to_dispatch = []

    if d_success:

        items = engine.ResultStack.Items

        contract_state = None
        for i in items:
            if type(i) is ContractState:
                contract_state = i
                break
            elif type(i) is InteropInterface:
                item = i.GetInterface()
                if type(item) is ContractState:
                    contract_state = item
                    break

        shash = contract_state.Code.ScriptHash()

        invoke_args, neo_to_attach, gas_to_attach = PromptUtils.get_asset_attachments(invoke_args)
        invoke_args, no_parse_addresses = PromptUtils.get_parse_addresses(invoke_args)

        invoke_args.reverse()

        if '--i' in invoke_args:
            invoke_args = []
            for index, iarg in enumerate(contract_state.Code.ParameterList):
                param, abort = PromptUtils.gather_param(index, iarg)
                if abort:
                    return None, [], 0, None
                else:
                    invoke_args.append(param)
            invoke_args.reverse()

        sb = ScriptBuilder()

        for p in invoke_args:
            process_params(sb, p, wallet, no_parse_addresses)

        sb.EmitAppCall(shash.Data)
        out = sb.ToArray()

        outputs = []

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

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

            outputs.append(output)

        itx = InvocationTransaction()
        itx.Version = 1
        itx.outputs = outputs
        itx.inputs = []
        itx.scripts = []
        itx.Attributes = deepcopy(invoke_attrs) if invoke_attrs else []
        itx.Script = binascii.unhexlify(out)

        if len(outputs) < 1 and not owners:
            contract = wallet.GetDefaultContract()
            itx.Attributes.append(TransactionAttribute(usage=TransactionAttributeUsage.Script,
                                                       data=contract.ScriptHash))
            itx.Attributes = make_unique_script_attr(itx.Attributes)

        try:
            itx = wallet.MakeTransaction(tx=itx, from_addr=from_addr)
        except (ValueError):
            pass

        context = ContractParametersContext(itx)
        wallet.Sign(context)

        if owners:
            owners = list(owners)
            for owner in owners:
                itx.Attributes.append(TransactionAttribute(usage=TransactionAttributeUsage.Script, data=owner))
                itx.Attributes = make_unique_script_attr(itx.Attributes)
            context = ContractParametersContext(itx, isMultiSig=True)

        if context.Completed:
            itx.scripts = context.GetScripts()
        else:
            logger.warn("Not gathering signatures for test build.  For a non-test invoke that would occur here.")

        engine = ApplicationEngine(
            trigger_type=TriggerType.Application,
            container=itx,
            snapshot=snapshot,
            gas=itx.Gas,
            testMode=invocation_test_mode
        )

        engine.invocation_args = invoke_args
        engine.LoadScript(itx.Script)
        engine.LoadDebugInfoForScriptHash(debug_map, shash.Data)

        if enable_debugger:
            debugger = Debugger(engine)
            i_success = debugger.Execute()
        else:
            i_success = engine.Execute()

        engine._Service.ExecutionCompleted(engine, i_success)
        to_dispatch = to_dispatch + engine._Service.events_to_dispatch

        for event in to_dispatch:
            events.emit(event.event_type, event)

        if i_success:
            if len(engine._Service.notifications) > 0:

                for n in engine._Service.notifications:
                    Blockchain.Default().OnNotify(n)

            logger.info("Used %s Gas " % engine.GasConsumed().ToString())

            consumed = engine.GasConsumed() - Fixed8.FromDecimal(10)
            consumed = consumed.Ceil()

            if consumed <= Fixed8.Zero():
                consumed = min_fee

            total_ops = engine.ops_processed

            # set the amount of gas the tx will need
            itx.Gas = consumed
            itx.Attributes = []
            result = engine.ResultStack.Items
            return itx, result, total_ops, engine
        else:
            print("error executing invoke contract...")

    else:
        print("error executing deploy contract.....")

    # service.ExecutionCompleted(engine, False, 'error')

    return None, [], 0, None
예제 #10
0
    def GetAllSpentCoins(self):
        coins = DBInterface(self._db, DBPrefix.ST_SpentCoin, SpentCoinState)

        return coins.Keys
예제 #11
0
 def GetStorageItem(self, storage_key):
     storages = DBInterface(self._db, DBPrefix.ST_Storage, StorageItem)
     item = storages.TryGet(storage_key.ToArray())
     return item
예제 #12
0
 def GetStates(self, prefix, classref):
     return DBInterface(self._db, prefix, classref)