def test_parse(self):
        string = '0xcedb5c4e24b1f6fc5b239f2d1049c3229ad5ed05293c696b3740dc236c3f41b4'
        uint256 = UInt256.ParseString(string)
        self.assertIsInstance(uint256, UInt256)
        self.assertEqual(uint256.To0xString(), string)

        string = '9410bd44beb7d6febc9278b028158af2781fcfb40cf2c6067b3525d24eff19f6'
        uint256 = UInt256.ParseString(string)
        self.assertIsInstance(uint256, UInt256)
        self.assertEqual(uint256.ToString(), string)

        string = '9410bd44beb7d6febc9278b028158af2781fcfb40cf2c6067b3525d24eff19f'
        with self.assertRaises(Exception) as context:
            uint256 = UInt256.ParseString(string)
Beispiel #2
0
    def execute(self, arguments):
        item = get_arg(arguments)
        if item is not None:
            if item.lower() == "all":
                assets = Blockchain.Default().ShowAllAssets()
                assetlist = []
                for asset in assets:
                    state = Blockchain.Default().GetAssetState(asset.decode('utf-8')).ToJson()
                    asset_dict = {state['name']: state['assetId']}
                    assetlist.append(asset_dict)
                print(json.dumps(assetlist, indent=4))
                return assetlist

            if item.lower() == 'neo':
                assetId = Blockchain.Default().SystemShare().Hash
            elif item.lower() == 'gas':
                assetId = Blockchain.Default().SystemCoin().Hash
            else:
                try:
                    assetId = UInt256.ParseString(item)
                except Exception:
                    print("Could not find asset from args: %s" % arguments)
                    return

            asset = Blockchain.Default().GetAssetState(assetId.ToBytes())

            if asset is not None:
                print(json.dumps(asset.ToJson(), indent=4))
                return asset.ToJson()
            else:
                print("Asset %s not found" % item)
                return
        else:
            print('Please specify the required parameter')
            return
    def StaticAssetState(assetId):
        neo = AssetState()
        neo.AssetId = UInt256.ParseString("0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b")
        neo.AssetType = 0x00

        gas = AssetState()
        gas.AssetId = UInt256.ParseString("0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7")
        gas.AssetType = 0x01

        if assetId == neo.AssetId:
            return neo

        elif assetId == gas.AssetId:
            return gas

        else:
            return None
Beispiel #4
0
    def test_interop_get_bad_transaction_height(self):

        u256 = UInt256.ParseString(
            'e4d2ea5df2adf77df91049beccbb16f98863b93a16439c60381eac1f23bff176')

        hash = StackItem.New(u256.Data)

        self.engine.EvaluationStack.PushT(hash)
        self.state_reader.Blockchain_GetTransactionHeight(self.engine)

        height = self.engine.EvaluationStack.Pop().GetBigInteger()

        self.assertEqual(height, -1)
Beispiel #5
0
    def test_interop_get_bad_transaction(self):

        u256 = UInt256.ParseString(
            'e4d2ea5df2adf77df91049beccbb16f98863b93a16439c60381eac1f23bff176')

        hash = StackItem.New(u256.Data)

        self.engine.EvaluationStack.PushT(hash)
        self.state_reader.Blockchain_GetTransaction(self.engine)

        tx = self.engine.EvaluationStack.Pop().GetInterface()

        self.assertIsNone(tx)
Beispiel #6
0
    def test_interop_get_transaction(self):
        u256 = UInt256.ParseString(
            '8be9660512991d36e016b8ced6fda5d611d26a0f6e2faaaf1f379496edb3395f')

        hash = StackItem.New(u256.Data)

        self.econtext.EvaluationStack.PushT(hash)
        self.engine.InvocationStack.PushT(self.econtext)
        self.state_reader.Blockchain_GetTransaction(self.engine)

        tx = self.econtext.EvaluationStack.Pop().GetInterface()

        self.assertIsInstance(tx, Transaction)
Beispiel #7
0
    def test_interop_get_bad_transaction_height(self):
        u256 = UInt256.ParseString(
            '8be9660512991d36e016b8ced6fda5d611d26a0f6e2faaaf1f379496edb33956')

        hash = StackItem.New(u256.Data)

        self.econtext.EvaluationStack.PushT(hash)
        self.engine.InvocationStack.PushT(self.econtext)
        self.state_reader.Blockchain_GetTransactionHeight(self.engine)

        height = self.econtext.EvaluationStack.Pop().GetBigInteger()

        self.assertEqual(height, -1)
