示例#1
0
    def initCoin(self):

        #generate some walets
        Coinbase = wlt.Wallet()
        walletA = wlt.Wallet()

        #send 100 coins to walleta
        genesisTransaction = txn.Transaction(Coinbase.PublicKey,
                                             walletA.PublicKey, 100, 0, None)
        genesisTransaction.GenerateTransactionSignature(Coinbase.PrivateKey)

        #give the transaction a manual hash
        genesisTransaction.TransactionHash = "0"
        genesisTransaction.TransactionOutputs.append(
            outs.TransactionOutput(genesisTransaction.Recipient,
                                   genesisTransaction.Value,
                                   genesisTransaction.TransactionHash))
        self.UTXOs[genesisTransaction.TransactionOutputs[0].Id] = {
            "Transaction": genesisTransaction.TransactionOutputs[0]
        }

        print("create and mine genesis block")
        genesis = bl.Block("0")
        genesis.AddTransaction(genesisTransaction, self)
        self.AddBlock(genesis)
示例#2
0
    def Genesis(self):

        #generate some walets
        Coinbase1 = wlt.Wallet()
        self.Coinbase = wlt.Wallet()

        #send 10000 coins to coinbase
        genesisTransaction = txn.Transaction(
            Coinbase1.PEMPublicKey.decode(),
            self.Coinbase.PEMPublicKey.decode(), 100000, 0, None)
        genesisTransaction.GenerateTransactionSignature(Coinbase1.PrivateKey)
        self.GenesisTransaction = genesisTransaction

        #give the transaction a manual hash
        genesisTransaction.TransactionHash = "0"
        genesisTransaction.TransactionOutputs.append(
            outs.TransactionOutput(genesisTransaction.Recipient,
                                   genesisTransaction.Value,
                                   genesisTransaction.TransactionHash, 0))
        self.UTXOs[genesisTransaction.TransactionOutputs[0].Id] = {
            "Transaction": genesisTransaction.TransactionOutputs[0]
        }

        print("create and mine genesis block")
        genesis = bl.Block("0")
        genesis.AddTransaction(genesisTransaction, self)
        self.AddBlock(genesis)
示例#3
0
def test():
    """Test cases """
    print("Testing Message")
    Message.test()
    print("Testing PublicKey")
    PublicKey.test()
    print("Testing PrivateKey")
    PrivateKey.test()
    print("Testing PublicKeyMap")
    PublicKeyMap.test()
    print("Testing Wallet")
    Wallet.test()
    print("Testing SampleWallet")
    SampleWallet.test()
    print("Testing TxOutput")
    TxOutput.test()
    print("Testing TxOutputList")
    TxOutputList.test()
    print("Testing TxInputUnsigned")
    TxInputUnsigned.test()
    print("Testing TxInput")
    TxInput.test()
    print("Testing TxInputList")
    TxInputList.test()
    print("Testing AccountBalance")
    AccountBalance.test()
示例#4
0
    def setUp(self):
        self.settings = Blockchain.ChainSettings()
        self.ha = HashAlgorithm.SHA256HashAlgorithm()
        self.ca = ConsensusAlgorithm.ProofOfWorkAlgorithm(
            self.ha, self.settings)
        self.bc = Blockchain.Blockchain(self.ca, self.ha, self.settings)

        self.wallet1 = Wallet.Wallet('geheim')
        self.wallet2 = Wallet.Wallet('other')
        self.wallet3 = Wallet.Wallet('bla')
示例#5
0
    def test_transaction_creation(self):
        wallet_sender = Wallet.Wallet('geheim')
        wallet_receiver = Wallet.Wallet('other')

        transaction = wallet_sender.create_transaction(
            wallet_receiver.get_public_address(), 100.0)

        transaction_compare = Transaction.Transaction(
            wallet_sender.get_public_address(),
            wallet_receiver.get_public_address(), 100.0)
        transaction_compare.signature = transaction.signature
        print(transaction)
        self.assertEqual(transaction, transaction_compare)
