示例#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
示例#2
0
def peers():
    if request.method == 'POST':
        try:
            socket.inet_aton(request.json['host'])
            host = request.json['host']
            port = int(request.json['port'])
            failed = request.json.get('failed')
            if failed:
                res = Mongo.db.peers.find({'host': host, 'port': port})
                if res.count():
                    Mongo.db.peers.update({
                        'host': host,
                        'port': port
                    }, {'$inc': {
                        'failed': 1
                    }})
            else:
                Mongo.db.peers.update({
                    'host': host,
                    'port': port
                }, {
                    'host': host,
                    'port': port,
                    'active': True,
                    'failed': 0
                },
                                      upsert=True)
            Peers.init_local()
            return 'ok'
        except:
            return 'failed to add peer, invalid host', 400
    else:
        return json.dumps(Peers.to_dict(), indent=4)
示例#3
0
 def txn_broadcast_job(cls, transaction):
     Peers.init()
     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.to_dict())
             socketIO.wait(seconds=1)
             chat_namespace.disconnect()
         except Exception as e:
             pass
示例#4
0
 def txn_broadcast_job(cls, transaction):
     config = app.config['yada_config']
     mongo = app.config['yada_mongo']
     Peers.init(config, mongo, config.network)
     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.to_dict())
             socketIO.wait(seconds=1)
             chat_namespace.disconnect()
         except Exception as e:
             pass
示例#5
0
文件: rpc.py 项目: EggPool/yadacoin
def peers():
    config = current_app.config['yada_config']
    mongo = current_app.config['yada_mongo']
    peers = Peers(config, mongo)
    if request.method == 'POST':
        try:
            socket.inet_aton(request.json['host'])
            host = request.json['host']
            port = int(request.json['port'])
            if request.json.get('failed'):
                return 'wrong consensus cleint version, please update', 400
            failed = request.json.get('failed_v1')
            if failed:
                res = mongo.db.peers.find({'host': host, 'port': port})
                if res.count():
                    mongo.db.peers.update({
                        'host': host,
                        'port': port
                    }, {'$inc': {
                        'failed': 1
                    }})
            else:
                mongo.db.peers.update({
                    'host': host,
                    'port': port
                }, {
                    'host': host,
                    'port': port,
                    'active': True,
                    'failed': 0
                },
                                      upsert=True)
            Peers.peers_json = peers.init_local()
            return 'ok'
        except:
            return 'failed to add peer, invalid host', 400
    else:
        if not hasattr(Peers, 'peers'):
            Peers.peers_json = peers.init_local()
        return Peers.peers_json
示例#6
0
文件: rpc.py 项目: icook/yadacoin
def peers():
    config = current_app.config['yada_config']
    mongo = current_app.config['yada_mongo']
    peers = Peers(config, mongo)
    if request.method == 'POST':
        try:
            socket.inet_aton(request.json['host'])
            host = request.json['host']
            port = int(request.json['port'])
            failed = request.json.get('failed')
            if failed:
                res = mongo.db.peers.find({'host': host, 'port': port})
                if res.count():
                    mongo.db.peers.update({
                        'host': host,
                        'port': port
                    }, {'$inc': {
                        'failed': 1
                    }})
            else:
                mongo.db.peers.update({
                    'host': host,
                    'port': port
                }, {
                    'host': host,
                    'port': port,
                    'active': True,
                    'failed': 0
                },
                                      upsert=True)
                current_app.config['yada_peers'] = peers.init_local()
            return 'ok'
        except:
            return 'failed to add peer, invalid host', 400
    else:
        if 'yada_peers' not in current_app.config:
            current_app.config['yada_peers'] = peers.init_local()
        return current_app.config['yada_peers']
