Giter Club home page Giter Club logo

django-bitcoin's Introduction

Please Note! Not maintained.

Currently django-bitcoin is not maintained. I don't recommend using it.

If you want to develop it, don't issue pull requests, but create your own fork. Thanks!

Introduction

django-bitcoin is a Django web framework application for building Bitcoin web apps.

Features

  • Simple Bitcoin wallet management
  • Bitcoin payment processing
  • Bitcoin market information

Installation

To install, just add the app to your settings.py INSTALLED_APPS like:

INSTALLED_APPS = [
    ...
    'django_bitcoin',
    ...
]

Also you have to run a local bitcoind instance, and specify connection string in settings:

BITCOIND_CONNECTION_STRING = "http://bitcoinuser:password@localhost:8332"

Usage

Tutorial

There is a small tutorial about how to use django-bitcoin to create your own instawallet.

Wallet websites, escrow services using the "Wallet"-model

You can use the Wallet class to do different bitcoin-moving applications. Typical example would be a marketplace-style site, where there are multiple sellers and buyer. Or job freelance site, where escrow is needed. Or even an exchange could be done with this abstraction (a little extra classes would be needed however).

Note that while you move bitcoins between Wallet-objects, only bitcoin transactions needed are incoming and outgoing transactions. Transactions between the system "Wallet"-objects don't generate "real" bitcoin transactions. Every transaction (except incoming transactions) is logged to WalletTransaction object to ease accounting.

This also means that outgoing bitcoin transactions are "mixed":

from django_bitcoin import Wallet, currency

class Profile(models.Model):
    wallet = ForeignKey(Wallet)
    outgoing_bitcoin_address = CharField()

class Escrow(models.Model):
    wallet = ForeignKey(Wallet)
    buyer_happy = BooleanField(default=False)

buyer=Profile.objects.create()
seller=Profile.objects.create()

purchase=Escrow.objects.create()

AMOUNT_USD="9.99"

m=currency.Money(AMOUNT_USD, "USD")
btc_amount=currency.exchange(m, "BTC")

print "Send "+str(btc_amount)+" BTC to address "+buyer.wallet.receiving_address()

sleep(5000) # wait for transaction

if p1.wallet.total_balance()>=btc_amount:
    p1.send_to_wallet(purchase, btc_amount)

    sleep(1000) # wait for product/service delivery

    if purchase.buyer_happy:
        purchase.wallet.send_to_wallet(seller.wallet)
        seller.wallet.send_to_address(seller.outgoing_bitcoin_address, seller.wallet.total_balance())
    else:
        print "WHY U NO HAPPY"
        #return bitcoins to buyer, 50/50 split or something

Templatetags

To display transaction history and simple wallet tagline in your views, use the following templatetags:

{% load currency_conversions %}
<!-- display balance tagline, estimate in USD and received/sent -->
{% wallet_tagline profile.bitcoin_wallet %}
<!-- display list of transactions as a table -->
{% wallet_history profile.bitcoin_wallet %}

Easy way to convert currencies from each other: btc2usd, usd2btc, eur2btc, btc2eur

Also currency2btc, btc2currency for any currencies on bitcoincharts.com:

{% load currency_conversions %}
Hi, for the pizza: send me {{bitcoin_amount}}BTC (about {{ bitcoin_amount|btc2usd }}USD).

Display QR code of the bitcoin payment using google charts API:

{% load currency_conversions %}
Pay the following payment with your android bitcoin wallet:
{% bitcoin_payment_qr wallet.receiving_address bitcoin_amount %}.

The same but display also description and an estimate in EUR:
{% bitcoin_payment_qr wallet.receiving_address bitcoin_amount "One beer" "EUR" %}.

Transaction notifications

To enable bitcoin transaction notifications, set the following flag in your settings.py:

BITCOIN_TRANSACTION_SIGNALING = True

After that, you need to setup a cron job to run each minute, something like the following:

* * * * * (cd $APP_PATH && python manage.py python manage.py CheckTransactions >> $APP_PATH/logs/email_sends.log 2>&1)

After that you can define your balance_changed and balance_changed_confirmed signals:

from django_bitcoin.models import balance_changed, balance_changed_confirmed
from django.dispatch import receiver


@receiver(balance_changed)
def balance_changed_handler(sender, **kwargs):
    pass
    # try:
    # print "balance changed", sender.id, kwargs["changed"], sender.total_balance()