示例#6
0
    def initCoin(self):

        #generate some walets
        Coinbase = wlt.Wallet()

        #send 100 coins to walleta
        genesisTransaction = txn.Transaction(
            Coinbase.PEMPublicKey.decode(),
            self.mainWallet.PEMPublicKey.decode(), 10000000000, 0, None)
        genesisTransaction.GenerateTransactionSignature(Coinbase.PrivateKey)

        #give the transaction a manual hash
        genesisTransaction.TransactionHash = "0"
        genesisTransaction.TransactionOutputs.append(
            outs.TransactionOutput(genesisTransaction.Recipient,
                                   genesisTransaction.Value,
                                   genesisTransaction.TransactionHash, 0))
        self.UTXOs[genesisTransaction.TransactionOutputs[0].Id] = {
            "Transaction": genesisTransaction.TransactionOutputs[0]
        }
        self.Genesis = genesisTransaction

        print("create and mine genesis block")
        genesis = bl.Block("0")
        genesis.AddTransaction(genesisTransaction, self)
        self.AddBlock(genesis)
        self.AcceptedBlocks.append(genesis)
        self.node.AcceptedBlockData = self.AcceptedBlocks
        self.SendGenesisData(Coinbase, self.mainWallet)
示例#7
0
    def get_wallet_by_id(self, wallet_id):
        w = None
        conn = self.connect()
        cur = conn.cursor()

        query = """SELECT
                 w.wallet_id,
                 w.wallet_nid,
                 w.wallet_name,
                 w.wallet_key,
                 wb.wallet_balance
                 FROM wallets w
                 JOIN wallet_balances wb ON wb.wallet_nid = w.wallet_nid
                 WHERE w.wallet_id = %s"""

        result = cur.execute(query, (wallet_id, ))

        row = cur.fetchone()
        if row:
            w = Wallet.Wallet(row[2], row[3], row[0])
            w.nid = int(row[1])
            w.balance = decimal.Decimal(row[4])

        cur.close()
        conn.close()

        return w
示例#8
0
def stopWallet():
    global tWS
    # Stop WalletServer
    Wallet.StopAll()
    if tWS: tWS.join()
    tWS = None
    # Save head_blocks
    return True
示例#9
0
    def test_sender_receiver_equal_error(self):
        wallet = Wallet.Wallet('other')

        with self.assertRaises(RuntimeError) as context:
            wallet.create_transaction(wallet.get_public_address(), 100.0)
        self.assertTrue(
            'Receiver address can not be the same like sender address.' in str(
                context.exception))
示例#10
0
 def __init__(self, name, initial_cash, initial_chips):
     self.__name = name #initialize the name
     self.__wallet = Wallet(initial_cash) #initialize the Wallet
     self.__chips = ChipBag(initial_chips) #initialize the ChipBag
     self.__saturation = 10 #just ate
     self.__hunger = 0 #not hungry
     self.__fatigue = 0 #not tired
     self.__rep = 0 #no reputation
示例#11
0
def Ruby_numpy (candles, initial_USD, ema1=8, ema2=32, ema3=41, buy_t=0.01, sell_t=0.03):
	"""
	candles: Expecting a list of lists, each candle being [unix_timestamp, Open,
	         High, Low, Close ]
	"""
	# in percent
	buy_threshold  = buy_t    #Default .3%
	sell_threshold = sell_t   #Defaul  .5%
	wallet = Wallet.sim_wallet(5000, 0, 0.55);
	np_candles = np.array(candles)

	# Generate the EMAs
	EMA1  = numpy_moving_average(np_candles[:,4].astype(float), ema1, type='exponential')
	EMA2  = numpy_moving_average(np_candles[:,4].astype(float), ema2, type='exponential')
	EMA3  = numpy_moving_average(np_candles[:,4].astype(float), ema3, type='exponential')

	np_candles_ema = np.column_stack ((np_candles, EMA1,  EMA2, EMA3 ))

	Current_USD = initial_USD
	Current_BTC = 0
	Status = "init"

	for candle in np_candles_ema:
		t_ema1  = candle[5]
		t_ema2  = candle[6]
		t_ema3  = candle[7]
		if  t_ema1 > t_ema3 and t_ema3 > t_ema2 and t_ema1-t_ema3 > candle[4]*buy_threshold and Status != "long" :

			#Current_BTC = Current_USD*(1-0.0055)/candle[4]
			#Current_USD = 0.0
			#print '[BUY BTC ] price:{0:.5f}   BTC:{1:.5f}   USD:{2:.5f}  <{3}> '.format(
			#	candle[4], Current_BTC, Current_USD, datetime.datetime.fromtimestamp(int(candle[0])).strftime('%Y-%m-%d %H:%M:%S'))
			wallet.buy_all(candle[4], candle[0]);
			Status = "long"

		elif t_ema2 > t_ema3 and t_ema3 > t_ema1 and t_ema2-t_ema1 > candle[4]*sell_threshold and Status == "long":

			#Current_USD = Current_BTC*(1-0.0055)*candle[4]
			#Current_BTC = 0.0
			#print '[SELL BTC] price:{0:.5f}   BTC:{1:.5f}   USD:{2:.5f}  <{3}> '.format(
			#	candle[4], Current_BTC, Current_USD, datetime.datetime.fromtimestamp(int(candle[0])).strftime('%Y-%m-%d %H:%M:%S'))
			wallet.sell_all(candle[4], candle[0]);
			Status = "short"

		elif t_ema1-t_ema3 > candle[4]*buy_threshold and Status == "init" :

			#Current_BTC = Current_USD*(1-0.0055)/candle[4]
			#Current_USD = 0.0
			#print '[BUY BTC ] price:{0:.5f}   BTC:{1:.5f}   USD:{2:.5f}  <{3}> '.format(
		    #  	candle[4], Current_BTC, Current_USD, datetime.datetime.fromtimestamp(int(candle[0])).strftime('%Y-%m-%d %H:%M:%S'))
			wallet.buy_all(candle[4], candle[0]);
			Status = "long"

	#if ( Status == "long" ) :
		#Current_USD = Current_BTC*(1-0.0055)*candles[-1][4]

	return wallet.get_balance(candles[-1][4], candles[-1][0]);
