def __init__(self, contract_hash, wallet_path, wallet_pass):
        super(SurTokenContract, self).__init__()
        self.daemon = True

        self.contract_hash = contract_hash
        self.wallet_path = wallet_path
        self.wallet_pass = to_aes_key(wallet_pass)

        self.smart_contract = SmartContract(contract_hash)
        self.invoke_queue = Queue()

        self.tx_in_progress = None
        self.wallet = None

        settings.set_log_smart_contract_events(False)

        @self.smart_contract.on_notify
        def sc_notify(event):
            logger.info("SmartContract Runtime.Notify event: %s", event)

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

            # The event payload list has at least one element. As developer of the smart contract
            # you should know what data-type is in the bytes, and how to decode it. In this example,
            # it's just a string, so we decode it with utf-8:
            logger.info("- payload part 1: %s",
                        event.event_payload[0].decode("utf-8"))
Exemple #2
0
    def __init__(self):
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'nrve-niche-config.json'), 'r') as f:
            config = json.load(f)
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'network-wallets.json'), 'r') as f:
            network_wallets_config = json.load(f)
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'db-config.json'), 'r') as f:
            self.db_config = json.load(f)
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'smtp-config.json'), 'r') as f:
            self.smtp_config = json.load(f)

        super().__init__(NetworkType[config['network']],
                         'nrve-niche-payment-handler')

        self.smart_contract = SmartContract(config['smart_contract'])
        self.niche_payment_address = config['niche_payment_address']
        self.niche_payment_storage_address = config[
            'niche_payment_storage_address']

        self.setup_wallet(
            network_wallets_config[config['network']]['wallet_path'])

        # decorate the event handler methods dynamically now that we have loaded the SC
        self.sc_notify = self.smart_contract.on_notify(self.sc_notify)
    def __init__(self):

        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'neo-nrve-config.json'), 'r') as f:
            config = json.load(f)

        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'network-wallets.json'), 'r') as f:
            network_wallets_config = json.load(f)

        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'db-config.json'), 'r') as f:
            self.db_config = json.load(f)

        super().__init__(NetworkType[config['network']],
                         'neo-nrve-eventhandler')

        self.smart_contract_hash = config['smart_contract']
        self.smart_contract = SmartContract(self.smart_contract_hash)

        self.wait_whitelist_tx_processing_seconds = config[
            'wait_whitelist_tx_processing_seconds']
        self.wait_load_addresses_to_whitelist_seconds = config[
            'wait_load_addresses_to_whitelist_seconds']

        self.addresses_to_whitelist_count = config[
            'addresses_to_whitelist_count']

        self.setup_wallet(
            network_wallets_config[config['network']]['wallet_path'])
Exemple #4
0
    def __init__(self, disable_auto_whitelist):
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'neo-nrve-config.json'), 'r') as f:
            config = json.load(f)
        if not disable_auto_whitelist:
            with open(
                    os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                 'config', 'network-wallets.json'), 'r') as f:
                network_wallets_config = json.load(f)
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'db-config.json'), 'r') as f:
            self.db_config = json.load(f)
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'smtp-config.json'), 'r') as f:
            self.smtp_config = json.load(f)

        super().__init__(NetworkType[config['network']],
                         'neo-nrve-eventhandler')

        self.smart_contract_hash = config['smart_contract']
        self.smart_contract = SmartContract(self.smart_contract_hash)
        self.old_smart_contract = SmartContract(config['old_smart_contract'])
        self.ignore_blocks_older_than = config['ignore_blocks_older_than']

        # decorate the event handler method dynamically now that we have loaded the SCs
        self.sc_notify = self.old_smart_contract.on_notify(self.sc_notify)
        self.sc_notify = self.smart_contract.on_notify(self.sc_notify)

        if not disable_auto_whitelist:
            self.setup_wallet(
                network_wallets_config[config['network']]['wallet_path'])
        else:
            self.setup_network()

        self.disable_auto_whitelist = disable_auto_whitelist
    def __init__(self):
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'bulk-tx-config.json'), 'r') as f:
            config = json.load(f)
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', config['job_config_file']), 'r') as f:
            job_config = json.load(f)
        with open(
                os.path.join(os.path.abspath(os.path.dirname(__file__)),
                             'config', 'network-wallets.json'), 'r') as f:
            network_wallets_config = json.load(f)

        super().__init__(NetworkType[config['network']], 'bulk-process-tx')

        self.test_only = config['test_only']

        self.operation = job_config['operation']
        self.operation_args_array_length = job_config[
            'operation_args_array_length']
        self.expected_result_count = job_config['expected_result_count']
        try:
            self.from_addr = job_config['from_addr']
        except KeyError:
            pass

        self.jobs = job_config['jobs']

        # Setup the smart contract instance
        self.smart_contract_hash = config['smart_contract']
        self.smart_contract = SmartContract(self.smart_contract_hash)

        # decorate the event handler methods dynamically now that we have loaded the SC
        self.sc_notify = self.smart_contract.on_notify(self.sc_notify)
        self.sc_storage = self.smart_contract.on_storage(self.sc_storage)
        self.sc_execution = self.smart_contract.on_execution(self.sc_execution)

        self.setup_wallet(
            network_wallets_config[config['network']]['wallet_path'])