Beispiel #8
0
 def show_tx(self, args):
     if len(args):
         try:
             txid = UInt256.ParseString(get_arg(args))
             tx, height = Blockchain.Default().GetTransaction(txid)
             if height > -1:
                 jsn = tx.ToJson()
                 jsn['height'] = height
                 jsn['unspents'] = [uns.ToJson(tx.outputs.index(uns)) for uns in Blockchain.Default().GetAllUnspent(txid)]
                 tokens = [(Token.Command, json.dumps(jsn, indent=4))]
                 print_tokens(tokens, self.token_style)
                 print('\n')
         except Exception as e:
             print("Could not find transaction from args: %s (%s)" % (e, args))
     else:
         print("Please specify a TX hash")
Beispiel #9
0
    def get_by_tx(self, request, tx_hash):
        request.setHeader('Content-Type', 'application/json')

        bc = Blockchain.Default()  # type: Blockchain
        notifications = []
        try:
            hash = UInt256.ParseString(tx_hash)
            tx, height = bc.GetTransaction(hash)
            block_notifications = self.notif.get_by_block(height - 1)
            for n in block_notifications:
                if n.tx_hash == tx.Hash:
                    notifications.append(n)
        except Exception as e:
            logger.info("Could not get tx with hash %s because %s " % (tx_hash, e))
            return self.format_message("Could not get tx with hash %s because %s " % (tx_hash, e))

        return self.format_notifications(request, notifications)
    def json_rpc_method_handler(self, method, params):

        if method == "getnodestate":
            height = Blockchain.Default().Height
            headers = Blockchain.Default().HeaderHeight
            diff = height - self.start_height
            now = datetime.datetime.utcnow()
            difftime = now - self.start_dt
            mins = difftime / datetime.timedelta(minutes=1)
            secs = mins * 60
            bpm = 0
            tps = 0

            if diff > 0 and mins > 0:
                bpm = diff / mins
                tps = Blockchain.Default().TXProcessed / secs

            return {
                'Progress': [height, "/", headers],
                'Block-cache length': Blockchain.Default().BlockCacheCount,
                'Blocks since program start': diff,
                'Time elapsed (minutes)': mins,
                'Blocks per min': bpm,
                'TPS': tps
            }

        elif method == "gettxhistory":
            if self.wallet:
                res = []
                for tx in self.wallet.GetTransactions():
                    json = tx.ToJson()
                    tx_id = UInt256.ParseString(json['txid'])
                    txx, height = Blockchain.Default().GetTransaction(tx_id)
                    header = Blockchain.Default().GetHeaderByHeight(height)
                    block_index = header.Index
                    json['block_index'] = block_index
                    block_timestamp = header.Timestamp
                    json['blocktime'] = block_timestamp
                    res.append(json)
                return res
            else:
                raise JsonRpcError(-400, "Access denied.")

        return super(ExtendedJsonRpcApi,
                     self).json_rpc_method_handler(method, params)
    def FromJson(json):
        """
        Convert a json object to a ContractParameter object

        Args:
            item (dict): The item to convert to a ContractParameter object

        Returns:
            ContractParameter

        """
        type = ContractParameterType.FromString(json['type'])

        value = json['value']
        param = ContractParameter(type=type, value=None)

        if type == ContractParameterType.Signature or type == ContractParameterType.ByteArray:
            param.Value = bytearray.fromhex(value)

        elif type == ContractParameterType.Boolean:
            param.Value = bool(value)

        elif type == ContractParameterType.Integer:
            param.Value = int(value)

        elif type == ContractParameterType.Hash160:
            param.Value = UInt160.ParseString(value)

        elif type == ContractParameterType.Hash256:
            param.Value = UInt256.ParseString(value)

        # @TODO Not sure if this is working...
        elif type == ContractParameterType.PublicKey:
            param.Value = ECDSA.decode_secp256r1(value).G

        elif type == ContractParameterType.String:
            param.Value = str(value)

        elif type == ContractParameterType.Array:
            val = [ContractParameter.FromJson(item) for item in value]
            param.Value = val

        return param
Beispiel #12
0
 def execute(self, arguments):
     if len(arguments):
         try:
             txid = UInt256.ParseString(get_arg(arguments))
             tx, height = Blockchain.Default().GetTransaction(txid)
             if height > -1:
                 jsn = tx.ToJson()
                 jsn['height'] = height
                 jsn['unspents'] = [uns.ToJson(tx.outputs.index(uns)) for uns in
                                    Blockchain.Default().GetAllUnspent(txid)]
                 print(json.dumps(jsn, indent=4))
                 return jsn
             else:
                 print(f"Could not find transaction for hash {txid}")
                 return
         except Exception:
             print("Could not find transaction from args: %s" % arguments)
             return
     else:
         print("Please specify the required parameter")
         return