示例#12
0
    def __init__(self, _Network):
        self.Blockchain = []
        self.AlternativeCoins = []
        self.OpenOrders = []
        self.UTXOs = dict()
        self.Markets = []

        self.Network = _Network
        self.MakeBlock = False
        self.MainWallet = wlt.Wallet()
示例#13
0
 def __init__(self, value, rate):
     wallet = Wallet()
     wallet.buy(self, (float(value)))
     wallet.set_eur(0)
     self.delay = rate
     get_initial_values(self.delay)
     self.main()
示例#14
0
def test():
    wallet = Wallet()
    delay = int(input("At what rate do you wanna trade in seconds"))
    wallet.buy(float(input("How much do you wanna invest")))
    wallet.set_eur(0)
    get_initial_values(delay)
    main()
示例#15
0
    def CreateArtificialTransactions(self):

        wallet2 = wlt.Wallet()
        #          tx = self.mainWallet.CreateNewCoin(self,"HephCoin", "Heph", 100000)
        #          self.BroadCastTransaction(tx)

        while True:

            time.sleep(2)

            tx = self.mainWallet.SendFunds(wallet2.PEMPublicKey.decode(), 5,
                                           self)
            self.BroadCastTransaction(tx)
示例#16
0
def create_wallets(relayPorts,numWalletsPerRelay):
    """
    Create wallets for ports in relayPorts list.
    For an index of the relayPorts list, the function creates n wallets, n being the value of the numWalletsPerRelay list for this index.
    """

    passwordList=[]
    walletList=[]
    print("Creating of wallets:")
    for portIndex,numWallet in enumerate(numWalletsPerRelay): 
        for _ in range(numWallet):
            print("Wallet "+str(len(walletList))+" created.")
            password=''.join(random.choice(string.ascii_letters+string.digits) for _ in range(16))
            passwordList.append(password)            
            walletList.append(Wallet.Wallet(relayPorts[portIndex],password))
    
    print("")
    return walletList,passwordList
示例#17
0
    def __init__(self):
        self.wallets = []
        self.mainWallet = wlt.Wallet()
        self.wallets.append(self.mainWallet)
        self.node = node.Node()
        self.AcceptedBlocks = []
        self.Blockchain = []
        self.UTXOs = dict()
        self.MinimumTransactionValue = 0.000000000001
        self.ConstructMode = False
        self.Validators = dict()
        self.CandidateBlocks = []
        self.TemporaryBlocks = []
        self.TransactionQue = []
        self.Announcement = ""
        self.Genesis = ""
        self.State = 0

        #start the blockchain
        self.StartClient()
示例#18
0
    def get_wallet_by_address(self, wallet_address):  # todo rework this
        w = None
        conn = self.connect()
        cur = conn.cursor()

        if wallet_address.is_alias():
            query = """SELECT
                w.wallet_id,
                w.wallet_nid,
                w.wallet_name,
                w.wallet_key,
                wb.wallet_balance
                FROM wallets w
                JOIN wallet_aliases wa ON wa.wallet_nid = w.wallet_nid
                JOIN wallet_balances wb ON wb.wallet_nid = w.wallet_nid
                WHERE wa.alias = %s"""

            result = cur.execute(query, (wallet_address.alias(), ))
        else:
            query = """SELECT
                w.wallet_id,
                w.wallet_nid,
                w.wallet_name,
                w.wallet_key,
                wb.wallet_balance
                FROM wallets w
                JOIN wallet_balances wb ON wb.wallet_nid = w.wallet_nid
                WHERE w.wallet_id = %s"""

            result = cur.execute(query, (wallet_address.alias(), ))

        row = cur.fetchone()
        if row:
            w = Wallet.Wallet(row[2], row[3], row[0])
            w.nid = int(row[1])
            w.balance = decimal.Decimal(row[4])

        cur.close()
        conn.close()

        return w
