Beispiel #1
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
Beispiel #2
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
Beispiel #3
0
 def dispatch_request(self):
     config = app.config['yada_config']
     mongo = app.config['yada_mongo']
     address = request.args.get('address')
     bulletin_secret = request.args.get('bulletin_secret').replace(' ', "+")
     rid = TU.generate_rid(config, bulletin_secret)
     unspent_transactions = [
         x for x in BU.get_wallet_unspent_transactions(
             config, mongo, address)
     ]
     regular_txns = []
     txns_for_fastgraph = []
     for txn in unspent_transactions:
         if 'signatures' in txn and txn['signatures']:
             fastgraph = FastGraph.from_dict(config, mongo, txn)
             origin_fasttrack = fastgraph.get_origin_relationship(rid)
             if origin_fasttrack:
                 txns_for_fastgraph.append(txn)
         else:
             if 'rid' in txn and txn[
                     'rid'] == rid and 'dh_public_key' in txn and txn[
                         'dh_public_key']:
                 txns_for_fastgraph.append(txn)
             else:
                 regular_txns.append(txn)
     wallet = {
         'balance': BU.get_wallet_balance(config, mongo, address),
         'unspent_transactions': regular_txns,
         'txns_for_fastgraph': txns_for_fastgraph
     }
     return json.dumps(wallet, indent=4)
Beispiel #4
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('/')
Beispiel #5
0
    def dispatch_request(self):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        address = request.args.get('address')
        bulletin_secret = request.args.get('bulletin_secret').replace(' ', "+")
        rid = TU.generate_rid(config, bulletin_secret)
        unspent_transactions = [x for x in BU().get_wallet_unspent_transactions(address)]
        spent_txn_ids = []
        for x in unspent_transactions:
            spent_txn_ids.extend([y['id'] for y in x['inputs']])

        unspent_fastgraph_transactions = [x for x in BU().get_wallet_unspent_fastgraph_transactions(address) if x['id'] not in spent_txn_ids]
        print('fastgraph uspent txn ids:')
        print([x['id'] for x in unspent_fastgraph_transactions])
        spent_fastgraph_ids = []
        for x in unspent_fastgraph_transactions:
            spent_fastgraph_ids.extend([y['id'] for y in x['inputs']])
        print('regular unspent txn ids:')
        print([x['id'] for x in unspent_transactions])
        regular_txns = []
        txns_for_fastgraph = []
        for txn in unspent_transactions:
            if 'signatures' in txn and txn['signatures']:
                fastgraph = FastGraph.from_dict(0, txn)
                origin_fasttrack = fastgraph.get_origin_relationship(rid)
                if origin_fasttrack:
                    txns_for_fastgraph.append(txn)
                else:
                    regular_txns.append(txn)
            else:
                if 'rid' in txn and txn['rid'] == rid and 'dh_public_key' in txn and txn['dh_public_key']:
                    txns_for_fastgraph.append(txn)
                else:
                    regular_txns.append(txn)
        #print(unspent_fastgraph_transactions)
        if unspent_fastgraph_transactions:
            txns_for_fastgraph.extend(unspent_fastgraph_transactions)
        print('final txn ids:')
        print([x['id'] for x in txns_for_fastgraph])
        wallet = {
            'balance': BU().get_wallet_balance(address),
            'unspent_transactions': regular_txns,
            'txns_for_fastgraph': txns_for_fastgraph
        }
        return json.dumps(wallet, indent=4)
Beispiel #6
0
    def dispatch_request(self):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        res = mongo.db.signed_transactions.find_one(
            {'hash': request.json.get('hash')})
        if res:
            return 'no', 400
        try:
            rid = TU.generate_rid(config, request.json.get('bulletin_secret'))
            my_entry_for_relationship = BU.get_transaction_by_rid(
                config,
                mongo,
                rid,
                config.wif,
                rid=True,
                my=True,
                public_key=config.public_key)
            their_entry_for_relationship = BU.get_transaction_by_rid(
                config,
                mongo,
                rid,
                rid=True,
                raw=True,
                theirs=True,
                public_key=config.public_key)
            verified = verify_signature(
                base64.b64decode(request.json.get('bulletin_secret')),
                my_entry_for_relationship['relationship']['their_username'],
                their_entry_for_relationship['public_key'].decode('hex'))
            if not verified:
                return 'no', 400
            verified = verify_signature(
                base64.b64decode(request.json.get('id')),
                request.json.get('hash'),
                their_entry_for_relationship['public_key'].decode('hex'))

            address = str(
                P2PKHBitcoinAddress.from_pubkey(
                    their_entry_for_relationship['public_key'].decode('hex')))
            found = False
            for x in BU.get_wallet_unspent_transactions(
                    config, mongo, address, [request.json.get('input')]):
                if request.json.get('input') == x['id']:
                    found = True

            if found:
                res = mongo.db.signed_transactions.find(
                    {'input': request.json.get('input')})
                if res.count():
                    return 'already signed this input', 400
            else:
                return 'no transactions with this input found', 400

            if verified:
                transaction_signature = TU.generate_signature_with_private_key(
                    config.private_key, request.json.get('hash'))
                signature = {
                    'signature': transaction_signature,
                    'hash': request.json.get('hash'),
                    'bulletin_secret': request.json.get('bulletin_secret'),
                    'input': request.json.get('input'),
                    'id': request.json.get('id')
                }
                mongo.db.signed_transactions.insert(signature)
                if '_id' in signature:
                    del signature['_id']
                return json.dumps(signature)
            else:
                return 'no', 400
        except Exception as e:
            return json.dumps({'status': 'error', 'msg': e}), 400
