Example #1
0
    def post(self):

        if (request.data.__len__() == 0):
            if (request.args.get('password', '') == None):
                key = Key.generate()
            else:
                key = Key.generate(request.args.get('password', ''))
        else:
            password = json.loads(request.data).get("password")
            if (password != ""):
                key = Key.generate(password)
            else:
                key = Key.generate()

        file_name = './{}.json'.format(key.public_key_hash())

        with open(file_name) as json_file:
            data = json.load(json_file)

        os.remove(file_name)

        #activate / reveal

        data['secret_key'] = key.secret_key()

        return data
Example #2
0
    def setUp(self):
        self.util = PtzUtils(flextesa_sandbox)
        # self.util = PtzUtils(pytezos)

        self.admin_key = self.util.client.key

        self.orig_contracts()

        self.mike_key = Key.generate(export=False)
        self.kyle_key = Key.generate(export=False)

        # self.transfer_init_funds()
        print("basic test setup completed")
Example #3
0
    def read_mnemonic(self, sess):
        k = Key.from_mnemonic(sess['mnemonic'],
                              passphrase=sess['password'],
                              email=sess['email'])
        p = pytezos.using(key=k, shell=sess['network'])

        return p
Example #4
0
    def test_should_set_new_admin(self):
        new_admin = Key.generate(export=False).public_key_hash()

        res = self.contract.set_admin(new_admin).interpret(storage=storage(), sender=first_signer_key.public_key_hash())

        self.assertEqual(first_signer_key.public_key_hash(), res.storage["admin"])
        self.assertEqual(new_admin, res.storage["pending_admin"])
    def read_secret(self, sess):
        k = Key.from_encoded_key(sess['secret'], passphrase=sess['password'])
        p = pytezos.using(key=k, shell=sess['network'])

        print(k.public_key_hash())

        return p
    def test_should_only_be_called_by_quorum_contract(self):
        with self.assertRaises(MichelsonRuntimeError) as context:
            payment_address = Key.generate(export=False).public_key_hash()
            self.bender_contract.signer_ops(signer_1_key, payment_address) \
                .interpret(storage=(valid_storage()),
                           sender=other_party)

        self.assertEqual("'NOT_SIGNER'", context.exception.args[-1])
Example #7
0
    def test_only_pending_admin_can_confirm(self):
        with self.assertRaises(MichelsonRuntimeError) as context:
            new_admin = Key.generate(export=False).public_key_hash()
            valid_storage = storage()
            valid_storage["pending_admin"] = new_admin

            self.contract.confirm_admin().interpret(storage=valid_storage, sender=first_signer_key.public_key_hash())

        self.assertEqual("'NOT_A_PENDING_ADMIN'", context.exception.args[-1])
Example #8
0
    def test_should_confirm_new_admin(self):
        new_admin = Key.generate(export=False).public_key_hash()
        valid_storage = storage()
        valid_storage["pending_admin"] = new_admin

        res = self.contract.confirm_admin().interpret(storage=valid_storage, sender=new_admin)

        self.assertEqual(new_admin, res.storage["admin"])
        self.assertEqual(None, res.storage["pending_admin"])
    def test_set_signer_payment_address(self):
        payment_address = Key.generate(export=False).public_key_hash()
        storage = valid_storage()

        res = self.bender_contract.signer_ops(signer_1_key, payment_address) \
            .interpret(storage=storage,
                       sender=super_admin)

        self.assertEqual(payment_address, res.storage["fees"]["signers"][signer_1_key])
