Ejemplo n.º 1
0
 def __init__(self, alias='guest', server='127.0.0.1', port=5000, **kwargs):
     super(ClientApp, self).__init__(**kwargs)
     self.alias = alias
     self.server = server
     self.port = int(port)
     self.blockchain = Blockchain(alias)
     self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.textbox = None
     self.label = None
Ejemplo n.º 2
0
    def test_fraudulent_tx_source_coinbase(self):
        blockchain = Blockchain()

        victim = generate_key()
        miner = Miner(blockchain)
        miner.reward_addr = victim.publickey()
        emptyblock = miner._mine()
        self.assertEqual(len(emptyblock.transactions), 1)
        self._test_fraudulent_tx(victim, blockchain)
Ejemplo n.º 3
0
    def __init__(self, user_ID, password):
        """Create a new wallet

        user_ID  : The ID of the user to select it's own address on the DB
        password : The password is used to generate a AES_Key to ecrypt / decrypt the private key on DB
                   Here, we used it to load all the address or write the new address
        """
        self.blockChain = Blockchain('client')
        self.relay = RelayClient()
        self.updater = Updater(self.blockChain, self.relay)
        self.updater.update()
        self.user_ID = user_ID
        self.addrList = loadAddressList(self.user_ID)  # list of address
        self.last = len(self.addrList) - 1  #index of the actual address
        if self.addrList == []:  #New Wallet : Create the first Address
            self.addr = Address()
            self.addr.encryptPrivateKey(password)
            add_address(self.user_ID, self.addr, 0)
            self.addrList.append(self.addr)
        else:
            self.addr = self.addrList[len(self.addrList) - 1]
        self.count = self.blockChain.get_amount_of_address(self.addr)
Ejemplo n.º 4
0
    def test_fraudulent_tx_source_other_user(self):
        blockchain = Blockchain()

        victim = generate_key()
        miner_key = generate_key()

        miner = Miner(blockchain)
        miner.reward_addr = miner_key.publickey()
        emptyblock = miner._mine()

        transfer = Wallet(miner_key, blockchain)
        transfer.send(10, victim.publickey())

        self.assertEqual(len(emptyblock.transactions), 1)
        self._test_fraudulent_tx(victim, blockchain)
Ejemplo n.º 5
0
    def test_chained_tx(self):
        blockchain = Blockchain()

        member1 = generate_key()
        member2 = generate_key()
        member3 = generate_key()

        miner = Miner(blockchain)
        miner.reward_addr = member1.publickey()
        _ = miner._mine()

        wallet1 = Wallet(member1, blockchain)
        wallet1.send(10, member2.publickey())

        wallet2 = Wallet(member2, blockchain)
        wallet2.send(10, member3.publickey())

        wallet3 = Wallet(member3, blockchain)

        self.assertEqual(wallet1.balance(), 0)
        self.assertEqual(wallet2.balance(), 0)
        self.assertEqual(wallet3.balance(), 10)
Ejemplo n.º 6
0
    def test_pending_transactions(self):
        receiver = generate_key()

        tx = Transaction(None, txtype=TxType.COINBASE)
        tx.add_out(10, receiver.publickey())

        blockchain = Blockchain()
        blockchain.add(tx)

        pending_tx = blockchain.get_pending_transactions()

        self.assertEqual(len(filter(lambda x: tx.hash, pending_tx)), 1)

        miner = Miner(blockchain)
        miner.reward_addr = receiver.publickey()
        newb = miner._mine()

        pending_tx = blockchain.get_pending_transactions()

        self.assertEqual(len(filter(lambda x: tx.hash, pending_tx)), 0)
        self.assertEqual(len(filter(lambda x: tx.hash, newb.transactions)), 2)
Ejemplo n.º 7
0
Archivo: bis.py Proyecto: Artanidos/THX
 def checkFirst(self):
     dbName = "bis.db"
     if not os.path.exists(dbName):
         self.block_chain = Blockchain(dbName)
Ejemplo n.º 8
0
    t = Transaction(f, receivers)
    if relay.submit_transaction(t):
        print('transaction sent to the network')
    else:
        print('error sending transaction')