# If you want to enable logging to a file, set the filename here:
LOGFILE = os.getenv("NEO_REST_LOGFILE", None)

# Internal: if LOGFILE is set, file logging will be setup with max
# 10 MB per file and 3 rotations:
if LOGFILE:
    settings.set_logfile(LOGFILE, max_bytes=1e7, backup_count=3)

# Internal: get the API token from an environment variable
API_AUTH_TOKEN = os.getenv("NEO_REST_API_TOKEN", None)
if not API_AUTH_TOKEN:
    raise Exception("No NEO_REST_API_TOKEN environment variable found!")

# Internal: setup the smart contract instance
smart_contract = SmartContract(SMART_CONTRACT_HASH)

# Internal: setup the klein instance
app = Klein()

# Internal: generate the @authenticated decorator with valid tokens
authenticated = gen_authenticated_decorator(API_AUTH_TOKEN)

#
# Smart contract event handler for Runtime.Notify events
#


@smart_contract.on_notify
def sc_notify(event):
    logger.info("SmartContract Runtime.Notify event: %s", event)
Exemple #7
0
from logzero import logger
from twisted.internet import reactor, task

from neo.contrib.smartcontract import SmartContract
from neo.Network.NodeLeader import NodeLeader
from neo.Core.Blockchain import Blockchain
from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain
from neo.Settings import settings
from neocore.BigInteger import BigInteger

# If you want the log messages to also be saved in a logfile, enable the
# next line. This configures a logfile with max 10 MB and 3 rotations:
# settings.set_logfile("/tmp/logfile.log", max_bytes=1e7, backup_count=3)

# Setup the smart contract instance
smart_contract = SmartContract("d5537fc7dea2150d250e9d5f0cd67b8b248b3fdf")


# Register an event handler for Runtime.Notify events of the smart contract.
@smart_contract.on_notify
def sc_notify(event):
    logger.info("SmartContract Runtime.Notify event: %s", event)

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

    # The event payload list has at least one element. As developer of the smart contract
    # you should know what data-type is in the bytes, and how to decode it. In this example,
    # it's just a string, so we decode it with utf-8:
    byte_array = event.event_payload[0]
Exemple #8
0
from logzero import logger
from twisted.internet import reactor, task

from neo.contrib.smartcontract import SmartContract
from neo.SmartContract.ContractParameter import ContractParameter, ContractParameterType
from neo.Network.NodeLeader import NodeLeader
from neo.Core.Blockchain import Blockchain
from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain
from neo.Settings import settings

# If you want the log messages to also be saved in a logfile, enable the
# next line. This configures a logfile with max 10 MB and 3 rotations:
# settings.set_logfile("/tmp/logfile.log", max_bytes=1e7, backup_count=3)

# Setup the smart contract instance
smart_contract = SmartContract("6537b4bd100e514119e3a7ab49d520d20ef2c2a4")


# Register an event handler for Runtime.Notify events of the smart contract.
@smart_contract.on_notify
def sc_notify(event):
    logger.info("SmartContract Runtime.Notify event: %s", event)

    # Make sure that the event payload list has at least one element.
    if not isinstance(
            event.event_payload, ContractParameter
    ) or event.event_payload.Type != ContractParameterType.Array or not len(
            event.event_payload.Value):
        return

    # The event payload list has at least one element. As developer of the smart contract