Example #10
0
 def create_wallet(self, passphrase):
     mnemonic = Mnemonic('english').generate(128)
     key = Key.from_mnemonic(mnemonic, passphrase, curve=b'ed')
     if self.blockchain.name == 'tzlocal':
         # during tests, use sandbox accounts to avoid having to make time-eating transfers
         if 'DJBLOCKCHAIN_MOCK' in os.environ and os.environ[
                 'DJBLOCKCHAIN_MOCK']:
             key = self.get_sandbox_account()
     return key.public_key_hash(), key.secret_exponent
    def test_distribute_xtz_to_signer_registered_payment_address(self):
        signer_1_payment_address = Key.generate(export=False).public_key_hash()
        initial_storage = valid_storage()
        with_xtz_to_distribute(100, initial_storage)
        initial_storage["fees"]["signers"][signer_1_key] = signer_1_payment_address

        res = self.bender_contract.distribute_xtz([signer_1_key]).interpret(storage=initial_storage,
                                                                            sender=super_admin,
                                                                            self_address=self_address)

        self.assertEqual(50, self._xtz_of(signer_1_payment_address, res.storage))
Example #12
0
    def test_should_fail_on_bad_signature(self):
        with self.assertRaises(MichelsonRuntimeError) as context:
            payment_address = Key.generate(export=False).public_key_hash()
            signature = first_signer_key.sign(self._pack_set_payment_address(0, payment_address))

            current_storage = storage()
            current_storage["counters"][first_signer_id] = 1
            self.contract.set_signer_payment_address(minter_contract=minter_contract, signer_id=first_signer_id,
                                                     signature=signature).interpret(
                storage=current_storage,
                sender=payment_address, self_address=self_address, chain_id=chain_id)
        self.assertEqual("'BAD_SIGNATURE'", context.exception.args[-1])
Example #13
0
    def read_faucet(self, sess):

        faucet = sess['faucet']
        #print(faucet)
        path = './faucets/{}.json'.format(faucet['pkh'])

        with open(path, 'w') as outfile:
            json.dump(faucet, outfile)

        k = Key.from_faucet(path)
        p = pytezos.using(key=k, shell=sess['network'])

        return p
    def test_should_reject_other_transfers(self):
        with self.assertRaises(MichelsonRuntimeError) as context:
            storage = with_token_balance(initial_storage(), user, 100)
            destination = Key.generate(export=False).public_key_hash()

            self.contract.transfer([{
                "from_":
                user,
                "txs": [{
                    "to_": destination,
                    "token_id": 2,
                    "amount": 10
                }]
            }]).interpret(storage=storage, sender=user)
        self.assertEqual("'FA2_TOKEN_UNDEFINED'", context.exception.args[-1])
Example #15
0
    def test_should_set_signer_payment_address(self):
        payment_address = Key.generate(export=False).public_key_hash()
        signature = first_signer_key.sign(self._pack_set_payment_address(0, payment_address))

        res = self.contract.set_signer_payment_address(minter_contract=minter_contract, signer_id=first_signer_id,
                                                       signature=signature).interpret(
            storage=storage(),
            sender=payment_address, self_address=self_address, chain_id=chain_id)

        self.assertEqual(1, len(res.operations))
        op = res.operations[0]
        self.assertEqual(minter_contract, op["destination"])
        self.assertEqual('signer_ops', op["parameters"]["entrypoint"])
        self.assertEqual(michelson_to_micheline(
            f'(Pair "{first_signer_key.public_key_hash()}" "{payment_address}")'),
            op['parameters']['value'])
        self.assertEqual(1, res.storage["counters"][first_signer_id])
    def test_should_transfer_unfrozen(self):
        storage1 = initial_storage()
        storage = with_token_balance(storage1, user, 100)
        destination = Key.generate(export=False).public_key_hash()

        result = self.contract.transfer([{
            "from_":
            user,
            "txs": [{
                "to_": destination,
                "token_id": 0,
                "amount": 10
            }]
        }]).interpret(storage=storage, sender=user)

        self.assertEqual(10, balance_of(result.storage, destination))
        self.assertEqual(90, balance_of(result.storage, user))
    def test_operator_should_transfer_tokens(self):
        storage = with_token_balance(initial_storage(), user, 100)
        destination = Key.generate(export=False).public_key_hash()
        storage['assets']['operators'][(user, super_admin)] = None

        result = self.contract.transfer([{
            "from_":
            user,
            "txs": [{
                "to_": destination,
                "token_id": 0,
                "amount": 10
            }]
        }]).interpret(storage=storage, sender=super_admin)

        self.assertEqual(10, balance_of(result.storage, destination))
        self.assertEqual(90, balance_of(result.storage, user))
