Example #1
0
def dumpaddress(fn,passphrase,address,coin):
	wallet = Wallet(fn).fromFile(passphrase)
	d = None
	for k in wallet.Keys:
		if k.address(VERWIF[coin][0]) == address:
			d = k.wif(VERWIF[coin][1])
	if d is None:
		return "ERROR: address not found!"
	else:
		d.update({ 'address':k.address(VERWIF[coin][0]) })
		return json.dumps(d, sort_keys=True, indent=4)
Example #2
0
def listaddresses(fn):
    keys = Wallet(fn).pubkeysOnly()
    a = []
    for k in keys:
        a.append({
            'address_type': k.address_type(),
            NETWORK: k.address(),
            'infiniti': k.address(True)
        })
    d = {"addresses": a}
    return json.dumps(d, sort_keys=True, indent=4)
Example #3
0
def listunspent(wallet_name,network=NETWORK):
	syncwallets()
	keys = Wallet(wallet_name).pubkeysOnly()
	balance = 0
	sync_height = getheight()
	results = {}
	for key in keys:
		addr = key.address(VERWIF[param_query(network,'network_shortname')][0])
		r = utxo_by_address(addr,network,sync_height)
		if r is not None:
			results.update({addr:r})
	return json.dumps(results, sort_keys=True, indent=4, cls=DecimalEncoder)
Example #4
0
    def test_clear_transaction(self):
        transaction_pool = TransactionPool()

        transaction1 = Transaction(Wallet(), "recipient_address", 1)
        transaction2 = Transaction(Wallet(), "recipient_address", 2)

        transaction_pool.add_transaction(transaction1)
        transaction_pool.add_transaction(transaction2)

        blockchain = Blockchain()
        blockchain.add_block(
            [transaction1.serialize(),
             transaction2.serialize()])

        self.assertIn(transaction1.id, transaction_pool.transactions)
        self.assertIn(transaction2.id, transaction_pool.transactions)

        transaction_pool.clear_transactions(blockchain)

        self.assertNotIn(transaction1.id, transaction_pool.transactions)
        self.assertNotIn(transaction2.id, transaction_pool.transactions)
Example #5
0
def signmessage(fn,passphrase,address,message):
	w = Wallet(fn).fromFile(passphrase)
	#try:
	infiniti = address[:1]=='i'
	for k in w.Keys:
		if k.address(infiniti) == address:
			sig = k.sign_msg(message)
	return json.dumps({
			"address":k.address(infiniti),
			"message":message,
			"signature":sig
		}, sort_keys=True, indent=4)
Example #6
0
    def test_calculate_balance(self):
        blockchain = Blockchain()
        wallet = Wallet()

        self.assertEqual(
            Wallet.calculate_balance(blockchain, wallet.address), STARTING_BALANCE
        )

        amount = 50
        transaction = Transaction(wallet, "recipient_address", amount)
        blockchain.add_block([transaction.serialize()])

        self.assertEqual(
            Wallet.calculate_balance(blockchain, wallet.address),
            STARTING_BALANCE - amount,
        )

        # Add some transactions where wallet receives an amount
        blockchain.add_block(
            [
                Transaction(Wallet(), wallet.address, 30).serialize(),
                Transaction(Wallet(), wallet.address, 75).serialize(),
            ]
        )

        self.assertEqual(
            Wallet.calculate_balance(blockchain, wallet.address),
            STARTING_BALANCE - amount + 30 + 75,
        )
Example #7
0
def newaddress(fn, passphrase, addr_type=0):
    """
	getnetaddress
	"""
    #try:
    wallet = Wallet(fn).fromFile(passphrase)
    # Address Types
    # addr_type == 0, deposit
    # addr_type == 1, change
    # addr_type == 2, staking
    # addr_type == 3, Dealer
    # Address types aren't programmatically important, but help to organize
    if addr_type is None:
        addr_type = 0
    k = wallet.create_address(save=True, addr_type=addr_type)
    dump = ({
        'address_type': k.address_type(),
        NETWORK: k.address(),
        'infiniti': k.address(True),
    })
    d = {"address": dump}
    return json.dumps(d, sort_keys=True, indent=4)