示例#7
0
def node(nonces=None, config=None):
    Config.from_dict(json.loads(config))
    Peers.init()
    latest_block_index = Value('i', 0)
    my_peer = Config.peer_host + ":" + str(Config.peer_port)
    Config.max_duration = 300000
    Config.block_version = 1
    #p = Process(target=new_block_checker, args=(latest_block_index,))
    status = Array('c', 'asldkjf')
    #p.start()
    Mongo.init()
    # default run state will be to mine some blocks!
    block = BU.get_latest_block()
    if block:
        latest_block_index.value = block.get('index') + 1
    else:
        genesis_block = BlockFactory.get_genesis_block()
        genesis_block.save()
        Mongo.db.consensus.insert({
            'block': genesis_block.to_dict(),
            'peer': 'me',
            'id': genesis_block.signature,
            'index': 0
        })
        block = BU.get_latest_block()
        latest_block_index.value = block.get('index')

    dup_test = Mongo.db.consensus.find({
        'peer':
        'me',
        'index':
        latest_block_index.value,
        'block.version':
        BU.get_version_for_height(latest_block_index.value + 1)
    }).sort([('index', -1)])
    if dup_test.count():
        #print 'returning', latest_block_index.value + 1, BU.get_version_for_height(latest_block_index.value + 1)
        return

    transactions = Mongo.db.miner_transactions.find()
    transaction_objs = []
    unspent_indexed = {}
    for txn in transactions:
        try:
            transaction = Transaction.from_dict(txn)
            transaction.verify()
            #check double spend
            address = str(
                P2PKHBitcoinAddress.from_pubkey(
                    transaction.public_key.decode('hex')))
            if address in unspent_indexed:
                unspent_ids = unspent_indexed[address]
            else:
                needed_value = sum(
                    [float(x.value)
                     for x in transaction.outputs]) + float(transaction.fee)
                res = BU.get_wallet_unspent_transactions(
                    address, needed_value=needed_value)
                unspent_ids = [x['id'] for x in res]
                unspent_indexed[address] = unspent_ids
            failed1 = False
            failed2 = False
            used_ids_in_this_txn = []

            for x in transaction.inputs:
                if x.id not in unspent_ids:
                    failed1 = True
                if x.id in used_ids_in_this_txn:
                    failed2 = True
                used_ids_in_this_txn.append(x.id)
            if failed1:
                Mongo.db.miner_transactions.remove(
                    {'id': transaction.transaction_signature})
                print 'transaction removed: input presumably spent already, not in unspent outputs', transaction.transaction_signature
                Mongo.db.failed_transactions.insert({
                    'reason':
                    'input presumably spent already',
                    'txn':
                    transaction.to_dict()
                })
            elif failed2:
                Mongo.db.miner_transactions.remove(
                    {'id': transaction.transaction_signature})
                print 'transaction removed: using an input used by another transaction in this block', transaction.transaction_signature
                Mongo.db.failed_transactions.insert({
                    'reason':
                    'using an input used by another transaction in this block',
                    'txn':
                    transaction.to_dict()
                })
            else:
                transaction_objs.append(transaction)
        except MissingInputTransactionException as e:
            #print 'missing this input transaction, will try again later'
            pass
        except InvalidTransactionSignatureException as e:
            print 'InvalidTransactionSignatureException: transaction removed'
            Mongo.db.miner_transactions.remove(
                {'id': transaction.transaction_signature})
            Mongo.db.failed_transactions.insert({
                'reason': 'InvalidTransactionSignatureException',
                'txn': transaction.to_dict()
            })
        except InvalidTransactionException as e:
            print 'InvalidTransactionException: transaction removed'
            Mongo.db.miner_transactions.remove(
                {'id': transaction.transaction_signature})
            Mongo.db.failed_transactions.insert({
                'reason': 'InvalidTransactionException',
                'txn': transaction.to_dict()
            })
        except Exception as e:
            #print e
            #print 'rejected transaction', txn['id']
            pass
        except BaseException as e:
            #print e
            #print 'rejected transaction', txn['id']
            pass
    try:
        block = BlockFactory.mine(transaction_objs, Config.public_key,
                                  Config.private_key, Config.max_duration,
                                  output, latest_block_index, status, nonces)
    except Exception as e:
        raise
    if block:
        dup_test = Mongo.db.consensus.find_one({
            'peer':
            'me',
            'index':
            block.index,
            'block.version':
            BU.get_version_for_height(block.index)
        })
        if not dup_test:
            print '\r\nCandidate submitted for index:', block.index
            print '\r\nTransactions:'
            for x in block.transactions:
                print x.transaction_signature
            Mongo.db.consensus.insert({
                'peer': 'me',
                'index': block.index,
                'id': block.signature,
                'block': block.to_dict()
            })
            print '\r\nSent block to:'
            for peer in Peers.peers:
                try:
                    block_dict = block.to_dict()
                    block_dict['peer'] = my_peer
                    requests.post('http://{peer}/newblock'.format(
                        peer=peer.host + ":" + str(peer.port)),
                                  json=block_dict,
                                  timeout=3,
                                  headers={'Connection': 'close'})
                    print peer.host + ":" + str(peer.port)
                except Exception as e:
                    print e
                    try:
                        print 'reporting bad peer'
                        requests.post('https://yadacoin.io/peers',
                                      json={
                                          'host': peer.host,
                                          'port': str(peer.port),
                                          'failed': True
                                      },
                                      timeout=3,
                                      headers={'Connection': 'close'})
                    except:
                        print 'failed to report bad peer'
                        pass