Exemple #9
0
from neocore.KeyPair import KeyPair
import coinmarketcap
from neocore.BigInteger import BigInteger
from neo.Core.Helper import Helper

import random

# If you want the log messages to also be saved in a logfile, enable the
# next line. This configures a logfile with max 10 MB and 3 rotations:
# settings.set_logfile("/tmp/logfile.log", max_bytes=1e7, backup_count=3)

# Setup the smart contract instance
# This is online voting v0.5

#smart_contract_hash = "7dc2db1227a8518146dc41c55dfafa97d9a83c27"
smart_contract = SmartContract(smart_contract_hash)
#wallet_hash = 'Aaaapk3CRx547bFvkemgc7z2xXewzaZtdP'
#wallet_arr = Helper.AddrStrToScriptHash(wallet_hash).ToArray()

Wallet = None

buffer = None

normalisation = 300


def test_invoke_contract(args):
    if not Wallet:
        print("where's the wallet")
        return
    if args and len(args) > 0:
Exemple #10
0
from neo.Network.NodeLeader import NodeLeader
from twisted.internet import reactor, task
from neo.Core.Blockchain import Blockchain, Events
from neo.SmartContract.StateReader import StateReader
from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain
from neo.Settings import settings
from neocore.Cryptography.Crypto import Crypto
from neocore.UInt160 import UInt160

import discord

client = discord.Client()

DISCORD_TOKEN = ''
CHANNEL_ID = ''
smart_contract = SmartContract('2d838efcda02e9b6bc42ce21ce34acad14b58923')


@smart_contract.on_notify
def sc_notify(event):
    if len(event.event_payload):
        #print("***** got new notify payload {}".format(event.event_payload[0]))
        if event.event_payload[0].decode("utf-8") == 'new_king':
            address = event.event_payload[1]
            bounty = int(event.event_payload[2])
            newKingMessage = ''
            if len(event.event_payload[3]) > 0:
                name = event.event_payload[3].decode("utf-8", "ignore")
                newKingMessage = '{} is now king. Next bounty is {} TUT'.format(
                    name, bounty / 100000000)
            else:
Exemple #11
0
from logzero import logger

from twisted.internet import reactor, task

from neo.contrib.smartcontract import SmartContract
from neo.Network.NodeLeader import NodeLeader
from neo.Core.Blockchain import Blockchain
from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain
from neo.Settings import settings

from channel_manager.channel import get_channelnames_via_address, Channel, State
from channel_manager.manager import close_channel
from utils.channel import split_channel_name
from crypto.Cryptography.Helper import hash_to_wallet_address, bytes_to_hex_string, hex2interger

smart_contract = SmartContract(Configure["TNC"].replace("0x", ""))
ContractAddr = Configure["ContractAddr"]
DepositIN = []
DepositOut = []