Example #8
0
    def is_valid(transaction):
        """Validates a transaction"""
        output_total = sum(transaction.output.values())

        if transaction.input == MINING_REWARD_INPUT:
            if list(transaction.output.values()) != [MINING_REWARD]:
                raise MiningRewardError()
            # return if mining reward is valid.
            return

        if transaction.input["amount"] != output_total:
            raise TransactionValuesError()

        if not Wallet.verify(
            transaction.input["public_key"],
            transaction.output,
            transaction.input["signature"],
        ):
            raise TransactionSignatureError()
Example #9
0
def listaddresses(fn,network):
	keys = Wallet(fn).pubkeysOnly()
	results = []

	q = [[],[],[],[]]
	for k in keys:
		q[k.addr_type()].append(k)

	for keys in q:
		_at = ''
		_attr = 0
		_chld = 0
		_keys = []
		for key in keys:
			a = []
			_at = key.address_type()
			_attr = key.addr_type()
			_chld = key.child()
			if network is None:
				for _k,v in VERWIF.iteritems():
					a.append({
							_k:k.address(v[0])
						})
			else:
				a.append({
						network:k.address(VERWIF[network][0])
					})
			a.append({
					'infiniti':k.address(103)
				})
			_keys.append({	'key' 			: 'm/0/{0}h/{1}'.format(_attr,_chld),
							'addresses'		: a,
				})
		_a = {
				'address_type' 	: _at,
				'keys':_keys
			}
		if len(_keys) > 0:
			results.append(_a)
	return json.dumps(results, sort_keys=True, indent=4)
Example #10
0
 def test_is_valid_reward_transaction(self):
     reward_transaction = Transaction.reward(Wallet())
     Transaction.is_valid(reward_transaction)
Example #11
0
def createwallet(passphrase,filename=None):
	seed,nonce = Wallet().create_seed()
	wallet = Wallet(filename).fromSeed(seed,nonce,passphrase,wallet_path=os.path.dirname(os.path.abspath(__file__)))
	wallet.update_status("height",str(_CONNECTION.parameters.start_height))
	wallet.update_status("utxo",json.dumps([]))
	wallet.update_status("current","ready")
	wallet.update_status("updated",str(0))
	d = {
		"passphrase":passphrase,
		"nonce" : binascii.hexlify(nonce),
		"seed":seed,
		"data_file":wallet._fn() 
	}
	return json.dumps(d, sort_keys=True, indent=4)
Example #12
0
    def test_invalid_reward_transaction_extra_recipient(self):
        reward_transaction = Transaction.reward(Wallet())
        reward_transaction.output["recipient_address"] = 50

        with self.assertRaises(MiningRewardError):
            Transaction.is_valid(reward_transaction)
Example #13
0
import datetime
import hashlib
import json
import multiprocessing
import time
import requests
import os
from flask import Flask, request
from miner.candidate_block import CandidateBlock
from wallet.wallet import Wallet

CHAIN_ENDPOINT = os.environ['CHAIN_ENDPOINT']

if __name__ == '__main__':
    wallet_miner = Wallet('wallet/miner.json')
    # kick off a block here
    candidateBlockContent = [wallet_miner.register_wallet_payload()]
    candidateBlock = CandidateBlock(0, 'xxx',
                                    json.dumps(candidateBlockContent),
                                    str(datetime.datetime.utcnow()))
    candidateBlock.mine()
    print(json.dumps(candidateBlock.returnBlockData(), indent=2))
    candidateBlockData = candidateBlock.returnBlockData()

    response = requests.post('{}/candidateblock'.format(CHAIN_ENDPOINT),
                             json.dumps(candidateBlockData),
                             headers={'Content-Type': 'application/json'})

    print(response.text)