Example #18
0
    def get_client(self, private_key, reveal=False, sender=None):
        client = pytezos.using(
            key=Key.from_secret_exponent(private_key),
            shell=self.blockchain.endpoint,
        )
        if reveal:
            # key reveal dance
            try:
                operation = client.reveal().autofill().sign().inject()
            except RpcError as e:
                if 'id' in e.args[0] and 'previously_revealed_key' in e.args[
                        0]['id']:
                    return client
                raise e
            else:
                logger.debug(f'Revealing {sender}')
                opg = self.wait_injection(client, operation)
                if not opg:
                    raise ValidationError(f'Could not reveal {sender}')

        return client
from pathlib import Path
from unittest import TestCase

from pytezos import michelson_to_micheline, MichelsonRuntimeError, Key
from src.ligo import LigoContract

super_admin = 'tz1irF8HUsQp2dLhKNMhteG1qALNU9g3pfdN'
user = '******'
fees_contract = 'tz1et19hnF9qKv6yCbbxjS1QDXB5HVx6PCVk'
token_contract = 'KT1LEzyhXGKfFsczmLJdfW1p8B1XESZjMCvw'
nft_contract = 'KT1X82SpRG97yUYpyiYSWN4oPFYSq46BthCi'
other_party = 'tz3SYyWM9sq9eWTxiA8KHb36SAieVYQPeZZm'
self_address = 'KT1RXpLtz22YgX24QQhxKVyKvtKZFaAVtTB9'
dev_pool = Key.generate(export=False).public_key_hash()
staking_pool = Key.generate(export=False).public_key_hash()
signer_1_key = Key.generate(export=False).public_key_hash()
signer_2_key = Key.generate(export=False).public_key_hash()
signer_3_key = Key.generate(export=False).public_key_hash()


class MinterTest(TestCase):
    @classmethod
    def compile_contract(cls):
        root_dir = Path(__file__).parent.parent / "ligo"
        cls.bender_contract = LigoContract(root_dir / "minter" / "main.mligo", "main").compile_contract()

    @classmethod
    def setUpClass(cls):
        cls.compile_contract()
        cls.maxDiff = None
Example #20
0
def a_user():
    return Key.generate(export=False).public_key_hash()
Example #21
0
import unittest
from pathlib import Path

from pytezos import Key, MichelsonRuntimeError

from src.ligo import LigoContract
from unittest_data_provider import data_provider

reward_token = ("KT1VUNmGa1JYJuNxNS4XDzwpsc9N1gpcCBN2", 1)
stake_token = ("KT1LRboPna9yQY9BrjtQYDS1DVxhKESK4VVd", 0)
self_address = "KT1BEqzn5Wx8uJrZNvuS9DVHmLvG9td3fDLi"
reserve_contract = "KT1K7L5bQzqmVRYyrgLTHWNHQ6C5vFpYGQRk"
admin = Key.generate(export=False).public_key_hash()
scale = 10**16


class StakingContractTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        root_dir = Path(__file__).parent.parent / "ligo"
        cls.contract = LigoContract(
            root_dir / "staking" / "staking_main.mligo",
            "main").get_contract()


class DepositTest(StakingContractTest):
    def test_should_increase_balance_on_staking(self):
        user = a_user()
        storage = with_balance(user, 150, valid_storage(total_supply=10))

        res = self.contract.stake(100).interpret(storage=storage, sender=user)
Example #22
0
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask
from pytezos import pytezos, Key

