Example #1
0
def home():
    session.setdefault('id', str(uuid.uuid4()))

    if request.method == 'POST':
        bulletin_secret = request.form.get('bulletin_secret', '')
        if not bulletin_secret:
            return redirect('/?error')
        # generate a transaction which contains a signin message containing the current sessions identifier
        txn = TransactionFactory(bulletin_secret=bulletin_secret,
                                 public_key=Config.public_key,
                                 private_key=Config.private_key,
                                 signin=session.get('id'),
                                 fee=0.01).transaction

        # send the transaction to our own serve instance, which saves it to miner_transactions
        # the miner looks in miner_transactions to include in a block when it finds a new block
        for peer in Peers.peers:
            print peer.host, peer.port
            requests.post("http://{host}:{port}/newtransaction".format(
                host=peer.host, port=peer.port),
                          txn.to_json(),
                          headers={"Content-Type": "application/json"})
        return redirect('/?bulletin_secret=%s' %
                        urllib.quote_plus(bulletin_secret))
    elif request.method == 'GET':
        bulletin_secret = request.args.get('bulletin_secret', '')
        rid = TU.generate_rid(bulletin_secret)
        txns = BU.get_transactions_by_rid(rid, rid=True)

        txns2 = BU.get_transactions_by_rid(rid, rid=True, raw=True)
        half1 = False
        half2 = False
        for txn in txns:
            if txn['public_key'] == Config.public_key:
                half1 = True
        for txn in txns2:
            if txn['public_key'] != Config.public_key:
                half2 = True
        registered = half1 and half2
        sent, received = BU.verify_message(rid, session['id'])
        session['loggedin'] = received
        return render_template('index.html',
                               session_id=str(session.get('id')),
                               registered=str(registered),
                               sent=str(sent),
                               received=str(received),
                               loggedin=str(session['loggedin']),
                               bulletin_secret=str(bulletin_secret),
                               rid=str(rid))
    else:
        return redirect('/')
Example #2
0
def send(to, value):
    Peers.init()
    Mongo.init()
    used_inputs = []
    new_inputs = []

    try:
        transaction = TransactionFactory(fee=0.01,
                                         public_key=Config.public_key,
                                         private_key=Config.private_key,
                                         outputs=[Output(to=to, value=value)])
    except NotEnoughMoneyException as e:
        print "not enough money yet"
        return
    except:
        raise
    try:
        transaction.transaction.verify()
    except:
        print 'transaction failed'
    TU.save(transaction.transaction)
    print 'Transaction generated successfully. Sending:', value, 'To:', to
    for peer in Peers.peers:
        try:
            socketIO = SocketIO(peer.host,
                                peer.port,
                                wait_for_connection=False)
            chat_namespace = socketIO.define(ChatNamespace, '/chat')
            chat_namespace.emit('newtransaction',
                                transaction.transaction.to_dict())
            socketIO.disconnect()
            print 'Sent to:', peer.host, peer.port
        except Exception as e:
            print e
Example #3
0
    def dispatch_request(self):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        unspent = BU().get_wallet_unspent_transactions(request.json.get('address'))
        unspent_inputs = dict([(x['id'], x) for x in unspent])
        input_sum = 0
        for x in request.json.get('inputs'):
            found = False
            if x['id'] in unspent_inputs:
                for tx in unspent_inputs[x['id']].get('outputs'):
                    input_sum += float(tx['value'])
                found = True
                break
            if not found:
                if mongo.db.blocks.find_one({'transactions.id': x['id']}, {'_id': 0}):
                    return json.dumps({'status': 'error', 'msg': 'output already spent'}), 400
                else:
                    return json.dumps({'status': 'error', 'msg': 'transaction id not in blockchain'}), 400
        output_sum = 0
        for x in request.json.get('outputs'):
            output_sum += float(x['value'])

        if (output_sum + float(request.json.get('fee'))) > input_sum:
            return json.dumps({'status': 'error', 'msg': 'not enough inputs to pay for transaction outputs + fee'})
        try:
            txn = TransactionFactory(
                block_height=BU().get_latest_block(config, mongo)['index'],
                public_key=request.json.get('public_key'),
                fee=float(request.json.get('fee')),
                inputs=request.json.get('inputs'),
                outputs=request.json.get('outputs')
            )
        except NotEnoughMoneyException as e:
            return json.dumps({'status': 'error', 'msg': 'not enough coins from referenced inputs to pay for transaction outputs + fee'}), 400
        return '{"header": "%s", "hash": "%s"}' % (txn.header, txn.hash)