def usage():
    exit('usage: python3 '+av[0]+' list|new|transfer')

if __name__ == '__main__':
    # init database
    db.createDB()
    
    # always update blockchain
    bc = Blockchain('client')
    relay = RelayClient()
    u = Updater(bc, relay)
    print('updating blockchain ...')
    u.update()
    
    # parse arguments
    av = sys.argv
    ac = len(av)
    if ac == 1:
        usage()
    
    if av[1] == 'list':
        display_addresses(bc)
    elif av[1] == 'new':
        create_address()
Ejemplo n.º 9
0
class ClientApp(App):
    def __init__(self, alias='guest', server='127.0.0.1', port=5000, **kwargs):
        super(ClientApp, self).__init__(**kwargs)
        self.alias = alias
        self.server = server
        self.port = int(port)
        self.blockchain = Blockchain(alias)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.textbox = None
        self.label = None

    def build(self):
        root = self.setup_gui()
        self.connect_to_server()
        return root

    def setup_gui(self):
        Config.set('graphics', 'width', '200')
        Config.set('graphics', 'height', '200')
        Window.size = (500, 300)
        layout = BoxLayout(orientation='vertical')
        layout.bind(minimum_height=layout.setter('height'))
        self.textbox = TextInput(size_hint_y=.1, multiline=False)
        self.textbox.bind(on_text_validate=self.send_message)
        self.label = ScrollableLabel(text='connecting...')
        layout.add_widget(self.label)
        layout.add_widget(self.textbox)
        return layout

    def connect_to_server(self):
        try:
            self.s.connect((self.server, self.port))
            self.label.text = "Connected to %s:%s\n" % (self.server, self.port)
            listener = Thread(target=self.receive_messages).start()
        except Exception as e:
            self.label.text = "Failed to connect to %s:%s\n%s\n" % (
                self.server, self.port, e)

    def send_message(self, *args):
        msg = self.textbox.text
        if msg:
            if "?chain" in msg:
                self.label.text += "Dumping chain to ./blockchain.json\n"
                with open('blockchain.json', 'wt') as out:
                    pprint(self.blockchain.chain, stream=out)
                self.textbox.text = ""
            else:
                block = self.blockchain.send_block(msg)
                payload = base64.b64encode(block.encode('utf-8'))
                try:
                    self.s.send(payload)
                    self.label.text += "<{}> {}\n".format(self.alias, msg)
                except BrokenPipeError:
                    self.label.text += "You aren't connected!\n"
                self.textbox.text = ""

    def receive_messages(self):
        while True:
            socket_list = [sys.stdin, self.s]
            read_sockets, write_sockets, error_sockets = select.select(
                socket_list, [], [])
            for sock in read_sockets:
                if sock == self.s:
                    data = sock.recv(4096).decode('utf-8')
                    if not data:
                        sys.exit()
                    elif 'entered room' in data:
                        self.label.text += "{}".format(data)
                    else:
                        split = data.split('>')
                        ldata = "%s>" % split[0]
                        rdata = ''.join(split[1:]).encode('utf-8')
                        decoded = base64.b64decode(rdata)
                        block = self.blockchain.recv_block(
                            decoded.decode('utf-8'))
                        txn = block['contents']['txns']
                        lident = list(txn.keys())[0]
                        rident = list(txn.values())[0]
                        display = "<%s> %s" % (lident, rident)
                        self.label.text += "{}".format(display)
                        self.label.scroll_to(display)