@receiver(balance_changed_confirmed)
def balance_changed_confirmed_handler(sender, **kwargs):
    pass

Support and source code

Issue tracker at Github.com.

django-bitcoin's People

Contributors

dcramer avatar divyekapoor avatar elyezer avatar hylje avatar igor-shevchenko avatar jpic avatar kangasbros avatar kottenator avatar miohtama avatar spotty-banana avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-bitcoin's Issues

Django-bitcoin ignores "generate" transations

When wallet recieves "generate" transacion (transaction from mining pool with fresh coins) it ignored by django_bitcoin.tasks.query_transactions

Also utils.bitcoind.total_received doesn't work correctly, it also ignores generate transacions, because bitcoind API call getreceivedbyaddress ingnores them too.

PS
I wonder, is somebody using django-botcoin in production ? With django 1.6 ?

Bitcoincharts API error

I'm having problem getting data from this URL http://bitcoincharts.com/t/weighted_prices.json so I decided to have a look to Bitcoincharts web site and I realise that they have now a different URL to call their API http://api.bitcoincharts.com/v1/weighted_prices.json

Should we change the URL that we are using in the code right now?

Cheers.

TypeError: string indices must be integers on running 'CheckTransactions'

Steps to reproduce

Get the latest version from gh.

pip install -r django_bitcoin/requirements.txt

go to your application

run python manage.py CheckTransactions

it yields:

python manage.py CheckTransactions
starting overall1 0.000110864639282 2013-11-11 01:32:48.944677
starting round 0.00641298294067
TypeError: string indices must be integers

Am I doing something wrong? I have tried this with an application that had some running wallets as well as with an empty one, to no avail.

TransactionManagementError when trying Wallet.send_to_address

Hi
I'm trying to send bitcoins from wallet

>>> from django_bitcoin.models import Wallet
>>> w=Wallet.objects.get(id=6)
>>> w.send_to_address('n4a3fmSEqwoDLeWdjWLyiKr39j3xpRJAwL', 0.01)

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/limpbrains/dev/split/env/local/lib/python2.7/site-packages/django_bitcoin/models.py", line 804, in send_to_address
    return (bwt, None)
  File "/home/limpbrains/dev/split/env/local/lib/python2.7/site-packages/django/db/transaction.py", line 393, in __exit__
    self.exiting(exc_type, self.using)
  File "/home/limpbrains/dev/split/env/local/lib/python2.7/site-packages/django/db/transaction.py", line 436, in exiting
    leave_transaction_management(using=using)
  File "/home/limpbrains/dev/split/env/local/lib/python2.7/site-packages/django/db/transaction.py", line 78, in leave_transaction_management
    get_connection(using).leave_transaction_management()
  File "/home/limpbrains/dev/split/env/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 315, in leave_transaction_management
    "Transaction managed block ended with pending COMMIT/ROLLBACK")
TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK

I'm using Django 1.6.1
django-bitcoin from master
I've tried sqllite and mysql/innodb

Security issue on running installations (fixed 2012-09-09)

The BitcoinAddress -> Wallet m2m relation was causing some
bitcoinaddresses to belong multiple wallets. This basically allow
double spends for some edge cases. Should be problem only if
you are runnign very big installation.

You can check your installation from django shell this way:

BitcoinAddress.objects.all()
for ba in BitcoinAddress.objects.all():
if ba.wallet_set.count()>1:
print [(w.id, w.total_balance()) for w in ba.wallet_set.all()]

If it doesn't output anything, you are good. Otherwise you have to go
thourgh the cases manually.

The issue is fixed in current version on git, if you have south
migrations then it should be pretty painless to upgrade. (The m2m
relationship was changed to basic foreignkey relationship).

receiving_address() is generating more that one address

I'm creating a new wallet with the code below:

master_wallet, created = Wallet.objects.get_or_create(label="master_wallet")

And trying to get one bitcoinaddress to start receiving coins but instead the code below generate 5 address and only one is activated in the database (activate=1)

recv_address = master_wallet.receiving_address(fresh_addr=False)
print recv_address

Looking for forks

django-bitcoin is no longer mantained if anyone have some knowledge of a continuation fork, please mention it. Thanks.

receiving_address() raises DatabaseError with postgresql

I follow this tutorial:
http://opensourcehacker.com/2013/10/16/accepting-and-spending-bitcoins-in-a-django-application/

Everything is ok if database is sqlite (or mysql) but when I use postgresql (psycopg2) and I try to do master_wallet.receiving_address(fresh=False)
it returns