from datetime import datetime, timezone
import atexit, base64, os, tempfile

oracle_address = os.environ['ORACLE_ADDRESS']
alpha_vantage_api_key = os.environ['ALPHA_VANTAGE_API_KEY']
alpha_vantage_ticker_symbol = os.environ['ALPHA_VANTAGE_TICKER_SYMBOL']

tezos_user_key = None
with tempfile.NamedTemporaryFile(suffix='.json', delete=False) as key_file:
    key_file.write(base64.standard_b64decode(os.environ['TEZOS_USER_KEY']))
    key_file.close()
    tezos_user_key = Key.from_faucet(key_file.name)
    os.remove(key_file.name)

class OracleServer:
    def __init__(self, api_key=alpha_vantage_api_key, ticker_symbol=alpha_vantage_ticker_symbol, tezos_key=tezos_user_key, oracle_contract_address=oracle_address):
        self.oracle_contract_address = oracle_contract_address
        self.pytezos_instance = pytezos.using(key=tezos_key, shell='carthagenet')
        self.time_series = TimeSeries(key=api_key, output_format='json')
        self.ticker_symbol = ticker_symbol

    def oracle_contract(self):
        return self.pytezos_instance.contract(self.oracle_contract_address)

    def update_value(self):
        try:
            now_utc = datetime.now(tz=timezone.utc)
Example #23
0
 def load_keystore(self):
     k = Key.from_encoded_key(os.getenv('TZ_SK_DEPLHI'),
                              passphrase=os.getenv('TZ_PASS_DELPHI'))
     return pytezos.using(key=k, shell=os.getenv('TZ_NETWORK'))
Example #24
0
        blocks = self.client.shell.blocks[-self.block_depth:]
        try:
            res = blocks.find_operation(op_hash)
            if not OperationResult.is_applied(res):
                raise RpcError.from_errors(
                    OperationResult.errors(res)) from op_hash
            print(pformat_consumed_gas(res))
            return res
        except StopIteration:
            # not found
            return None


flextesa_sandbox = pytezos.using(
    shell="http://localhost:20000",
    key=Key.from_encoded_key(
        "edsk3RFgDiCt7tWB2oe96w1eRw72iYiiqZPLu9nnEY23MYRp2d8Kkx"),
)