Beispiel #13
0
def transaction(request, tx):
    #
    # this API returns the details of transaction
    # for the given address
    #
    res = {}
    try:
        txid = UInt256.ParseString(tx)
        tx, height = Blockchain.Default().GetTransaction(txid)
        if height > -1:
            res = tx.ToJson()
            res['height'] = height
            res['unspents'] = [
                uns.ToJson(tx.outputs.index(uns))
                for uns in Blockchain.Default().GetAllUnspent(txid)
            ]
            # tokens = [(Token.Command, json.dumps(jsn, indent=4))]
            # print_tokens(tokens, self.token_style)
            # print('\n')
    except Exception as e:
        res["error"] = True
        res["message"] = e
        logger.error("Could not find transaction from tx: %s (%s)" % (e, tx))
    return res
Beispiel #14
0
 def test_get_unspents(self):
     u = UInt256.ParseString(
         'f999c36145a41306c846ea80290416143e8e856559818065be3f4e143c60e43a')
     unspents = GetBlockchain().GetAllUnspent(u)
     self.assertEqual(len(unspents), 1)
 def test_get_unspents(self):
     u = UInt256.ParseString(
         '0ff23561c611ccda65470c9a4a5f1be31f2f4f61b98c75d051e1a72e85a302eb')
     unspents = GetBlockchain().GetAllUnspent(u)
     self.assertEqual(len(unspents), 1)
Beispiel #16
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 == "mw_construct_send_tx":
            return MyWishMethods.construct_send_tx(self.wallet, params)

        elif method == "mw_construct_deploy_tx":
            return MyWishMethods.construct_deploy_tx(self.wallet, params)

        elif method == "mw_construct_invoke_tx":
            return MyWishMethods.construct_invoke_tx(self.wallet, params)

        elif method == "getapplicationlog":
            assert(all([x in '1234567890abcdefABCDEFxX' for x in params[0]])) # prevent traversal
            try:
                with open('/home/neo/neo-python/notis/' + params[0]) as f:
                    res =  [json.loads(x) for x in f.read().split('\n') if x]
                    return [{'name': x['notify_type'], 'contract': x['contract'], 'args': x['payload']} for x in res]
            except FileNotFoundError:
                return ([])

        elif method == "submitblock":
            raise NotImplementedError()

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

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

        raise JsonRpcError.methodNotFound()