Ejemplo n.º 10
0
class Wallet(object):
    """Wallet is the principal user
    Wallet have money and can create some Transaction to send money to an another Wallet
    """
    def __init__(self, user_ID, password):
        """Create a new wallet

        user_ID  : The ID of the user to select it's own address on the DB
        password : The password is used to generate a AES_Key to ecrypt / decrypt the private key on DB
                   Here, we used it to load all the address or write the new address
        """
        self.blockChain = Blockchain('client')
        self.relay = RelayClient()
        self.updater = Updater(self.blockChain, self.relay)
        self.updater.update()
        self.user_ID = user_ID
        self.addrList = loadAddressList(self.user_ID)  # list of address
        self.last = len(self.addrList) - 1  #index of the actual address
        if self.addrList == []:  #New Wallet : Create the first Address
            self.addr = Address()
            self.addr.encryptPrivateKey(password)
            add_address(self.user_ID, self.addr, 0)
            self.addrList.append(self.addr)
        else:
            self.addr = self.addrList[len(self.addrList) - 1]
        self.count = self.blockChain.get_amount_of_address(self.addr)

    def backAddress(self):
        """Return to the previous address
        """
        if len(self.addrList) >= 2:
            self.addr = self.addrList[len(addrList) - 2]
            self.addrList.pop(self.addrList[len(self.addrList) - 1])

    def checkUpdate(self):
        """Update the amount and the blockChain
        """
        self.updater.update()
        self.count = self.blockChain.get_amount_of_address(self.addr)

    def createTransaction(self, password, destList):
        """Create a new transaction and send it to the RelayNode
           destList is a list of tuples
           Each tuples is like : (str_address, value)
           The last transaction is the rest of the wallet send to the new user address
        """
        self.checkUpdate()
        newAddr = Address()
        newAddr.encryptPrivateKey(password)
        total = sum([i[1] for i in destList])
        if total <= self.count:
            destList.append((str(newAddr), (self.count - total)))
            transac = Transaction(self.addr.public(), destList)
            self.addr.decryptPrivateKey(password)
            transac.sign(self.addr)
            debug('valid: ' + ('True' if transac.is_signed() else 'False'))
            self.addr.encryptPrivateKey(password)
            if not self.relay.submit_transaction(transac):
                return False
            self.addrList.append(newAddr)
            self.addr = newAddr
            add_address(self.user_ID, self.addr, len(self.addrList) - 1)
            return True
        else:
            return False
Ejemplo n.º 11
0
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  THX is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with THX.  If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################

from lib.thx import Thx
from lib.blockchain import Blockchain
from lib.bis import Bis
from datetime import datetime
import uuid

app_uuid = uuid.uuid1()

t = Thx(mintingDate=datetime(2020,5,9), amount=10)
print(t.value())

t = Thx(mintingDate=datetime(2014,1,1), amount=1000)
print(t.value())

b = Blockchain("test.db")
b.flush()

bis = Bis()
Ejemplo n.º 12
0
from lib.blockchain import Blockchain
from lib.network import Network
from lib.http_server import MasterServer

if __name__ == '__main__':
    b = Blockchain('master')
    master = Network.get_master()
    server = MasterServer(master, b)
    server.serve_forever()
Ejemplo n.º 13
0
    def test_value_transfer(self):
        """
        Test successful transaction
        """
        SENDER_ORIG_VALUE = MINING_REWARD  # Mining reward
        SEND_AMOUNT = 5

        blockchain = Blockchain()

        sender = generate_key()
        receiver = generate_key()
        miner_key = generate_key()

        # This is an empty blockchain so create value out of thin air.
        miner = Miner(blockchain)
        miner.reward_addr = sender.publickey()
        emptyblock = miner._mine()

        self.assertEqual(len(emptyblock.transactions), 1)

        # First test with unconfirmed transactions
        for i in range(1, 3):
            wallet = Wallet(sender, blockchain)
            wallet.send(SEND_AMOUNT, receiver.publickey())

            # Scan the blockchain for the transaction that just happened.
            receiver_owns = blockchain.scan_unspent_transactions(
                receiver.publickey())
            value_received = sum(
                map(lambda x: x.get('value', 0), receiver_owns))
            self.assertEqual(value_received, SEND_AMOUNT * i)

            sender_owns = blockchain.scan_unspent_transactions(
                sender.publickey())
            value_owned_by_sender = sum(
                map(lambda x: x.get('value', 0), sender_owns))
            self.assertEqual(value_owned_by_sender,
                             SENDER_ORIG_VALUE - SEND_AMOUNT * i)

        # Mine the transactions
        miner = Miner(blockchain)
        miner.reward_addr = miner_key.publickey()
        newb = miner._mine()

        # Test with confirmed transactions
        receiver_owns = blockchain.scan_unspent_transactions(
            receiver.publickey())
        value_received = sum(map(lambda x: x.get('value', 0), receiver_owns))
        self.assertEqual(value_received, SEND_AMOUNT * 2)

        sender_owns = blockchain.scan_unspent_transactions(sender.publickey())
        value_owned_by_sender = sum(
            map(lambda x: x.get('value', 0), sender_owns))
        self.assertEqual(value_owned_by_sender,
                         SENDER_ORIG_VALUE - SEND_AMOUNT * 2)

        # Check whether miner received the award
        miner_owns = blockchain.scan_unspent_transactions(
            miner_key.publickey())
        value_owned_by_miner = sum(map(lambda x: x.get('value', 0),
                                       miner_owns))
        self.assertEqual(value_owned_by_miner, MINING_REWARD)

        self.assertEqual(len(newb.transactions), 3)
