Exemple #1
0
def create_transaction():
    """Add and broadcast the given transaction.
    Returns HTTP 400 if the transaction is considered invalid."""
    try:
        # retrieve transaction from request body
        jso = request.get_data(as_text=True)
        tx = Transaction.from_json(jso)

        # add transaction to local blockchain
        success = app.p2p.bc.add_transaction(tx)
        if success:
            # broadcast transaction to p2p network
            app.p2p.broadcast_tx(tx)

            return Response(tx.to_json(), status=HTTP_CREATED)
        else:
            logger.debug("failed to add tx")
            raise BadRequest()
    except BadRequest:
        raise
    except BaseException as e:
        logger.debug(e)
        logger.debug(traceback.format_exc())
        logger.debug(sys.exc_info())
        raise BadRequest()
Exemple #2
0
    def test_transaction_serialize(self):
        t1 = Transaction(0, 1, 2)
        t2 = Transaction(0, 1, 2)

        self.assertNotEqual(t1.get_hash(), t2.get_hash())

        t3 = Transaction.from_json(t1.to_json())
        self.assertEqual(t1.get_hash(), t3.get_hash())
        self.assertEqual(t1.src, t3.src)
        self.assertEqual(t1.dst, t3.dst)
        self.assertEqual(t1.qty, t3.qty)

        w = Wallet()
        w.create_keys()
        w.sign_transaction(t1)
        t4 = Transaction.from_json(t1.to_json())
        self.assertEqual(t1.get_hash(), t4.get_hash())
Exemple #3
0
def post_new_block():
    """Create and return a new block, ready for mining."""
    try:
        # retrieve transaction from request body
        jso = request.get_data(as_text=True)
        tx = Transaction.from_json(jso)

        # generate new block
        b = app.p2p.bc.new_block(tx)
        return Response(b.to_json(), status=HTTP_CREATED)
    except BaseException as e:
        logger.debug(e)
        logger.debug(traceback.format_exc())
        logger.debug(sys.exc_info())
        raise
Exemple #4
0
 def deserialize(self, data):
     nb = data[self.NB]
     objs = data[self.OBJECTS]
     if nb != len(objs):
         logger.error("bad number of objects")
         raise DeserializationError("bad number of objects")
     self.objects = []
     for ot in objs:
         otype = ot[0]
         obj = ot[1]
         if otype == MsgInv.TYPE_BLOCK:
             obj = Block.from_json(json.dumps(obj))
         elif otype == MsgInv.TYPE_TX:
             obj = Transaction.from_json(json.dumps(obj))
         self.objects.append((otype, obj))
Exemple #5
0
 def deserialize(self, data):
     tx = Transaction.from_json(json.dumps(data))
     self.tx = tx