Beispiel #17
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()
Beispiel #18
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 == "getLastBlog":

            if len(params) > 0:
                height = params[0]
            else:
                height = Blockchain.Default().Height + 1
            data = self.get_blog_content(height, "")
            return data;
        elif method == "getLastBlogByTag":

            if len(params) > 1:
                height = params[1]
                tag = params[0]
            elif len(params) > 0:
                tag = params[0]
                height = Blockchain.Default().Height + 1
            else:
                raise JsonRpcError(-100, "no enough param")
            data = self.get_blog_content(height, tag)
            return data;
        elif method == "getLastBlogBySender":

            if len(params) > 1:
                height = params[1]
                sender = params[0]
            elif len(params) > 0:
                sender = params[0]
                height = Blockchain.Default().Height + 1
            else:
                raise JsonRpcError(-100, "no enough param")
            data = self.get_blog_content(height, "", sender)
            return data;
        elif method == "getBlogContent":
            tx_id = UInt256.ParseString(params[0])
            tx, height = Blockchain.Default().GetTransaction(tx_id)
            if not tx:
                raise JsonRpcError(-100, "Unknown Transaction")

            for attr in tx.Attributes:
                item = attr.ToJson;
                if item['usage'] == 240:
                    item['content'] = binascii.a2b_hex(item['data']).decode("utf8")
                    return item;
            raise JsonRpcError(-100, "no blog content")


        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 == "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 == "createAddress":

            private_key = bytes(Random.get_random_bytes(32))
            key = KeyPair(priv_key=private_key)
            self.wallet._keys[key.PublicKeyHash.ToBytes()] = key
            self.wallet.OnCreateAccount(key)
            contract = WalletContract.CreateSignatureContract(key.PublicKey)
            self.wallet.AddContract(contract)
            if key :
                result = {'privateKey': key.Export(),'address':contract.Address}
                return result;
            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 == "sendBlog":
        #     shash = UInt160.ParseString(params[0])
        #     contract_parameters = [ContractParameter.FromJson(p) for p in params[1]]
        #     sb = ScriptBuilder()
        #     sb.EmitAppCallWithJsonArgs(shash, contract_parameters)
        #     script = sb.ToArray();
        #     tx = ContractTransaction()
        #     tx.inputs = []
        #     tx.outputs = []
        #     attribute = TransactionAttribute(240, params[2].encode('utf-8'))
        #     standard_contract = self.wallet.GetStandardAddress()
        #     data = standard_contract.Data
        #     tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script,
        #                                           data=data)]
        #
        #     tx.Attributes.append(attribute)
        #     tx.Version = 1
        #     tx.scripts = []
        #     BC = GetBlockchain()
        #     contract = BC.GetContract(params[0])
        #     output = TransactionOutput(AssetId=Blockchain.SystemShare().Hash,
        #                                Value=Fixed8.FromDecimal(float(1)),
        #                                script_hash=contract.Code.ScriptHash(),
        #                                )
        #     tx.outputs.append(output)
        #     logger.info("output %s" % output.ToJson(0))
        #     tx.Script = binascii.unhexlify(script)
        #     print("percentage %s %s" % (self.wallet.WalletHeight, Blockchain.Default().Height))
        #     scripthash_from = None
        #     if not self.wallet.IsSynced:
        #         raise JsonRpcError.invalidRequest("wallet not synced")
        #     private_key = None
        #     if len(params) > 3:
        #         from_address = params[3]
        #         if from_address is not None:
        #             scripthash_from = lookup_addr_str(self.wallet, from_address)
        #     if len(params) > 4:
        #         private_key = params[4]
        #     wallet_tx = SendBlog(self.wallet, tx, from_addr=scripthash_from, privatekey=private_key)
        #     if wallet_tx != False:
        #         return wallet_tx.ToJson();
        #     self.wallet.Rebuild()
        #     raise JsonRpcError.invalidRequest("Field 'no enough asset")
        elif method == 'postblog':
            try:

                if len(params) > 3:
                    from_address = params[3]
                assetId =Blockchain.SystemShare().Hash

                if len(params) > 4:
                    private_key = params[4]

                if assetId is None:
                    print("Asset id not found")
                    return False

                contract_parameters = [ContractParameter.FromJson(p) for p in params[1]]
                sb = ScriptBuilder()
                sb.EmitAppCallWithJsonArgs(UInt160.ParseString(params[0]), contract_parameters)
                script = sb.ToArray();

                scripthash_from = None

                if from_address is not None:
                    scripthash_from = lookup_addr_str(self.wallet, from_address)

                # f8amount = Fixed8.TryParse(0, require_positive=True)
                # if f8amount is None:
                #     print("invalid amount format")
                #     return False
                #
                # if type(assetId) is UInt256 and f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState(
                #         assetId.ToBytes()).Precision) != 0:
                #     print("incorrect amount precision")
                #     return False
                #
                fee = Fixed8.Zero()
                #
                # output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=contract.Code.ScriptHash())
                tx = InvocationTransaction()

                ttx = self.wallet.MakeTransaction(tx=tx,
                                             change_address=None,
                                             fee=fee,
                                             from_addr=scripthash_from)

                if ttx is None:
                    print("insufficient funds")
                    return False
                standard_contract = self.wallet.GetStandardAddress()
                if scripthash_from is not None:
                    signer_contract = self.wallet.GetContract(scripthash_from)
                else:
                    signer_contract = self.wallet.GetContract(standard_contract)

                if not signer_contract.IsMultiSigContract:
                    data = scripthash_from.Data
                    print(data)
                    tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script,
                                                          data=data),TransactionAttribute(usage=TransactionAttributeUsage.Remark1,
                                                          data=from_address.encode('utf-8'))]

                # insert any additional user specified tx attributes
                tx.Attributes.append(TransactionAttribute(240, params[2].encode('utf-8')))
                tx.Script = binascii.unhexlify(script)

                context = ContractParametersContext(tx, isMultiSig=signer_contract.IsMultiSigContract)
                if private_key is not None:
                    prikey = KeyPair.PrivateKeyFromWIF(private_key)
                    kp = KeyPair(prikey)
                self.wallet.Sign(context,kp)
                attributes = [attr.ToJson() for attr in tx.Attributes]
                print("attributes %s" %attributes)
                if context.Completed:

                    tx.scripts = context.GetScripts()

                    #            print("will send tx: %s " % json.dumps(tx.ToJson(),indent=4))

                    relayed = NodeLeader.Instance().Relay(tx)

                    if relayed:
                        self.wallet.SaveTransaction(tx)

                        print("Relayed Tx: %s " % tx.Hash.ToString())
                        return tx.ToJson()
                    else:

                        print("Could not relay tx %s " % tx.Hash.ToString())

                else:
                    print("Transaction initiated, but the signature is incomplete")
                    print(json.dumps(context.ToJson(), separators=(',', ':')))
                    return False

            except Exception as e:
                print("could not send: %s " % e)

            return False
        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 == "submitblock":
            raise NotImplementedError()

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

        elif method == "getpeers":
            raise NotImplementedError()

        raise JsonRpcError.methodNotFound()