示例#19
0
    def get_submissions(self, challenge_id):
        submissions = []
        conn = self.connect()
        cur = conn.cursor()

        query = """SELECT
                        s.submission_id,
                        s.challenge_id,
                        s.nonce,
                        s.hash,
                        s.submitted_on,
                        w.wallet_nid,
                        w.wallet_id,
                        w.wallet_key,
                        w.wallet_name,
                        wb.wallet_balance,
                        s.remote_ip
                    FROM submissions s
                    JOIN wallets w ON s.wallet_nid = w.wallet_nid
                    JOIN wallet_balances wb ON wb.wallet_nid = s.wallet_nid
                    WHERE s.challenge_id = %s
                    ORDER BY s.submitted_on"""

        rs = cur.execute(query, (challenge_id, ))

        for row in cur.fetchall():
            wallet = Wallet.Wallet(row[8], row[7], row[6])
            wallet.nid = int(row[5])
            wallet.balance = decimal.Decimal(row[9])

            submission = Submission(int(row[1]), int(row[2]), wallet, row[10])
            submission.id = int(row[0])
            submission.submitted_on = int(row[4])

            submissions.append(submission)

        cur.close()
        conn.close()
        return submissions
示例#20
0
    def __init__(self, population, agent_id, inherited_model=None):
        self.population = population
        self.wallet = Wallet.Wallet(self.population.starting_cash,
                                    self.population.starting_price,
                                    self.population.trading_fee)
        self.agent_id = agent_id

        self.score = 0
        self.fitness = 0
        self.model = None

        self.BUY = 1
        self.SELL = 2
        self.SLEEP = 3

        if inherited_model:
            model_copy = clone_model(inherited_model)
            model_copy.set_weights(inherited_model.get_weights())
            self.model = model_copy
            self.mutate()
        else:
            self.model = self.population.model_builder()
示例#21
0
    def get_wallets(self, start=0, count=100):
        wallets = []
        end = start + count
        conn = self.connect()
        cur = conn.cursor()

        query = """SELECT wallet_nid, wallet_id, wallet_name, wallet_key FROM wallets LIMIT %s, %s"""
        result = cur.execute(query, (
            start,
            end,
        ))

        rows = cur.fetchall()

        for row in rows:
            w = Wallet.Wallet(row[2], row[3], row[1])
            w.nid = row[0]
            wallets.append(w)

        cur.close()
        conn.close()

        return wallets
示例#22
0
    except:
        print("Error: unable to start thread " + str(i))
sleep(0.5)



print('Miner1 comes in ...')
password2 = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(16))
Miner1 = Miner.Miner(1,relayPorts[0],password2)
print('Miner1 mines a Block ...')
Miner1.do_pow()
print('Miner1 gets bonus, now Miner 1 has 10 coins: ')
print("Miner1 has: "+str(Miner1.get_wallet_balance())+" coins.")
print("Liyuan comes in ..." )
password1 = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(16))
Liyuan=Wallet.Wallet(relayPorts[0], password1)
print('Liyuan has no money: ')
print("Liyuan has: "+str(Liyuan.determine_wallet_money())+" coins")
print('Miner1 transacts 5 coins to Liyuan...')
LiyuanAddress=Liyuan.get_address()
Miner1.spend_money_from_wallet(LiyuanAddress, 5)
print('The miner on the same relay as Liyuan mines a new block to carry the new transaction...')
Miner1.do_pow()
print('Now Miner1 has 15 coins:')
print("Miner1 has: "+str(Miner1.get_wallet_balance())+" coins.")
print('Now new transaction is valid Liyuan gets 5 coins')
print("Liyuan has: "+str(Liyuan.determine_wallet_money())+" coins")