# Register an event handler for Runtime.Notify events of the smart contract.
@smart_contract.on_notify
def sc_notify(event):
    logger.info("SmartContract Runtime.Notify event: %s", event)

    if not len(event.event_payload):
        return

    logger.info("- payload part 1: %s", event.event_payload[0].decode("utf-8"))
    tx_type = event.event_payload[0]
    def __init__(self, contract_hash, wallet_path, wallet_pass):
        super(LootMarketsSmartContract, self).__init__()
        self.daemon = True

        self.contract_hash = contract_hash
        self.wallet_path = wallet_path
        self.wallet_pass = wallet_pass

        self.smart_contract = SmartContract(contract_hash)
        self.invoke_queue = Queue()

        # Setup redis cache.
        self.redis_cache = redis.StrictRedis(host='localhost', port=6379, db=0)

        self.calling_transaction = None
        self.tx_in_progress = None
        self.wallet = None

        settings.set_log_smart_contract_events(False)

        # Setup handler for smart contract Runtime.Notify event.
        # Here we listen to all notify events.
        @self.smart_contract.on_notify
        def sc_notify(event):
            """ This method catches Runtime.Notify calls, and updates the relevant cache. """

            # Log the received smart contract event.
            logger.info("- SmartContract Event: %s", str(event))
            event_name = event.event_payload[0].decode("utf-8")

            # ==== General Events ====
            # Smart contract events that are not specific to a marketplace.

            # Event: balance_of
            if event_name == "balance_of":
                # Convert the given script hash to an address.
                script_hash = event.event_payload[1]
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)
                balance = int.from_bytes(event.event_payload[2], 'little')
                # Save the balance to the cache.
                logger.info("- Balance of %s updated to %s LOOT", address,
                            balance)
                self.redis_cache.set("balance:%s" % address, int(balance))
                return

            # Event: get_marketplace_owner
            if event_name == "get_marketplace_owner":
                marketplace = event.event_payload[1].decode("utf-8")
                script_hash = event.event_payload[2]
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)
                logger.info("- Owner of %s: %s", marketplace, address)
                self.redis_cache.set("owner:%s" % marketplace, address)
                return

            # ==== Marketplace Events ====
            # Events that are specific to a marketplace.

            # Get the name of the marketplace, if it is none this is not a marketplace operation, return.
            marketplace = event.event_payload[1]
            if marketplace is not None:
                marketplace = marketplace.decode("utf-8")
            else:
                return

            # Ignore smart contract events that are not on our marketplace being used.
            if marketplace != self.marketplace:
                return

            # Event: get_inventory
            if event_name == "get_inventory":
                # Convert the script hash to an address.
                script_hash = event.event_payload[2]
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)

                # After being converted from a byte to an int, append each element to the list.
                inventory = []
                for i in event.event_payload[3]:
                    item_id = int.from_bytes(i, 'little')
                    inventory.append(item_id)

                # Update the inventory in the redis cache.
                logger.info("- Setting inventory of %s to %s", address,
                            inventory)
                self.redis_cache.set("inventory:%s" % address, inventory)
                self.redis_cache.set("inventoryUpdatedAt:%s" % address,
                                     int(time.time()))

            # Event: get_all_offers
            if event_name == "get_all_offers":
                retrieved_offers = event.event_payload[2]
                # Decode all the offers given in the payload.
                offers = []
                for i in retrieved_offers:
                    # Offer is received like 'offer\x03' so we convert to 'offer3'.
                    # We don't want to show the cached offers to the players.
                    i = i.decode("utf-8")
                    index = ord(i.split('offer')[1])
                    offer_id = 'offer' + str(index)
                    if offer_id not in self.cached_offers:
                        offers.append(offer_id)

                # Log the information and save to the cache.
                logger.info("-Setting offers in marketplace: %s", offers)
                self.redis_cache.set("offers", offers)
                self.redis_cache.set("timeOffersUpdated", str(datetime.now()))

            # Event: get_offer
            if event_name == "get_offer":
                print("Event: get_offer")
                # Get all the relevant information about the offer.
                offer = event.event_payload[2]
                address = offer[0]
                offer_id_encoded = offer[1]

                # If the offer is empty, return.
                if not offer:
                    return

                # We receive the offer index sent from contract in format e.g. "offer\x03", convert to "offer3".
                index = ord(offer_id_encoded.decode().split('offer')[1])
                offer_id = 'offer' + str(index)

                # Decode the bytes into integers.
                item_id = int.from_bytes(offer[2], 'little')
                price = int.from_bytes(offer[3], 'little')

                # Convert the script hash to an address.
                script_hash = address
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)

                # Put the offer information in a list and save it to the redis cache with the offer id as the key.
                offer_information = [address, offer_id, item_id, price]
                logger.info("-Setting offer:%s to %s", offer_id,
                            offer_information)
                self.redis_cache.set(offer_id, offer_information)

            # Event: Market/Item operation
            # The game/operator must know if these operations were successfully completed within the smart contract.
            # All of these notify events are sent in the same format.
            if event_name in ("cancel_offer", "buy_offer", "put_offer",
                              "give_items", "remove_item"):
                # Convert the script hash to address.
                script_hash = event.event_payload[2]
                sh = UInt160.UInt160(data=script_hash)
                address = Crypto.ToAddress(sh)
                # Check if the operation was successfully completed within the smart contract.
                operation_successful = event.event_payload[3]
                # Save the address, and result to the cache with the event_name used as a key.
                self.redis_cache.set(event_name + "%s" % address,
                                     operation_successful)
                logger.info(
                    "-" + event_name + " of address %s was completed: %s",
                    address, operation_successful)