Example #4
0
def faucet():
    Mongo.init()
    used_inputs = []
    new_inputs = []
    for x in Mongo.site_db.faucet.find({'active': True}):
        balance = BU.get_wallet_balance(x['address'])
        if balance >= 25:
            Mongo.site_db.faucet.update({'_id': x['_id']}, {
                'active': False,
                'address': x['address']
            })

            continue
        last_id_in_blockchain = x.get('last_id')
        if last_id_in_blockchain and not Mongo.db.blocks.find({
                'transactions.id':
                last_id_in_blockchain
        }).count():

            continue

        try:
            transaction = TransactionFactory(
                fee=0.01,
                public_key=Config.public_key,
                private_key=Config.private_key,
                outputs=[Output(to=x['address'], value=5)])
        except NotEnoughMoneyException as e:
            print "not enough money yet"
            return
        except Exception as e:
            print x
        try:
            transaction.transaction.verify()
        except:
            Mongo.site_db.failed_faucet_transactions.insert(
                transaction.transaction.to_dict())
            print 'faucet transaction failed'
        TU.save(transaction.transaction)
        x['last_id'] = transaction.transaction.transaction_signature
        Mongo.site_db.faucet.update({'_id': x['_id']}, x)
        print 'saved. sending...', x['address']
        for peer in Peers.peers:
            try:
                socketIO = SocketIO(peer.host,
                                    peer.port,
                                    wait_for_connection=False)
                chat_namespace = socketIO.define(ChatNamespace, '/chat')
                chat_namespace.emit('newtransaction',
                                    transaction.transaction.to_dict())
                socketIO.disconnect()
            except Exception as e:
                print e
Example #5
0
    def dispatch_request(self):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        if request.method == 'GET':
            bulletin_secret = request.args.get('bulletin_secret', '')
            username = request.args.get('username', '')
            to = request.args.get('to', '')
        else:
            bulletin_secret = request.json.get('bulletin_secret', '')
            username = request.json.get('username', '')
            to = request.json.get('to', '')

        if not bulletin_secret:
            return 'error: "bulletin_secret" missing', 400

        if not username:
            return 'error: "username" missing', 400

        if not to:
            return 'error: "to" missing', 400
        rid = TU.generate_rid(config, bulletin_secret)
        dup = mongo.db.blocks.find({'transactions.rid': rid})
        if dup.count():
            for txn in dup:
                if txn['public_key'] == config.public_key:
                    return json.dumps({
                        "success": False,
                        "status": "Already added"
                    })

        miner_transactions = mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        checked_out_txn_ids = mongo.db.checked_out_txn_ids.find()
        for mtxn in checked_out_txn_ids:
            mtxn_ids.append(mtxn['id'])

        a = os.urandom(32)
        dh_public_key = scalarmult_base(a).encode('hex')
        dh_private_key = a.encode('hex')

        transaction = TransactionFactory(config=config,
                                         mongo=mongo,
                                         block_height=BU.get_latest_block(
                                             config, mongo)['index'],
                                         bulletin_secret=bulletin_secret,
                                         username=username,
                                         fee=0.00,
                                         public_key=config.public_key,
                                         dh_public_key=dh_public_key,
                                         private_key=config.private_key,
                                         dh_private_key=dh_private_key,
                                         outputs=[{
                                             'to': to,
                                             'value': 0
                                         }])

        TU.save(config, mongo, transaction.transaction)

        mongo.db.miner_transactions.insert(transaction.transaction.to_dict())
        job = Process(target=TxnBroadcaster.txn_broadcast_job,
                      args=(transaction.transaction, ))
        job.start()

        my_bulletin_secret = config.bulletin_secret
        bulletin_secrets = sorted(
            [str(my_bulletin_secret),
             str(bulletin_secret)], key=str.lower)
        rid = hashlib.sha256(
            str(bulletin_secrets[0]) +
            str(bulletin_secrets[1])).digest().encode('hex')
        mongo.site_db.friends.insert({
            'rid': rid,
            'relationship': {
                'bulletin_secret': bulletin_secret
            }
        })
        return json.dumps({"success": True})