def token_metadata_literal(token_id, symbol, name, decimals):
    bsymbol = symbol.encode().hex()
    bname = name.encode().hex()
    bdecimals = str(decimals).encode().hex()
    return """{
        token_id = %sn;
        token_info = Map.literal [
          ("symbol", 0x%s);
          ("name", 0x%s);
          ("decimals", 0x%s);
        ];
    }
from pathlib import Path
from unittest import TestCase

from pytezos import Key, MichelsonRuntimeError

from src.ligo import LigoContract

super_admin = Key.generate(export=False).public_key_hash()
user = Key.generate(export=False).public_key_hash()
second_user = Key.generate(export=False).public_key_hash()
oracle_address = Key.generate(export=False).public_key_hash()
contract_address = 'KT1RXpLtz22YgX24QQhxKVyKvtKZFaAVtTB9'
dao_address = 'KT1Hd1hiG1PhZ7xRi1HUVoAXM7i7Pzta8EHW'


class GovernanceTokenTest(TestCase):
    @classmethod
    def compile_contract(cls):
        root_dir = Path(__file__).parent.parent / "ligo"
        cls.contract = LigoContract(
            root_dir / "fa2" / "governance" / "main.mligo",
            "main").compile_contract()

    @classmethod
    def setUpClass(cls):
        cls.compile_contract()
        cls.maxDiff = None


class Fa2Test(GovernanceTokenTest):
    def test_should_transfer_unfrozen(self):
Example #26
0
minter_contract = "KT1VUNmGa1JYJuNxNS4XDzwpsc9N1gpcCBN2"
chain_id = "NetXm8tYqnMWky1"
minter_ep = """(or
                 (or (pair %add_fungible_token (bytes %eth_contract) (pair %token_address address nat))
                     (pair %add_nft (bytes %eth_contract) (address %token_contract)))
                 (or (pair %mint_fungible_token
                        (bytes %erc_20)
                        (pair (pair %event_id (bytes %block_hash) (nat %log_index))
                              (pair (address %owner) (nat %amount))))
                     (pair %mint_nft
                        (bytes %erc_721)
                        (pair (pair %event_id (bytes %block_hash) (nat %log_index))
                              (pair (address %owner) (nat %token_id))))))"""
first_signer_id = "k51qzi5uqu5dilfdi6xt8tfbw4zmghwewcvvktm7z9fk4ktsx4z7wn0mz2glje"
second_signer_id = "k51qzi5uqu5dhuc1pto6x98woksrqgwhq6d1lff2hfymxmlk4qd7vqgtf980yl"
first_signer_key = Key.generate(curve=b'sp', export=False)
second_signer_key = Key.generate(curve=b'sp', export=False)
payload_type = michelson_to_micheline(f"(pair (pair chain_id address) (pair {minter_ep} address))")
self_address = "KT1BEqzn5Wx8uJrZNvuS9DVHmLvG9td3fDLi"


class QuorumContractTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        root_dir = Path(__file__).parent.parent / "ligo"
        cls.contract = LigoContract(root_dir / "quorum" / "multisig.mligo", "main").get_contract()


class SignerTest(QuorumContractTest):
    def test_accepts_valid_signature(self):
Example #27
0
import os.path
import requests
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

# The ID and range of a sample spreadsheet.
FOUNTAIN_SPREADSHEET_ID = '1fcMoCMw44mZvA2qR84Bdxfi90b0AEfINflPdiBqU3kg'
FOUNTAIN_RANGE_NAME = 'Form Responses 1!A2:I'

# Address: tz1UqhPnVXdPccrVsa5khscwCLHTF2Q2CAer
key = Key.from_encoded_key(os.environ['TEIA_FOUNTAIN_KEY'],
                           os.environ['TEIA_FOUNTAIN_PASS'])
pytezos = pytezos.using(shell='mainnet', key=key)
acct_id = pytezos.key.public_key_hash()
acct = pytezos.account()


def get_genesis(acct_id):
    url = f'https://api.tzkt.io/v1/bigmaps/522/keys?sort.asc=id&value.issuer={acct_id}&limit=1'
    r = requests.get(url)
    if r.status_code != 200:
        time.sleep(1)
        return get_genesis(acct_id)
    data = r.json()
    if len(data) > 0:
        return data[0]['key']
    return ''
Example #28
0
import unittest
from pathlib import Path

from pytezos import Key, MichelsonRuntimeError

from src.ligo import LigoContract
from unittest_data_provider import data_provider

reward_token = ("KT1VUNmGa1JYJuNxNS4XDzwpsc9N1gpcCBN2", 1)
stake_token = ("KT1LRboPna9yQY9BrjtQYDS1DVxhKESK4VVd", 0)
self_address = "KT1BEqzn5Wx8uJrZNvuS9DVHmLvG9td3fDLi"
reserve_contract = "KT1K7L5bQzqmVRYyrgLTHWNHQ6C5vFpYGQRk"
admin = Key.generate(export=False).public_key_hash()
burn_address = Key.generate(export=False).public_key_hash()
scale = 10 ** 16


class StackingContractTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        root_dir = Path(__file__).parent.parent / "ligo"
        cls.contract = LigoContract(
            root_dir / "stacking" / "stacking_main.mligo", "main"
        ).get_contract()


class DepositTest(StackingContractTest):

    def test_should_increase_balance_on_staking(self):
        user = a_user()
        storage = with_balance(user, 150, valid_storage(total_supply=10))