print('Julian comes in ... ')
Julian=Wallet.Wallet(relayPorts[0], password2)
print('Liyuan transacts 3 coins to Julian...')
    def initialize(self):
        if not os.path.exists('ca_key.priv') and not os.path.exists('ca_key.pub'):
            print("Generating CA Key pair")
            prng = Random.new().read

            key = RSA.generate(1024, prng)
            # saving key
            fp = open('ca_key.priv', 'wb')
            fp.write(key.exportKey(format='PEM'))
            fp.close()

            fp = open('ca_key.pub', 'wb')
            fp.write(key.publickey().exportKey(format='PEM'))
            fp.close()

            self.ca_private_key = key
            self.ca_public_key = key.publickey()
        else:
            fp = open('ca_key.priv', 'rb')
            f_priv_key = fp.read(4096)
            fp.close()

            fp = open('ca_key.pub', 'rb')
            f_pub_key = fp.read(4096)
            fp.close()

            self.ca_private_key = RSA.importKey(f_priv_key)
            self.ca_public_key = RSA.importKey(f_pub_key)

        # computing wallet id
        # hashing the public key
        hasher = SHA256.new()
        hasher.update(self.ca_public_key.exportKey(format='DER'))
        self.ca_wallet_id = hasher.hexdigest()

        self.database.init_schema()

        # loading from db
        print("Loading wallets from Database")
        self.wallets = self.database.get_wallets(0, 1000)

        for w in self.wallets:
            if w.id == self.ca_wallet_id:
                self.authority_wallet = w

        if self.authority_wallet is None:
            print("Creating CA Wallet")
            keyString = ""
            for b in self.ca_public_key.exportKey(format='PEM'):
                keyString += chr(b)

            w = Wallet.Wallet(self.ca_name, keyString, self.ca_wallet_id)
            self.database.create_wallet(w)
            self.wallets.append(w)
            print("CA Wallet Id -> {0}".format(self.ca_wallet_id))
            # Wallet.save_wallets(self.wallets)
            self.authority_wallet = w

        print("Loading transactions...")

        i = 0
        txns = self.database.get_transactions(i, 100)

        while len(txns) == 100:
            for t in txns:
                self.transactions.append(t)

            i += 100
            txns = self.database.get_transactions(i, 100)

        for t in txns:
            self.transactions.append(t)

        # computing wallet balance
        self.calculate_wallets_balance()

        # saving wallet balance
        self.save_wallets()
示例#24
0
from Transaction import *
from Network import *
from Node import *
from Nodes import *

n0 = Node("0.0.0.0", 1337, str(uuid4()).replace('-', ''))
n1 = Node("0.0.0.0", 1338, str(uuid4()).replace('-', ''))

nodes = Nodes([n0, n1])

blockchain = BlockChain()
blockchain.chain.append(blockchain.genesis())
# add into db
# share to other nodes

walletAlice = Wallet(blockchain, "Alice")
walletBob = Wallet(blockchain, "Bob")


@app.route('/valid', methods=['GET'])
def valid():
    return jsonify(blockchain.is_valid())


@app.route('/minerate', methods=['POST'])
def minerate():
    request_values = request.get_json()
    amount = request_values["amount"]
    blockchain.set_mining_rate(amount)

    return "Changed mining rate"
示例#25
0
import FunctionNetwork as Net
import BlockChain
import Wallet
from pycoin import merkle
bc = BlockChain.BlockChain()
#bc.add_block(BlockChain.Block("0",1,0,0))
w = Wallet.Wallet()
w.create_identity("ale", "nardo", "95042429425", "24/4/1995", "m")
b = BlockChain.Block("0", merkle.merkle([w.my_identity.get_hash()]), "0", "0")
b.set_identities([w.my_identity])
bc.add_block(b)