Example #6
0
    def dispatch_request(self):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        if request.method == 'GET':
            bulletin_secret = request.args.get('bulletin_secret', '')
            username = request.args.get('username', '')
            to = request.args.get('to', '')
        else:
            bulletin_secret = request.json.get('bulletin_secret', '')
            username = request.json.get('username', '')
            to = request.json.get('to', '')

        if not bulletin_secret:
            return 'error: "bulletin_secret" missing', 400

        if not username:
            return 'error: "username" missing', 400

        if not to:
            return 'error: "to" missing', 400
        rid = TU.generate_rid(config, bulletin_secret)
        dup = mongo.db.blocks.find({'transactions.rid': rid})
        if dup.count():
            found_a = False
            found_b = False
            for txn in dup:
                if txn['public_key'] == config.public_key:
                    found_a = True
                if txn['public_key'] != config.public_key:
                    found_b = True
            if found_a and found_b:
                return json.dumps({"success": False, "status": "Already added"})

        miner_transactions = mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        checked_out_txn_ids = mongo.db.checked_out_txn_ids.find()
        for mtxn in checked_out_txn_ids:
            mtxn_ids.append(mtxn['id'])

        a = os.urandom(32).decode('latin1')
        dh_public_key = scalarmult_base(a).encode('latin1').hex()
        dh_private_key = a.encode('latin1').hex()

        transaction = TransactionFactory(
            block_height=BU().get_latest_block()['index'],
            bulletin_secret=bulletin_secret,
            username=username,
            fee=0.00,
            public_key=config.public_key,
            dh_public_key=dh_public_key,
            private_key=config.private_key,
            dh_private_key=dh_private_key,
            outputs=[
                {
                    'to': to,
                    'value': 0
                }
            ]
        )

        mongo.db.miner_transactions.insert(transaction.transaction.to_dict())
        job = Process(target=TxnBroadcaster.txn_broadcast_job, args=(transaction.transaction,))
        job.start()

        return json.dumps({"success": True})
Example #7
0
def create_relationship():  # demo site
    if request.method == 'GET':
        bulletin_secret = request.args.get('bulletin_secret', '')
        username = request.args.get('username', '')
        to = request.args.get('to', '')
    else:
        bulletin_secret = request.json.get('bulletin_secret', '')
        username = request.json.get('username', '')
        to = request.json.get('to', '')

    if not bulletin_secret:
        return 'error: "bulletin_secret" missing', 400

    if not username:
        return 'error: "username" missing', 400

    if not to:
        return 'error: "to" missing', 400

    rid = TU.generate_rid(bulletin_secret)
    dup = Mongo.db.blocks.find({'transactions.rid': rid})
    if dup.count():
        for txn in dup:
            if txn['public_key'] == Config.public_key:
                return json.dumps({
                    "success": False,
                    "status": "Already added"
                })
    input_txns = BU.get_wallet_unspent_transactions(Config.address)

    miner_transactions = Mongo.db.miner_transactions.find()
    mtxn_ids = []
    for mtxn in miner_transactions:
        for mtxninput in mtxn['inputs']:
            mtxn_ids.append(mtxninput['id'])

    checked_out_txn_ids = Mongo.db.checked_out_txn_ids.find()
    for mtxn in checked_out_txn_ids:
        mtxn_ids.append(mtxn['id'])

    a = os.urandom(32)
    dh_public_key = scalarmult_base(a).encode('hex')
    dh_private_key = a.encode('hex')

    transaction = TransactionFactory(bulletin_secret=bulletin_secret,
                                     username=username,
                                     fee=0.01,
                                     public_key=Config.public_key,
                                     dh_public_key=dh_public_key,
                                     private_key=Config.private_key,
                                     dh_private_key=dh_private_key,
                                     outputs=[Output(to=to, value=1)])

    TU.save(transaction.transaction)

    Mongo.db.miner_transactions.insert(transaction.transaction.to_dict())
    job = Process(target=endpoints.TxnBroadcaster.txn_broadcast_job,
                  args=(transaction.transaction, ))
    job.start()

    my_bulletin_secret = Config.get_bulletin_secret()
    bulletin_secrets = sorted([str(my_bulletin_secret),
                               str(bulletin_secret)],
                              key=str.lower)
    rid = hashlib.sha256(str(bulletin_secrets[0]) +
                         str(bulletin_secrets[1])).digest().encode('hex')
    Mongo.site_db.friends.insert({
        'rid': rid,
        'relationship': {
            'bulletin_secret': bulletin_secret
        }
    })
    return json.dumps({"success": True})