Ejemplo n.º 14
0
    # pdb.set_trace()
    i = len(interlinks[lastblockid]) - 1
    proofs = {}
    # print 'Constructing proof at level %i' % i
    proofs[i] = construct_inner_chain(i, None, lastblockid, interlinks)
    while i > 0:
        boundary = max(m, len(proofs[i]))
        i -= 1
        # print 'Constructing proof at level %i' % i
        proofs[i] = construct_inner_chain(i, boundary, lastblockid, interlinks)
    blocks = []
    for i in proofs:
        blocks.extend(proofs[i])
    return blocks

blockchain = Blockchain(config, network)
blockchain.init()
block_height = 10000
block = blockchain.read_header(block_height)

max_height = blockchain.height()
bar = progressbar.ProgressBar(max_value = max_height, redirect_stdout=True)

MIN_M = 1
MAX_M = 10
MIN_K = 1
MAX_K = 10

levels = {}
samples = []
interlink = {}
Ejemplo n.º 15
0
import json
from lib.blockchain import Blockchain
from lib.wallet import Wallet, InsufficientFundsException
from lib.utils import generate_key
from lib.rsa import RSAKey, RSAPublicKey, RSAPrivateKey
from miner import Miner

blockchain = Blockchain()
miner = Miner(blockchain)


def status(query):
    return "OK"


def mine(data):
    l = json.loads(data)

    if miner.mine(l.get('reward_address')):
        return "Started mining with reward address:" + l.get('reward_address')
    else:
        return "Mining already ongoing"


def create_wallet(data):
    key = generate_key()

    return json.dumps({
        "public_key": str(key.publickey()),
        "private_key": str(key.privatekey())
    })
Ejemplo n.º 16
0
        while (1):
            if self.flag == 0:  # check relay for new block
                self.flag = Miner.FLAG
                if self.updater.update():
                    print('Downloaded new block')
                    print('Mining for address ' + str(self.address) + ' ',
                          end='')
                    self.create_block()
                print('.', end='', flush=True)  # show state to the user
            self.flag = self.flag - 1
            self.block.set_proof(strategy(self.index))
            self.index = self.index + 1
            if (self.block.good_difficulty()):
                print('\nMined block ' + self.block.get_hash())
                self.relay.submit_block(self.block)
                self.flag = 0  #Need to take new transactions


def randompow(previousPow=0):
    return random.randint(0, 2**256)


if __name__ == '__main__':
    argc = len(sys.argv)
    if not argc == 2:
        exit('usage: python3 ' + sys.argv[0] + ' YOUR_ADDRESS')

    b = Blockchain('miner')
    miner = Miner(b, sys.argv[1])
    miner.run(randompow)
Ejemplo n.º 17
0
import sys

# local imports
from lib.blockchain import Blockchain
from lib.network import Network
from lib.http_server import RelayServer

if __name__ == '__main__':
    argc = len(sys.argv)
    if not argc == 2:
        exit('usage: python3 ' + sys.argv[0] + ' RELAY_NUMBER')
    relays = Network.get_relays()
    n = len(relays)
    i = int(sys.argv[1]) % n
    print('Starting relay ' + str(i))
    b = Blockchain('relay' + str(i))
    master = Network.get_master()
    server = RelayServer(relays[i], b)
    server.serve_forever()
    # TODO update blockchain in background or receive pushes from server