Example #14
0
 def setUp(self):
     self.blockchain = Blockchain()
     for i in range(4):
         self.blockchain.add_block(
             [Transaction(Wallet(), "recipient_address", i).serialize()])
Example #15
0
 def test_transaction_amount_exceeds_balance(self):
     # Wallet starts with the default starting balance so ensure transaction amount exceeds that.
     with self.assertRaises(InsufficientFundsError):
         Transaction(Wallet(), "richard_west", 99999)
Example #16
0
from blockchain.blockchain import Blockchain, ChainReplacementError
from wallet.wallet import Wallet
from wallet.transaction import Transaction
from wallet.transaction_pool import TransactionPool
from flask_cors import CORS
from blockchain.block import BlockHelper


from pubsub import PubSub

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
# In future when app starts could broadcast a message saying node joined, then get a list of peers

blockchain = Blockchain()
wallet = Wallet(blockchain)
transaction_pool = TransactionPool()
pubsub = PubSub(blockchain, transaction_pool)


@app.route("/")
@app.route("/blockchain")
def get_blockchain():
    return jsonify(blockchain.serialize())


@app.route("/blockchain/range")
def get_blockchain_range():
    return jsonify(
        blockchain.serialize()[::-1][
            int(request.args.get("s")) : int(request.args.get("e"))
import os
import random
import requests
from flask import Flask, jsonify, request, render_template
from blockchain.blockchain import Blockchain
# from backend.app.src import blockchain
from wallet.wallet import Wallet
from wallet.transaction import Transaction
from wallet.transaction_pool import TransactionPool
from backend.pubsub import PubSub
app = Flask(__name__, template_folder='src')

blockchain = Blockchain()
wallet = Wallet()
transactionPool = TransactionPool()
pubsub = PubSub(blockchain, transactionPool)


@app.route('/')
def routeDefault():
    return render_template("index.html")


@app.route('/blockchain')
def routeBlockchain():
    return jsonify(blockchain.toJson())
    #return render_template("blockchain.html",ledger=blockchain.ledger)


@app.route('/blockchain/mine')
def routeBlockchainMine():
Example #18
0
    def sync(self, fn, passphrase, full=False):
        """
            Traverse the blockchain and update an index of all data belonging to addresses in this wallet
        """
        wallet = Wallet(fn).fromFile(passphrase)
        if full:
            wallet.update_status("height", str(self.parameters.start_height))
            utxo = []
            wallet.update_status("utxo", json.dumps(utxo))
        start_block = wallet.block_height()

        # Unspent transaction outputs
        utxo = json.loads(wallet.get_status("utxo"))
        # Spent transaction outputs
        stxo = []
        addresses = []
        transaction_value = []

        for k in wallet.Keys:
            addresses.append(k.address())

        info = self.getinfo()
        sys.stdout.write('Syncing.')
        sys.stdout.flush()
        wallet.update_status("current", "sync")
        try:
            current_status = wallet.get_status("current")
        except:
            current_status = 'ready'
        if current_status == 'sync':
            wallet.update_status("updated", str(int(time.time())))
            while info["blocks"] > start_block:
                block = self.getblockbynumber(start_block)
                if start_block > 0:
                    for tx_hash in block["tx"]:
                        raw = self.getrawtransaction(tx_hash)
                        tx = self.decoderawtransaction(raw)
                        """
                            Let's extract everything we need from this TX 
                            Create an index to this block and store all the data we need
                            Throw out the data we don't need
                        """
                        this_tx_reward = 0
                        this_tx_value = 0
                        this_tx_fees = 0
                        this_tx_unmodified_value = 0
                        this_tx_total_vin = 0
                        this_tx_total_vout = 0
                        proof_of_stake = False
                        # Gather up all of the inputs for addresses we own
                        for txin in tx["vin"]:
                            # Let's look back in time and see if this is our address
                            if not ("coinbase" in txin):
                                raw = self.getrawtransaction(txin["txid"])
                                txin_tx = self.decoderawtransaction(raw)
                                # Now lets loop through the old TX vout's to find us or not
                                for txout in txin_tx["vout"]:
                                    if txout["n"] == txin["vout"]:
                                        # We have a match, this one is ours we spent, so collect it
                                        intersection = list(
                                            set(txout["scriptPubKey"]
                                                ["addresses"])
                                            & set(addresses))
                                        if len(intersection) > 0:
                                            stxo.append({
                                                "txhash_in":
                                                txin["txid"],
                                                "txhash_out":
                                                tx_hash,
                                                "address":
                                                intersection[0],
                                                "value":
                                                txout["scriptPubKey"]["value"]
                                            })
                                            this_tx_total_vin += Decimal(
                                                txout["scriptPubKey"]["value"])
                        # Gather up all of the outputs for addresses we own
                        for txout in tx["vout"]:
                            try:
                                intersection = list(
                                    set(txout["scriptPubKey"]["addresses"])
                                    & set(addresses))
                            except:
                                # No addresses in this txout
                                intersection = ()
                            is_mine = (len(intersection) > 0)
                            if is_mine:
                                proof_of_stake = (txout['n'] == 0
                                                  and txout['value'] == 0)
                                if proof_of_stake and (
                                        txout['scriptPubKey']['type']
                                        == 'nonstandard' and txout['value'] > 0
                                        and txout['scriptPubKey']['asm']
                                        == ""):
                                    this_tx_reward = txout["value"]
                                else:
                                    for a in intersection:
                                        _new_val = txout["value"]
                                        utxo.append({
                                            "tx_hash": tx_hash,
                                            "value": _new_val,
                                            "address": a,
                                            "height": block["height"]
                                        })
                                        this_tx_unmodified_value += _new_val
                        this_tx_value = this_tx_unmodified_value - this_tx_total_vin - this_tx_reward
                        this_tx_fees = this_tx_unmodified_value - this_tx_total_vin - this_tx_reward - this_tx_value
                        if this_tx_value > 0:
                            transaction_value.append({
                                "txhash": tx_hash,
                                "value": this_tx_value,
                                "fees": this_tx_fees,
                                "reward": this_tx_reward
                            })
                info = self.getinfo()
                wallet.update_status("height", str(int(start_block)))
                if wallet.block_height() % 5 == 0:
                    sys.stdout.write('.')
                    sys.stdout.flush()
                start_block += 1
            for tx in utxo:
                for _tx in stxo:
                    if tx["tx_hash"] == _tx["txhash_in"]:
                        utxo.remove(tx)
            print "\n"
            wallet.update_status("utxo", json.dumps(utxo, cls=DecimalEncoder))
            wallet.update_status("current", "ready")
            wallet.update_status("updated", str(int(time.time())))
            return json.loads(wallet.get_status("utxo"))
Example #19
0
 def test_is_valid(self):
     Transaction.is_valid(Transaction(Wallet(), "recipient_address", 100))
Example #20
0
from wallet.wallet import Wallet

monEcran = Ecran()
mesBoutons = Boutons()
# monMenu = Menu(monEcran, mesBoutons)
menuComptes = Menu(monEcran, mesBoutons, "ecran/Comptes.txt")
menuPrincipal = Menu(monEcran, mesBoutons, "ecran/menuPrincipal.txt")
menuWifi = Menu(monEcran, mesBoutons, "ecran/hotspot.txt")
menuWelcome = Menu(monEcran, mesBoutons, "ecran/Welcome.txt")
ma_saisie = Alphabet(monEcran, mesBoutons)

menuWelcome.select()

fileWallet = "wallet.json"
w = Wallet(fileWallet)

if not os.path.isfile(fileWallet):
    monEcran.clear_scr()
    monEcran.draw_text("Creer un wallet avec", 0)
    monEcran.draw_text("l'interface web", 1)
    monEcran.display()
    mesBoutons.while_pressed("OK", 5000)
    while mesBoutons.getStatus("OK"):
        pass
    mesBoutons.while_pressed("OK", 60000)
    # activation du wifi
    en_hostspot()
    monEcran.clear_scr()
    monEcran.draw_text(ip(), 0)
    monEcran.draw_text(get_wifi_passwd(), 1)
def main():
    transaction = Transaction(Wallet(), 'receip', '1')
    transactionJson = transaction.toJson()
    restoredTransaction = transaction.fromJson(transactionJson)
    print(restoredTransaction.__dict__)
Example #22
0
    def test_transaction_update(self):
        sender_wallet = Wallet()
        first_recipient_address = "richard_west"
        first_recipient_amount = 25

        second_recipient_address = "jing_wang"
        second_recipient_amount = 25

        transaction = Transaction(sender_wallet, first_recipient_address,
                                  first_recipient_amount)

        # Update transaction
        transaction.update(sender_wallet, second_recipient_address,
                           second_recipient_amount)

        # Assert that transaction output contains the correct first recipient amount
        self.assertEqual(transaction.output[first_recipient_address],
                         first_recipient_amount)

        # Assert that transaction output contains the correct second recipients amount
        self.assertEqual(transaction.output[second_recipient_address],
                         second_recipient_amount)

        # Assert that transaction output contains the correct new/remaining balance of senders wallet
        self.assertEqual(
            transaction.output[sender_wallet.address],
            sender_wallet.balance - first_recipient_amount -
            second_recipient_amount,
        )

        # Verify the signature to ensure correctness. This will have been resigned.
        self.assertTrue(
            Wallet.verify(
                transaction.input["public_key"],
                transaction.output,
                transaction.input["signature"],
            ))

        # Test sending an additional amount to the same recipient
        first_recipient_additional_amount = 25
        transaction.update(sender_wallet, first_recipient_address,
                           first_recipient_additional_amount)

        # Assert that transaction output contains the correct first recipient amount
        self.assertEqual(
            transaction.output[first_recipient_address],
            first_recipient_amount + first_recipient_additional_amount,
        )

        # Assert that transaction output contains the correct new/remaining balance of senders wallet
        self.assertEqual(
            transaction.output[sender_wallet.address],
            sender_wallet.balance - first_recipient_amount -
            second_recipient_amount - first_recipient_additional_amount,
        )

        # Verify the signature to ensure correctness. This will have been resigned.
        self.assertTrue(
            Wallet.verify(
                transaction.input["public_key"],
                transaction.output,
                transaction.input["signature"],
            ))
Example #23
0
    def test_verify_invalid_signature(self):
        data = {"SHUcoin": "Is the best new cryptocurrency"}
        signature = Wallet().sign(data)

        # Pass an incorrect public key to verify method. This fails as the public key isn't a pair with the private key used to generate the signature.
        self.assertFalse(Wallet.verify(Wallet().public_key, data, signature))
def test_verifyInvalidSignature():
    data = {'foo': 'test data'}
    wallet = Wallet()
    signature = wallet.sign(data)

    assert not Wallet.verify(Wallet().public_key, data, signature) 
    class __Master(Server):
        def __init__(self):
            super(Master.__Master, self).__init__()
            self.balance = settings.MASTER_BALANCE
            self.wallet = Wallet()
            self.wallet.log_in(settings.MASTER_PASSWORD, settings.MASTER_LABEL,
                               settings.MASTER_ADDRESS_DIRECTORY)
            self.hardcoded_genesis_block()
            # self.add_genesis_block()

        def hardcoded_genesis_block(self):
            log.debug("Initializing genesis block (from file %s)" %
                      settings.GENESIS_BLOCK_FILE)
            with open(settings.GENESIS_BLOCK_FILE, 'r') as f:
                data = json.load(f)
            self.add_block(Block.parse(data))

        def add_genesis_block(self):
            addresses = settings.FIRST_ADDRESSES
            addresses_size = len(addresses)
            block = Block()
            for i in range(5):  # create the first 5 transactions
                destination_address = addresses[
                    i % addresses_size]  # if there's less than 5
                new_transaction = self.wallet.create_transaction(
                    destination_address, settings.FIRST_BALANCE)

                block.add_transaction(new_transaction)

            transactions_string = block.get_string_of_transactions()
            nonce = 0
            found = False
            while not found:  # hashing
                hash_object = hashlib.sha256(
                    str.encode(
                        transactions_string +
                        str(nonce)))  # b allows to concert string to binary
                block_header = hash_object.hexdigest()
                if block_header[:settings.
                                DIFFICULTY] == "0" * settings.DIFFICULTY:
                    found = True
                else:
                    nonce += 1
            block.header = block_header
            block.nonce = nonce

            self.add_block(block)

        def update_blockchain(self, block):
            """
            Add the block from the parameter if it's a valid one,
            otherwise reject it and return the bad transactions that
            made it invalid.
            """
            hash_verify = self.verify_hash(block)
            results = self.verify_transactions(block)
            if hash_verify and len(results) == 0:
                self.add_block(block)

            return (hash_verify, results)

        def verify_transactions(self, block):
            """
            Return a list of invalid transactions
            """
            bad_transactions = []
            senders_balance = dict()
            for transaction in block.transactions:
                if transaction.verify_signature():
                    sender_address = Address.generate_address(
                        transaction.sender_public_key)
                    if sender_address not in senders_balance:
                        senders_balance[
                            sender_address] = self.blockchain.get_balance(
                                sender_address)
                    if senders_balance[sender_address] >= transaction.amount:
                        senders_balance[sender_address] -= transaction.amount
                        if transaction.receiver not in senders_balance:
                            senders_balance[
                                transaction.
                                receiver] = self.blockchain.get_balance(
                                    transaction.receiver)
                        senders_balance[
                            transaction.receiver] += transaction.amount
                    else:
                        bad_transactions.append(transaction)
                else:
                    bad_transactions.append(transaction)

            return bad_transactions
Example #26
0
        except Exception as e:
            print(e)
            return {}
    return None


def IsOkToDrop(stock=None, wallet=None):
    if stock and wallet:
        if stock.IsDownTrend() and not wallet.HasStock(stock.ticker):
            print('Ok To Drop Stock: ', stock.ticker)
            return True
    return False


if __name__ == '__main__':
    wallet = Wallet(funds=1000, multiplier=0.25, stopLoss=0.8)
    wallet.Debug()
    stockList = None
    stocks = []
    run = True
    buy = True
    stocksWeeklyChecked = False
    stocksHourlyChecked = False
    stocksRefreshed = False
    openTime = 9
    closeTime = 16
    while run:
        #check if market is open
        if ((time.localtime()[3] >= openTime
             and time.localtime()[3] <= closeTime) and time.localtime()[6] < 5
                and stocksWeeklyChecked and stocksHourlyChecked):
Example #27
0
        # 404
        else:
            self.wfile.write(_html("<h1>requettes post non géré</h1>"))


def run(server_class=HTTPServer, handler_class=S, addr="0.0.0.0", port=80):
    server_address = (addr, port)
    httpd = server_class(server_address, handler_class)

    print(f"Starting httpd server on {addr}:{port}")
    httpd.serve_forever()


if __name__ == "__main__":
    fileWallet = "wallet.json"
    w = Wallet(fileWallet)

    parser = argparse.ArgumentParser(description="Run a simple HTTP server")
    parser.add_argument(
        "-l",
        "--listen",
        default="0.0.0.0",
        help="Specify the IP address on which the server listens",
    )
    parser.add_argument(
        "-p",
        "--port",
        type=int,
        default=80,
        help="Specify the port on which the server listens",
    )