bc.add_block(BlockChain.Block(bc.tip.get_hash(), 1, 0, 0))
a = Net.node(blockChain=bc, ip="127.0.0.1", port=Net.PORT, is_seed=1)
示例#26
0
     def HexCoin(self):
          
          #generate some walets
          Coinbase = wlt.Wallet()
          walletA = wlt.Wallet()
          walletB = wlt.Wallet()
          
          #send 100 coins to walleta
          genesisTransaction = txn.Transaction(Coinbase.PEMPublicKey.decode(), walletA.PEMPublicKey.decode(), 10000, 0, None)
          genesisTransaction.GenerateTransactionSignature(Coinbase.PrivateKey)
          
          #give the transaction a manual hash
          genesisTransaction.TransactionHash = "0"
          genesisTransaction.TransactionOutputs.append(outs.TransactionOutput(genesisTransaction.Recipient, genesisTransaction.Value, genesisTransaction.TransactionHash,0))
          self.UTXOs[genesisTransaction.TransactionOutputs[0].Id] = {"Transaction":genesisTransaction.TransactionOutputs[0]}
          
          print("create and mine genesis block")
          genesis = bl.Block("0")
          genesis.AddTransaction(genesisTransaction, self)
          self.AddBlock(genesis)
          
          #block 1
          block1 = bl.Block(genesis.BlockHash)
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("sending 40 from wallet a to b")
          block1.AddTransaction(walletA.SendFunds(walletB.PEMPublicKey.decode(), 40, self), self)
          self.AddBlock(block1)
          
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("balance of wallet b = " + str(walletB.getBalance(self)))

          #block 1
          block2 = bl.Block(block1.BlockHash)
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("spending more coins than in wallet")
          block2.AddTransaction(walletA.SendFunds(walletB.PEMPublicKey.decode(), 5, self), self)
          self.AddBlock(block2)
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("balance of wallet b = " + str(walletB.getBalance(self)))
          
          #block 1
          block3 = bl.Block(block2.BlockHash)
          print("balance of wallet a = " + str(walletB.getBalance(self)))
          print("sending 40 from wallet a to b")
          block3.AddTransaction(walletB.SendFunds(walletA.PEMPublicKey.decode(), 23.5, self), self)
          self.AddBlock(block3)
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("balance of wallet b = " + str(walletB.getBalance(self)))
          
          #clears spent Utxos and keeps the chain clean
          #self.CleanUpUtxo()
          self.CheckChainValid(genesisTransaction)
          
          #block 4 tests creating a new coin
          block4 = bl.Block(block3.BlockHash)
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("Creating a new coin")
          CoinTxn = walletA.CreateNewCoin(self, "HephCoin", "Heph", 100000)
          block4.AddTransaction(CoinTxn, self)
          self.AddBlock(block4)
          
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("coin balance of wallet a = " + str(walletA.GetTokenBalance(self, self.AlternativeCoins[0])))
          
          #block 5 sends tokens from one wallet to another
          block5 = bl.Block(block4.BlockHash)
          print("coin balance of wallet a = " + str(walletA.GetTokenBalance(self, self.AlternativeCoins[0])))
          print("coin balance of wallet b = " + str(walletB.GetTokenBalance(self, self.AlternativeCoins[0])))
          print("sending 500.5050505 Tokens from wallet a to b")
          TokenTransaction = walletA.SendToken(walletB.PEMPublicKey.decode(), 500.5050505, self.AlternativeCoins[0], self)
          block5.AddTransaction(TokenTransaction, self)
          self.AddBlock(block5)
          
          print("coin balance of wallet a = " + str(walletA.GetTokenBalance(self, self.AlternativeCoins[0])))
          print("coin balance of wallet b = " + str(walletB.GetTokenBalance(self, self.AlternativeCoins[0])))
          
          print("coin balance of wallet b = " + str(walletB.GetTokenBalance(self, self.AlternativeCoins[0])))
          print("Testing burning token by using the burn wallet function - This permenantly destroys the UTXOs")
          block6 = bl.Block(block5.BlockHash)
          BurnTransaction = walletB.BurnToken(0.5050505, self.AlternativeCoins[0], self)
          block6.AddTransaction(BurnTransaction, self)
          self.AddBlock(block6)
          
          print("spendable balance of wallet b = " + str(walletB.GetSpentableTokenBalance(self, self.AlternativeCoins[0])))
          print("freezing some 60 tokens from wallet b")
          block7 = bl.Block(block6.BlockHash)
          FreezeTransaction = walletB.FreezeUnfreezeTokens(60,self.AlternativeCoins[0], True, self)
          block7.AddTransaction(FreezeTransaction, self)
          self.AddBlock(block7)
          print("spentable token balance of wallet b = " + str(walletB.GetSpentableTokenBalance(self, self.AlternativeCoins[0])))
          print("coin balance of wallet b = " + str(walletB.GetTokenBalance(self, self.AlternativeCoins[0])))
          
          print("unfreezing 30 tokens")
          block8 = bl.Block(block7.BlockHash)
          FreezeTransaction = walletB.FreezeUnfreezeTokens(22,self.AlternativeCoins[0], False, self)
          block8.AddTransaction(FreezeTransaction, self)
          self.AddBlock(block8)
          print("spentable token balance of wallet b = " + str(walletB.GetSpentableTokenBalance(self, self.AlternativeCoins[0])))
          print("coin balance of wallet b = " + str(walletB.GetTokenBalance(self, self.AlternativeCoins[0])))
          
          print("Testing Limit Order")
          block9 = bl.Block(block8.BlockHash)
          order = walletB.CreateOrder(self.AlternativeCoins[0], 1, 10, True, self)
          block9.AddTransaction(order, self)
          self.AddBlock(block9)
          print("Buy Order Added")
          
          print("Testing Limit Order when matching order on the market")
          print("Values before Trade")
          
          print("coin balance of wallet a = " + str(walletA.GetTokenBalance(self, self.AlternativeCoins[0])))
          print("coin balance of wallet b = " + str(walletB.GetTokenBalance(self, self.AlternativeCoins[0])))
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("balance of wallet b = " + str(walletB.getBalance(self)))
          
          block10 = bl.Block(block9.BlockHash)
          order = walletA.CreateOrder(self.AlternativeCoins[0], 1, 10, False, self)
          block10.AddTransaction(order, self)
          self.AddBlock(block10)
          self.CleanOrders()
          print("Balance After Trade")
          print("coin balance of wallet a = " + str(walletA.GetTokenBalance(self, self.AlternativeCoins[0])))
          print("coin balance of wallet b = " + str(walletB.GetTokenBalance(self, self.AlternativeCoins[0])))
          print("balance of wallet a = " + str(walletA.getBalance(self)))
          print("balance of wallet b = " + str(walletB.getBalance(self)))
          
          return self.UTXOs, self.OpenOrders