Beispiel #7
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})
Beispiel #8
0
    for key in keys:
        input_txns = BU.get_wallet_unspent_transactions(config, mongo, key.get('address'))
        for tx in input_txns:
            for i, out in enumerate(tx['outputs']):
                if out['to'] != key.get('address'):
                    continue
                inputs.append({
                    "hash": tx['hash'],
                    "id": tx['id'],
                    "index": i,
                    "value": out['value'],
                    "time": tx['time'],
                    "height": tx['height'],
                    "fee": tx['fee'],
                    "public_key": tx['public_key'],
                    "signature": TU.generate_signature(tx['id'], key['private_key']),
                    "address": key.get('address')
                })

    spendable = sum(i['value'] for i in inputs)
    print("collected {:,} spendable inputs totaling {:,}"
            .format(len(inputs), spendable))
    if spendable < float(args.value) + 0.01:
        print("insufficient funds")
        sys.exit()


    picked = []
    picked_sum = 0
    for inp in inputs:
        picked.append(inp)
Beispiel #9
0
    def dispatch_request(self):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        try:
            fg = FastGraph.from_dict(0, request.json.get('txn'), raw=True)
            fg.verify()
        except:
            raise
            return 'invalid transaction', 400
        res = mongo.db.signed_transactions.find_one({'hash': request.json.get('hash')})
        print(request.json)
        if res:
            return 'no', 400
        try:
            rid = TU.generate_rid(config, request.json.get('bulletin_secret'))
            my_entry_for_relationship = GU().get_transaction_by_rid(rid, config.wif, rid=True, my=True, public_key=config.public_key)
            their_entry_for_relationship = GU().get_transaction_by_rid(rid, rid=True, raw=True, theirs=True, public_key=config.public_key)
            verified = verify_signature(
                base64.b64decode(request.json.get('bulletin_secret')),
                my_entry_for_relationship['relationship']['their_username'].encode(),
                bytes.fromhex(their_entry_for_relationship['public_key'])
            )
            if not verified:
                return 'no', 400
            verified = verify_signature(
                base64.b64decode(request.json.get('id')),
                request.json.get('hash').encode('utf-8'),
                bytes.fromhex(their_entry_for_relationship['public_key'])
            )

            address = str(P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(their_entry_for_relationship['public_key'])))
            found = False
            for x in BU().get_wallet_unspent_transactions(address, [request.json.get('input')]):
                if request.json.get('input') == x['id']:
                    found = True
            
            if not found:
                for x in BU().get_wallet_unspent_fastgraph_transactions(address):
                    if request.json.get('input') == x['id']:
                        found = True

            if found:
                signature = mongo.db.signed_transactions.find_one({'input': request.json.get('input')})
                if signature:
                    already_spent = mongo.db.fastgraph_transactions.find_one({'txn.inputs.id': request.json.get('input')})
                    if already_spent:
                        return 'already spent!', 400
                    return 'already signed!', 400
            else:
                return 'no transactions with this input found', 400

            if verified:
                transaction_signature = TU.generate_signature_with_private_key(config.private_key, request.json.get('hash'))
                signature = {
                    'signature': transaction_signature,
                    'hash': request.json.get('hash'),
                    'bulletin_secret': request.json.get('bulletin_secret'),
                    'input': request.json.get('input'),
                    'id': request.json.get('id'),
                    'txn': request.json.get('txn')
                }
                mongo.db.signed_transactions.insert(signature)
                if '_id' in signature:
                    del signature['_id']
                return json.dumps(signature)
            else:
                return 'no', 400
        except Exception as e:
            raise
            return json.dumps({
                'status': 'error',
                'msg': e
            }), 400
Beispiel #10
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})
Beispiel #11
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})