def setUp(self): self.w = Wallet() self.blocks = BlockStorage() # self.block_writer = BlockStorage() self.driver = ContractDriver() self.ws = WebServer(wallet=self.w, contracting_client=ContractingClient(), blocks=self.blocks, driver=n) self.ws.client.flush() self.blocks.flush() self.ws.driver.flush() self.loop = asyncio.get_event_loop()
def test_bad_transaction_returns_a_TransactionException(self): tx = build_transaction(wallet=Wallet(), processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) _, response = self.ws.app.test_client.post('/', data=tx) self.assertDictEqual(response.json, { 'error': 'Transaction processor does not match expected processor.' })
def test_jeffs_contract_behavior(self): code = ''' state = Hash() @construct def seed(): state['thiskey', 'current'] = 'jeff' state['thiskey', 'next'] = 'stu' @export def testing(value): state['thiskey', 'current'] = 'tejas' state['thiskey', 'next'] = value ''' stu = Wallet() o = Orchestrator(2, 4, self.ctx) block_0 = [] block_0.append( o.make_tx(contract='submission', function='submit_contract', kwargs={ 'name': 'con_jeff', 'code': code }, sender=stu)) block_1 = [] block_1.append( o.make_tx(contract='con_jeff', function='testing', kwargs={'value': 'moomoo'}, sender=stu)) async def test(): await o.start_network await send_tx_batch(o.masternodes[0], block_0) await asyncio.sleep(2) await send_tx_batch(o.masternodes[0], block_1) await asyncio.sleep(2) loop = asyncio.get_event_loop() loop.run_until_complete(test())
def test_get_nonce_pending_nonce_is_not_none_returns_pending_nonce(self): w2 = Wallet() self.ws.nonces.set_pending_nonce(sender=w2.verifying_key, processor=self.w.verifying_key, value=123) _, response = self.ws.app.test_client.get('/nonce/{}'.format( w2.verifying_key)) expected = { 'nonce': 123, 'processor': self.w.verifying_key, 'sender': w2.verifying_key } self.assertDictEqual(response.json, expected)
def setUp(self): self.ctx = zmq.asyncio.Context() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) self.base_tcp = 'tcp://127.0.0.1:19000' self.base_wallet = Wallet() self.router = Router(socket_id=self.base_tcp, ctx=self.ctx, wallet=self.base_wallet, secure=True) self.authenticator = authentication.SocketAuthenticator( client=ContractingClient(), ctx=self.ctx) self.authenticator.add_verifying_key(self.base_wallet.verifying_key) self.authenticator.configure()
def test_check_tx_formatting_incorrect_processor_fails(self): w = Wallet() tx = build_transaction(wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123.0, 'to': 'jeff' }) decoded = decode(tx) with self.assertRaises(transaction.TransactionProcessorInvalid): transaction.check_tx_formatting(decoded, 'c' * 64)
def setUp(self): self.ws = WebServer(wallet=Wallet(), contracting_client=ContractingClient(), blocks=BlockStorage(), driver=ContractDriver(), topics=[SAMPLE_TOPIC]) asyncio.set_event_loop(asyncio.new_event_loop()) self.loop = asyncio.get_event_loop() self.server = self.loop.run_until_complete( asyncio.ensure_future( self.ws.app.create_server(host='0.0.0.0', port=self.ws.port, return_asyncio_server=True))) self.loop.run_until_complete( self.ws.sio.connect(f'http://localhost:{EVENT_SERVICE_PORT}')) self.websocket = None self.messages = []
def test_future_transactions_fine_if_in_expiry(self): w = Wallet() tx = build_transaction(wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) decoded = decode(tx) decoded['metadata']['timestamp'] += 4 transaction.transaction_is_not_expired(decoded)
def test_startup_and_blocks_from_network_object_works_no_wait(self): network = mocks.MockNetwork(ctx=self.ctx, num_of_masternodes=1, num_of_delegates=1) sender = Wallet() async def test(): await network.start() network.refresh() await network.make_and_push_tx( wallet=mocks.TEST_FOUNDATION_WALLET, contract='currency', function='transfer', kwargs={ 'amount': 1_000_000, 'to': sender.verifying_key } )
def test_transaction_valid_for_fixed_edges(self): w = Wallet() tx = build_transaction( wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': {'__fixed__': '1.0'}, 'to': 'jeff' } ) print(tx) decoded = decode(tx) client = ContractingClient() client.flush() client.set_var( contract='currency', variable='balances', arguments=[w.verifying_key], value=1_000_000 ) client.set_var( contract='stamp_cost', variable='S', arguments=['value'], value=20_000 ) transaction.transaction_is_valid( transaction=decoded, expected_processor='b' * 64, client=client, nonces=self.driver )
def test_transaction_is_not_expired_true_if_within_timeout(self): w = Wallet() tx = build_transaction( wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' } ) decoded = decode(tx) self.assertTrue(transaction.transaction_is_not_expired(decoded))
def test_check_tx_formatting_signature_fails(self): w = Wallet() tx = build_transaction(wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) decoded = decode(tx) decoded['payload']['sender'] = 'a' * 64 with self.assertRaises(transaction.TransactionSignatureInvalid): transaction.check_tx_formatting(decoded, 'b' * 64)
def test_check_tx_formatting_not_formatted_fails(self): w = Wallet() tx = build_transaction(wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) decoded = decode(tx) decoded['payload']['nonce'] = -123 with self.assertRaises(transaction.TransactionFormattingError): transaction.check_tx_formatting(decoded, 'b' * 64)
def test_future_transactions_raise_error_if_beyond_expiry(self): w = Wallet() tx = build_transaction(wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) decoded = decode(tx) decoded['metadata']['timestamp'] += 6 with self.assertRaises(transaction.TransactionInvalidTimestampError): transaction.transaction_is_not_expired(decoded)
def test_check_tx_formatting_succeeds(self): w = Wallet() tx = build_transaction( wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': decimal.Decimal('123.872345873452873459873459870'), 'to': 'jeff' }) decoded = decode(tx) error = transaction.check_tx_formatting(decoded, 'b' * 64) self.assertIsNone(error)
def test_transaction_is_expired_false_if_outside_timeout(self): w = Wallet() tx = build_transaction(wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) decoded = decode(tx) decoded['metadata']['timestamp'] -= 1000 with self.assertRaises(transaction.TransactionStaleError): transaction.transaction_is_not_expired(decoded)
def test_execute_tx_returns_successful_output(self): test_contract = ''' v = Variable() @construct def seed(): v.set('hello') @export def set(var: str): v.set(var) @export def get(): return v.get() ''' self.client.submit(test_contract, name='testing') self.client.raw_driver.commit() self.client.raw_driver.clear_pending_state() stu = Wallet() tx = transaction.build_transaction( wallet=stu, contract='testing', function='set', kwargs={'var': 'jeff'}, stamps=100_000, processor='0' * 64, nonce=0 ) e = execution.SerialExecutor(executor=self.client.executor) result = e.execute_tx(decode(tx), stamp_cost=20_000) self.assertEqual(result['status'], 0) self.assertEqual(result['state'][0]['key'], 'testing.v') self.assertEqual(result['state'][0]['value'], 'jeff') self.assertEqual(result['stamps_used'], 1)
def test_sign_works_properly(self): w = Wallet() tx = build_transaction(wallet=w, processor='b' * 64, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) decoded = decode(tx) res = verify(w.verifying_key, encode(decoded['payload']), decoded['metadata']['signature']) self.assertTrue(res)
def test_submit_transaction_error_if_queue_full(self): self.ws.queue.extend(range(10_000)) tx = build_transaction(wallet=Wallet(), processor=self.ws.wallet.verifying_key, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) _, response = self.ws.app.test_client.post('/', data=tx) self.assertDictEqual(response.json, {'error': 'Queue full. Resubmit shortly.'}) self.ws.queue.clear()
def test_tx_with_error_returns_exception(self): tx = build_transaction(wallet=Wallet(), processor=self.ws.wallet.verifying_key, stamps=123, nonce=0, contract='currency', function='transfer', kwargs={ 'amount': 123, 'to': 'jeff' }) tx = decode(tx) tx['payload']['stamps_supplied'] = -123 tx = encode(tx) _, response = self.ws.app.test_client.post('/', data=tx) self.assertDictEqual( response.json, {'error': 'Transaction is not formatted properly.'})
def test_execute_tx_returns_successful_output(self): test_contract = ''' v = Variable() @construct def seed(): v.set('hello') @export def set(var: str): v.set(var) @export def get(): return v.get() ''' self.client.submit(test_contract, name='testing') tx = TransactionBuilder( sender='stu', contract='testing', function='set', kwargs={'var': 'jeff'}, stamps=100_000, processor=b'\x00' * 32, nonce=0 ) tx.sign(Wallet().signing_key) tx.serialize() result = execution.execute_tx(self.client, tx.struct) print(result) self.assertEqual(result.status, 0) self.assertEqual(result.state[0].key, b'testing.v') self.assertEqual(result.state[0].value, b'"jeff"') self.assertEqual(result.stampsUsed, 0)
def __init__(self, ctx, index=1, genesis_path=os.path.dirname(os.path.abspath(__file__))): self.wallet = Wallet() self.index = index port = 18000 + index self.ip = f'tcp://127.0.0.1:{port}' self.raw_driver = Driver(collection=f'state-{self.index}') self.driver = ContractDriver(driver=self.raw_driver) self.driver.flush() self.nonces = storage.NonceStorage(nonce_collection=f'nonces-{self.index}', pending_collection=f'pending-{self.index}') self.nonces.flush() self.ctx = ctx self.bootnodes = {} self.constitution = {} self.ready_to_start = False self.started = False self.obj = None self.genesis_path = genesis_path
def test_stamp_deduction_on_fail(self): test_contract = ''' @export def eat_stamps(): while True: pass ''' self.client.submit(test_contract, name='testing') self.client.raw_driver.commit() self.client.raw_driver.clear_pending_state() stu = Wallet() self.client.raw_driver.set(f'currency.balances:{stu.verifying_key}', 100000) tx = transaction.build_transaction( wallet=stu, contract='testing', function='eat_stamps', kwargs={}, stamps=10000, processor='0' * 64, nonce=0 ) e = execution.SerialExecutor(executor=self.client.executor) self.client.executor.metering = True result = e.execute_tx(decode(tx), stamp_cost=200) self.assertEqual(result['status'], 1) self.assertEqual(result['state'][0]['key'], f'currency.balances:{stu.verifying_key}') self.assertEqual(result['state'][0]['value'], Decimal('99950.0')) self.assertEqual(result['stamps_used'], 10000)
def test_is_valid_voter_false_for_others(self): r = self.upgrade.run_private_function(f='is_valid_voter', address=Wallet().verifying_key) self.assertFalse(r)
def test_process_message_good_and_bad_sbc_doesnt_pass_to_q(self): ### GOOD SBC tx_1_1 = { 'something': 'who_cares' } tx_1_2 = { 'something_else': 'who_cares' } txs = [encode(tx).encode() for tx in [tx_1_1, tx_1_2]] expected_tree = merklize(txs) w = Wallet() input_hash = 'something' signature = w.sign(expected_tree[0]) sbc_1 = { 'subblock': 0, 'transactions': [tx_1_1, tx_1_2], 'input_hash': input_hash, 'signer': w.verifying_key, 'merkle_tree': { 'signature': signature, 'leaves': expected_tree } } ### BAD SBC tx_2_1 = { 'something': 'who_cares2' } tx_2_2 = { 'something_else': 'who_cares2' } txs = [encode(tx).encode() for tx in [tx_2_1, tx_2_2]] expected_tree = merklize(txs) w = Wallet() input_hash = 'something2' signature = w.sign(expected_tree[0]) expected_tree[1] = 'crap' sbc_2 = { 'subblock': 1, 'transactions': [tx_2_1, tx_2_2], 'input_hash': input_hash, 'signer': w.verifying_key, 'merkle_tree': { 'signature': signature, 'leaves': expected_tree } } s = contender.SBCInbox() loop = asyncio.get_event_loop() if loop.is_closed(): loop = asyncio.new_event_loop() loop.run_until_complete(s.process_message([sbc_1, sbc_2])) self.assertEqual(s.q, [])
from lamden.crypto.wallet import Wallet # Create a new wallet with a new key pair wallet = Wallet() # Wallet address address = wallet.verifying_key # Wallet private key privkey = wallet.signing_key print("address", address) print("privkey", privkey) # Example output # address 77b9c48aa5e43d5bff575140f484bbda55ad2a619160b5eb5c04d8f27f437686 # privkey 01c4763eadd4285cc31fdd60dedb4fa7c68f29e325775dc7f7f082bbab9b5fc9
import json import time import requests from lamden.crypto.transaction import build_transaction from lamden.crypto.wallet import Wallet # Private key to send TAU from privkey = "01c4763eadd4285cc31fdd60dedb4fa7c68f29e325775dc7f7f082bbab9b5fc9" # Generate wallet to send TAU from wallet = Wallet(privkey) # Public address to send TAU from address = wallet.verifying_key # Amount of TAU to send amount = 10 # Maternode URL (testnet) url = "https://testnet-master-1.lamden.io" # Get nonce for our address nonce = requests.get(f"{url}/nonce/{address}") nonce = json.loads(nonce.text) # List of addresses to send TAU to addresses = [ "b0bb69bb8722e0b3364ada9d1d96675e8025f552e7d03770618c43b7df0584a5", "523e4db1ad94e8c70d63b788b4a4356e5fd9f026b3f1b16e115386fdb70ffb4d" ]
import requests import logging import tweepy import time import json import os from tweepy import Stream, StreamListener from lamden.crypto.transaction import build_transaction from lamden.crypto.wallet import Wallet USER_FILE = "users.txt" user_list = list() bot_wallet = Wallet(BOT_PRIVKEY) def is_address_valid(address: str): """ Check if the given address is valid """ if not len(address) == 64: return False try: int(address, 16) except: return False return True def add_user(user: str): user_list.append(str(user))
def test_startup_with_manual_node_creation_and_single_block_works(self): m = mocks.MockMaster(ctx=self.ctx, index=1) d = mocks.MockDelegate(ctx=self.ctx, index=2) bootnodes = { m.wallet.verifying_key: m.ip, d.wallet.verifying_key: d.ip } constitution = { 'masternodes': [m.wallet.verifying_key], 'delegates': [d.wallet.verifying_key] } m.set_start_variables(bootnodes, constitution) d.set_start_variables(bootnodes, constitution) sender = Wallet() async def test(): await asyncio.gather( m.start(), d.start() ) tx_1 = transaction.build_transaction( wallet=mocks.TEST_FOUNDATION_WALLET, contract='currency', function='transfer', kwargs={ 'amount': 1_000_000, 'to': sender.verifying_key }, stamps=10000, nonce=0, processor=m.wallet.verifying_key ) tx_2 = transaction.build_transaction( wallet=sender, contract='currency', function='transfer', kwargs={ 'amount': 1338, 'to': 'jeff' }, stamps=5000, nonce=0, processor=m.wallet.verifying_key ) async with httpx.AsyncClient() as client: await client.post('http://0.0.0.0:18081/', data=tx_1) await asyncio.sleep(2) await client.post('http://0.0.0.0:18081/', data=tx_2) await asyncio.sleep(2) await asyncio.sleep(2) m.stop() d.stop() self.loop.run_until_complete(test()) # dbal = dld.get_var(contract='currency', variable='balances', arguments=['jeff']) mbal = m.driver.get_var(contract='currency', variable='balances', arguments=['jeff']) # self.assertEqual(dbal, 1338) self.assertEqual(mbal, 1338)
from lamden.crypto.wallet import Wallet from lamden.crypto import transaction from contracting.db.driver import ContractDriver, Driver from lamden import storage from lamden.nodes import masternode, delegate import asyncio import random import httpx from lamden.logger.base import get_logger import os MOCK_FOUNDER_SK = '016afd234c03229b44cfb3a067aa6d9ec3cd050774c6eff73aeb0b40cc8e3a12' TEST_FOUNDATION_WALLET = Wallet(MOCK_FOUNDER_SK) class MockNode: def __init__(self, ctx, index=1, genesis_path=os.path.dirname(os.path.abspath(__file__))): self.wallet = Wallet() self.index = index port = 18000 + index self.ip = f'tcp://127.0.0.1:{port}' self.raw_driver = Driver(collection=f'state-{self.index}') self.driver = ContractDriver(driver=self.raw_driver) self.driver.flush() self.nonces = storage.NonceStorage(nonce_collection=f'nonces-{self.index}', pending_collection=f'pending-{self.index}') self.nonces.flush()