示例#27
0
 def createWalletFromHash(self, hashH):
     """ Create a Wallet from the hash """
     wallet = Wallet.Wallet(secrets.token_hex(32), hashH)
     return self.addWallet(wallet)
示例#28
0
 def run(self):
     kirdow = Wallet()
     bob = Wallet()
     alice = Wallet()
     kirdow.sendMoney(50, bob.publicKey)
     bob.sendMoney(23, alice.publicKey)
     alice.sendMoney(5, bob.publicKey)
示例#29
0
 def createWalletFromPassword(self, password):
     """ Create a wallet from a password """
     hexed = hashlib.sha256(password.encode('utf-8')).hexdigest()
     wallet = Wallet.Wallet(secrets.token_hex(32), hexed)
     return self.addWallet(wallet)
示例#30
0
# Starting the relays
for i in range(0, len(relayPorts)):
    port = relayPorts[i]
    try:
        threading.Thread(target=Relay.Relay, args=(
            masterPort,
            port,
        )).start()
    except:
        print("Error: unable to start thread " + str(i))

# Starting two wallets

password1 = ''.join(
    random.choice(string.ascii_letters + string.digits) for _ in range(16))
Wallet1 = Wallet.Wallet(relayPorts[0], password1)

#Starting miner
password2 = ''.join(
    random.choice(string.ascii_letters + string.digits) for _ in range(16))
Miner1 = Miner.Miner(1, relayPorts[0], password2)

print("---------- Difficulty Adjustment Test ---------- ")

print("Starting difficulty: 2")
print("When mining speed / transacting speed > 16: ")
print("Let us take a break for 5 seconds ...")
sleep(5)

# difficulty is modified by master in a period of 16 new blocks
for idx in range(16):
示例#31
0
        net = pickle.load(file_net)
        net.BlockChain = bc
        net.init_net([])
        file_net.close()
    else:
        net = FunctionNetwork.node(bc,
                                   ip=ip,
                                   port=port,
                                   is_seed=1,
                                   full_node=1)
auth = Authorization.Authorization(bc, trie)
if os.path.exists("./Wallet.dat") == False:
    print("\ndesea crear una identidad y registrarla? s/n")
    s = input()
    if s == "s":
        wallet = Wallet.Wallet()
        Wallet.create_identity_from_interface(wallet)
        net.send_id(wallet.my_identity)

index = -2
if (net.ip, net.port) in trusted_parties:
    index = trusted_parties.index((net.ip, net.port))


def verification_blocks(net, auth, bc):
    i = 0
    print("verifiying block")
    while 1:
        sleep(1)
        if kill:
            exit(0)