"DatabaseError: SELECT FOR UPDATE/SHARE cannot be applied to the nullable side of an outer join"

It is problem in new_bitcoin_address() (django_bitcoin/models.py) around line 118:

updated = BitcoinAddress.objects.select_for_update().filter(Q(id=bp.id) & Q(active=False) & Q(wallet__isnull=True) & \
Q(least_received__lte=0)).update(active=True)

Query it tries to run looks like this:

u'UPDATE "django_bitcoin_bitcoinaddress" SET "active" = %s WHERE "django_bitcoin_bitcoinaddress"."id" IN (SELECT U0."id" FROM "django_bitcoin_bitcoinaddress" U0 LEFT OUTER JOIN "django_bitcoin_wallet" U1 ON (U0."wallet_id" = U1."id") WHERE (U0."id" = %s  AND U0."active" = %s  AND U1."id" IS NULL AND U0."least_received" <= %s ) FOR UPDATE)'

But I'm not sure what to do with this, why query looks like this or what should it do. Maybe I am doing something wrong, maybe django ORM is translating it not the way it should, or the ORM query is not what you expected it to be.

If you know how to fix this, I would love to use django-bitcoin in my project.

raise exception

python manage.py CheckTransactions

starting overall1 3.60012054443e-05 2014-04-04 02:21:14.127606
starting round 0.000263214111328
Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/home/site/.virtualenvs/satoshi/lib/python2.7/site-packages/django/core/management/init.py", line 399, in execute_from_command_line
utility.execute()
File "/home/site/.virtualenvs/satoshi/lib/python2.7/site-packages/django/core/management/init.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/site/.virtualenvs/satoshi/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(_args, *_options.dict)
File "/home/site/.virtualenvs/satoshi/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(_args, *_options)
File "/home/site/.virtualenvs/satoshi/lib/python2.7/site-packages/django/core/management/base.py", line 415, in handle
return self.handle_noargs(**options)
File "/home/site/.virtualenvs/satoshi/lib/python2.7/site-packages/django_bitcoin/management/commands/CheckTransactions.py", line 45, in handle_noargs
dp.address.query_bitcoind(triggered_tx=t[u'txid'])
File "/home/site/.virtualenvs/satoshi/lib/python2.7/site-packages/django_bitcoin/models.py", line 272, in query_bitcoind
raise Exception("Deprecated")
Exception: Deprecated

Django 1.6.2

receiving_address() raises TransactionManagementError

When I am calling receiving_address method the following way, I am getting TransactionManagementError exception.

address = user.wallet.receiving_address()
print address

Does anybody have idea why is this happening or how can I debug it?

Traceback:

Traceback:
File "/Users/Elijen/Projects/Python/bitstore/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Elijen/Projects/Python/bitstore/bitstore/bitstore/views/invoice.py" in create
  12.         addr = invoice.wallet.receiving_address(fresh_addr=True)
File "/Users/Elijen/Projects/Python/bitstore/lib/python2.7/site-packages/django_bitcoin/models.py" in receiving_address
  363.             addr = new_bitcoin_address()
File "/Users/Elijen/Projects/Python/bitstore/lib/python2.7/site-packages/django_bitcoin/models.py" in new_bitcoin_address
  123.                     print "wallet transaction concurrency:", bp.address
File "/Users/Elijen/Projects/Python/bitstore/lib/python2.7/site-packages/django/db/transaction.py" in __exit__
  393.         self.exiting(exc_type, self.using)
File "/Users/Elijen/Projects/Python/bitstore/lib/python2.7/site-packages/django/db/transaction.py" in exiting
  436.         leave_transaction_management(using=using)
File "/Users/Elijen/Projects/Python/bitstore/lib/python2.7/site-packages/django/db/transaction.py" in leave_transaction_management
  78.     get_connection(using).leave_transaction_management()
File "/Users/Elijen/Projects/Python/bitstore/lib/python2.7/site-packages/django/db/backends/__init__.py" in leave_transaction_management
  315.                 "Transaction managed block ended with pending COMMIT/ROLLBACK")

Amount is reduced after a failed transaction

If you enter an invalid transaction (for example, sending bitcoins from a Wallet object to an invalid address), funds will get reduced from the Wallet anyways, even though no transaction was made.

for example :

wallet.send_to_address('invalid address', Decimal('0.1'))

will debit 0.1 BTC from the wallet, even though no bitcoin was sent.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.