示例#8
0
            with open(args.config, 'w+') as f:
                from utils import generate_config
                f.write(generate_config.generate())
        else:
            print '\'%s\' already exists! You must rename, move, or delete the existing file.' % args.config
        exit()

    if os.path.isfile(args.config):
        with open(args.config) as f:
            Config.from_dict(json.loads(f.read()))
    else:
        print 'no config file found at \'%s\'' % args.config
        exit()

    if args.mode == 'consensus':
        Peers.init()
        consensus = Consensus()
        while 1:
            consensus.sync()
            """
            p = Process(target=)
            p.start()
            p.join()
            """
            time.sleep(1)
    elif args.mode == 'send':
        send(args.to, float(args.value))
    elif args.mode == 'mine':
        print Config.to_json()

        def nonce_generator():
示例#9
0
文件: p2p.py 项目: icook/yadacoin
        Send.run(config, mongo, args.to, float(args.value))

    elif args.mode == 'mine':
        print config.to_json()
        print '\r\n\r\n\r\n//// YADA COIN MINER ////'
        print "Core count:", args.cores

        def get_mine_data():
            return json.loads(
                requests.get(
                    "http://{pool}/pool".format(pool=args.pool)).content)

        running_processes = []
        mp = MiningPool(config, mongo)
        while 1:
            Peers.init(config, mongo, args.network, my_peer=False)
            if not Peers.peers:
                time.sleep(1)
                continue
            if len(running_processes) >= int(args.cores):
                for i, proc in enumerate(running_processes):
                    if not proc.is_alive():
                        proc.terminate()
                        data = get_mine_data()
                        p = Process(target=mp.pool_mine,
                                    args=(args.pool, config.address,
                                          data['header'], data['target'],
                                          data['nonces'], data['special_min']))
                        p.start()
                        running_processes[i] = p
            else:
示例#10
0
    '/get-graph-friend-requests',
    view_func=endpoints.GraphFriendRequestsView.as_view('graphfriendrequests'),
    methods=['GET', 'POST'])
app.add_url_rule('/get-graph-friends',
                 view_func=endpoints.GraphFriendsView.as_view('graphfriends'),
                 methods=['GET', 'POST'])
app.add_url_rule('/get-graph-posts',
                 view_func=endpoints.GraphPostsView.as_view('graphposts'),
                 methods=['GET', 'POST'])
app.add_url_rule(
    '/get-graph-messages',
    view_func=endpoints.GraphMessagesView.as_view('graphmessages'),
    methods=['GET', 'POST'])
app.add_url_rule(
    '/get-graph-new-messages',
    view_func=endpoints.GraphNewMessagesView.as_view('graphnewmessages'),
    methods=['GET', 'POST'])
app.add_url_rule('/wallet', view_func=endpoints.WalletView.as_view('wallet'))
app.add_url_rule('/faucet', view_func=endpoints.FaucetView.as_view('faucet'))

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--conf', help='set your config file')
args = parser.parse_args()
conf = args.conf or 'config/config.json'
with open(conf) as f:
    Config.from_dict(json.loads(f.read()))

Peers.init_local()
Mongo.init()
push_service = FCMNotification(api_key=Config.fcm_key)