示例#32
0
class Player(object):

    #constructor
    def __init__(self, name, initial_cash, initial_chips):
        self.__name = name #initialize the name
        self.__wallet = Wallet(initial_cash) #initialize the Wallet
        self.__chips = ChipBag(initial_chips) #initialize the ChipBag
        self.__saturation = 10 #just ate
        self.__hunger = 0 #not hungry
        self.__fatigue = 0 #not tired
        self.__rep = 0 #no reputation

    #representation and string methods
    def __repr__(self):
        return self.__name #use the name field

    def __str__(self):
        return self.__repr__() #use the __repr__ method

    #getters
    def get_wallet(self):
        return self.__wallet #return the wallet field

    def get_chips(self):
        return self.__chips #return the chips field

    def get_rep(self):
        return self.__rep #return the rep field

    def get_name(self):
        return self.__name #return the name


    #properties
    wallet = property(get_wallet) #create a getter property for the wallet
    chips = property(get_chips) #create a getter property for chips
    rep = property(get_rep) #create a getter property for rep
    name = property(get_name) #create a getter property for name

    #methods

    #print_stats method - prints the stats of the player
    def print_stats(self):
        print(self.__name + '\'s current stats:')
        print('Hunger: ' + str(self.__hunger))
        print('Fatigue: ' + str(self.__fatigue))
        print('Reputation: ' + str(self.__rep))
        balance = self.__wallet.value + self.__chips.value + DepositBox().balance
        print('Wallet balance: ' + str(self.__wallet.value))
        print('Chip balance: ' + str(self.__chips.value))
        print('Deposit box balance: ' + str(DepositBox().balance))
        print('Total balance: ' + str(balance))
        percent_wallet = float(self.__wallet.value / balance)
        percent_chips = float(self.__chips.value / balance)
        percent_box = float(DepositBox().balance / balance)
        print('Percent in wallet: ' + str(percent_wallet))
        print('Percent in chips: ' + str(percent_chips))
        print('Percent in deposit box: ' + str(percent_box))


    #feed method - decreases the hunger of the player (cannot go past 0)
    def feed(self, food):
        self.__hunger -= food.nutrition #use the nutrition field to determine how much to feed
        if self.__hunger < 0: #check for invalid values
            self.__hunger = 0 #fix them
        self.__saturation += food.saturation #use the saturation field to determine the new saturation
        food.eat(self) #call food.eat to handle the food code


    #remove_fatigue method - removes a set number of fatigue points from the player
    def remove_fatigue(self, points):
        self.__fatigue -= points #remove the points

    #sleep method - completely removes fatigue from the player
    def sleep(self):
        self.__fatigue = 0 #refresh the player

    #gain_rep method - increases reputation
    def gain_rep(self, amt):
        self.__rep += amt #increase reputation
        if self.__rep > 100: #this if statement checks for invalid values
            self.__rep = 100
        elif self.__rep < -100:
            self.rep = -100


    #lose_rep method - decreases reputation
    def lose_rep(self, amt):
        self.gain__rep(-amt) #use the gain__rep method negatively


    #pass_time method - run by the game to pass the time
    def pass_time(self):
        if randint(0,1) == 1 and self.__saturation > 0:
            self.__saturation -= 1 #make the player hungry 50% of the time
        if randint(0,1) == 1 and self.__saturation == 0:
            self.__hunger += 1 #add hunger 50% of the time if saturation is 0
        if self.__hunger >= 100: #if the player is too hungry to continue
            print('You have fainted of hunger.') #print the 'death message'
            print('While asleep, you have been robbed of all your money.')
            current__bal = self.__wallet.value #get the value of the wallet
            self.__wallet.pay(current__bal) #wipe the wallet
        if self.__wallet.value <= 0:
            if DepositBox().balance <= 0 and self.__chips.value <= 0: #if the player has no more money
                print('You have no more money.')
                print('GAME OVER')
                sys.exit(0) #quit the script
        if self.__hunger >= 50: #if a warning should be shown
            print('You are very hungry.') #print the warning
        if randint(0,1) == 0:
            self.__fatigue +=  1 #add fatigue 50% of the time
        if self.__fatigue >= 100: #if tthe player is too tired to continue
            print('You have fainted from fatigue.') #print the 'death message'
            print('While asleep, all your chips were stolen.')
            current__bal = self.__chips.value #get the value of the chips
            self.__chips.pay(current__bal) #wipe the chip bag
        if self.__chips.value <= 0:
            if DepositBox().balance <= 0 and self.__wallet.value <= 0: #if the player has no more money
                print('You have no more money.')
                print('GAME OVER')
                sys.exit(0) #quit the script
        if self.__fatigue >= 50: #if a warning should be shown
            print('You are very tired.') #print the warning
示例#33
0
 def test_new_wallet(self):
     wallet = Wallet.Wallet('geheim')
     result = b'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlbor8kAc62jFaoivZGdArI9tY\nvKz1551t7i3j0s1j0KqwmLdIVI5fp5LYFcJ7iL9P1jsaotAw9QqdJuMu4x+ttOAT\nIqQ25TdyXA4FtRPLZ2zBbTmdklSlHNkekSpmE7nTOSl95S2FbLrDNuV3t1mPjfZB\nxq0HF0RamgLmE77gCwIDAQAB\n-----END PUBLIC KEY-----'
     self.assertEqual(result, wallet.get_public_address())