Exemple #13
0
from neo.Implementations.Notifications.LevelDB.NotificationDB import NotificationDB
from neo.Settings import settings

from neo.Network.api.decorators import json_response, gen_authenticated_decorator, catch_exceptions

from neo.Implementations.Wallets.peewee.UserWallet import UserWallet
from neo.Prompt.Commands.Invoke import InvokeContract, TestInvokeContract, test_invoke
from neo.contrib.smartcontract import SmartContract

import urllib.request


# setup the protocol to be used
PROTOCOL_CONFIG = os.path.join(parent_dir, "protocol.privnet.json")
# Setup the smart contract instance
smart_contract = SmartContract("0b93cde1096433b2d1d9ddf74f85a7c6e266c4dc")


@smart_contract.on_notify
def sc_notify(event):
    logger.info("SmartContract Runtime.Notify event: %s", event)

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

    # The event payload list has at least one element. As developer of the smart contract
    # you should know what data-type is in the bytes, and how to decode it. In this example,
    # it's just a string, so we decode it with utf-8:
    logger.info("- payload part 1: %s", event.event_payload[0].decode("utf-8"))
Exemple #14
0
from socket import *
from base58 import b58encode
from threading import Thread

from neo.Settings import settings
from neocore.Cryptography.Crypto import Crypto
from neo.Core.Blockchain import Blockchain
from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain
from neo.Implementations.Wallets.peewee.UserWallet import UserWallet
from neo.Network.NodeLeader import NodeLeader
from neo.Prompt.Commands.Invoke import InvokeContract, TestInvokeContract
from neo.contrib.smartcontract import SmartContract
from twisted.internet import reactor, task

contract_address = "3c6a0ee4cecadfd6d3fd06fd7e7eedfa6d57dfe1"
smart_contract = SmartContract(contract_address)


@smart_contract.on_notify
def sc_notify(event):
    global receiver

    if len(event.event_payload) != 3:
        return

    receiver.addGeo(event.event_payload)


class NRCReceiver:
    def __init__(self, walletPath, walletPwd):
        self.open_wallet(walletPath, walletPwd)
Exemple #15
0
from time import sleep

from logzero import logger
from twisted.internet import reactor, task

from neo.contrib.smartcontract import SmartContract
from neo.Network.NodeLeader import NodeLeader
from neo.Core.Blockchain import Blockchain
from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain
from neo.Settings import settings

from google.cloud import pubsub_v1

from neocore.Cryptography import Crypto

smart_contract = SmartContract(os.environ["CONTRACT"])
publisher = pubsub_v1.PublisherClient()
topic = publisher.topic_path("astrum-world", "neo")


def parse_arg(input):
    if isinstance(input, int):
        return input
    try:
        return input.decode('utf-8')
    except:
        pass
    if len(input) == 20:
        try:
            return Crypto.scripthash_to_address(input)
        except:
from neo.contrib.smartcontract import SmartContract
from neo.Network.NodeLeader import NodeLeader
from neo.Core.Blockchain import Blockchain
from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain
from neo.Settings import settings
from neocore.Cryptography.Crypto import Crypto, UInt160

from dotenv import load_dotenv
load_dotenv(os.path.abspath(os.path.join('.', '.env')))

# If you want the log messages to also be saved in a logfile, enable the
# next line. This configures a logfile with max 10 MB and 3 rotations:
# settings.set_logfile("/tmp/logfile.log", max_bytes=1e7, backup_count=3)

# Setup the smart contract instance
smart_contract = SmartContract("fdb94040d3578817cc9293f95b8ddae75d87ac57")


# Register an event handler for Runtime.Notify events of the smart contract.
@smart_contract.on_notify
def sc_notify(event):
    logger.info("SmartContract Runtime.Notify event: %s", event)

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

    # The event payload list has at least one element. As developer of the smart contract
    # you should know what data-type is in the bytes, and how to decode it. In this example,
    # it's just a string, so we decode it with utf-8: