initial dump of working faucet code.

This commit is contained in:
salt 2017-03-29 15:53:16 -07:00
parent 70df0c3006
commit ee4ab47287
28 changed files with 684 additions and 0 deletions

3
.gitignore vendored
View File

@ -87,3 +87,6 @@ ENV/
# Rope project settings
.ropeproject
*.sqlite3

80
README.md Normal file
View File

@ -0,0 +1,80 @@
zcash faucet
Set up instructions (WiP):
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install libpq-dev python-dev
sudo apt-get install postgresql postgresql-contrib
sudo apt-get install nginx
modify settings.py to configure settings.
export proper ENV variables:
export DJANGO_ENVIRONMENT=prod
export DJANGO_SECRET_KEY=xxx
export DJANGO_POSTGRESQL_PASSWORD=xxx
pip install -r requirements.txt
pip install -r requirements-prod.txt
sudo su - postgres
createdb django
createuser -P django
psql
GRANT ALL PRIVILEGES ON DATABASE django TO django;
python manage.py syncdb
gunicorn --workers=2 zfaucet.wsgi
sudo service nginx start
vim /etc/nginx/sites-available/zfaucet
server {
server_name faucet.yoursite.com;
access_log off;
location /static/ {
alias /home/ansible/static/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}
cd /etc/nginx/sites-enabled
sudo ln -s ../sites-available/zfaucet
sudo rm default
python manage.py collectstatic
(assuming user is ansible and has created a virtualenv called zfaucet)
crontab -e
*/5 * * * * /home/ansible/run_health.sh
*/5 * * * * /home/ansible/.virtualenvs/zfaucet/bin/python /home/ansible/zfaucet/manage.py healthcheck
run_health.sh:
#!/bin/bash
su ansible
source /home/ansible/set_prod.sh
cd /home/ansible/zfaucet
/home/ansible/.virtualenvs/zfaucet/bin/python ./manage.py healthcheck
run_sweep.sh
#!/bin/bash
su ansible
source /home/ansible/set_prod.sh
cd /home/ansible/zfaucet/pyzfaucet
/home/ansible/.virtualenvs/zfaucet/bin/python -m pyzcash.examples.sweep_all mfu8LbjAq15zmCDLCwUuay9cVc2FcGuY4d

0
faucet/__init__.py Normal file
View File

3
faucet/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

7
faucet/apps.py Normal file
View File

@ -0,0 +1,7 @@
from __future__ import unicode_literals
from django.apps import AppConfig
class FaucetConfig(AppConfig):
name = 'faucet'

View File

View File

View File

@ -0,0 +1,19 @@
from django.core.management.base import BaseCommand, CommandError
from faucet.models import HealthCheck
from pyzcash.rpc.ZDaemon import *
class Command(BaseCommand):
help = 'Updates health values shown on main page'
def handle(self, *args, **options):
zd = ZDaemon()
balance = zd.getTotalBalance()
height = zd.getNetworkHeight()
difficulty = zd.getNetworkDifficulty()
hc = HealthCheck()
hc.balance = balance
hc.height = height
hc.difficulty = difficulty
hc.save()

View File

@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-29 07:45
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Drip',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('timestamp', models.DateTimeField(auto_now_add=True, db_index=True)),
('address', models.CharField(db_index=True, max_length=255)),
('txid', models.CharField(db_index=True, max_length=255)),
('ip', models.GenericIPAddressField()),
],
options={
'ordering': ['-timestamp'],
},
),
migrations.CreateModel(
name='HealthCheck',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('timestamp', models.DateTimeField(auto_now_add=True, db_index=True)),
('height', models.IntegerField()),
('difficulty', models.FloatField()),
('balance', models.FloatField()),
],
options={
'ordering': ['-timestamp'],
},
),
]

View File

34
faucet/models.py Normal file
View File

@ -0,0 +1,34 @@
from __future__ import unicode_literals
from uuid import uuid4
from django.db.models import *
from django.conf import settings
#previous blockhash and nextblockhash?
class HealthCheck(Model):
id = UUIDField(primary_key=True, default=uuid4, editable=False)
timestamp = DateTimeField(auto_now_add=True, db_index=True)
height = IntegerField(null=False)
difficulty = FloatField()
balance = FloatField()
class Meta:
ordering = ['-timestamp']
class Drip(Model):
id = UUIDField(primary_key=True, default=uuid4, editable=False)
timestamp = DateTimeField(auto_now_add=True, db_index=True)
address = CharField(max_length=255, db_index=True)
txid = CharField(max_length=255, db_index=True)
ip = GenericIPAddressField()
class Meta:
ordering = ['-timestamp']

View File

@ -0,0 +1,85 @@
html {
position: relative;
min-height: 100%;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
background-color: #30332e;
color: #fffbfc;
}
.navbar {
background-color: #010400;
border-color: #62bbc1;
}
.navbar-nav>.active>a {
background-color: #62bbc1;
}
.btn-default, .input-group-addon {
background-color: #30332e;
color: #62bbc1;
border-color: #62bbc1;
}
.form-control {
background-color: #30332e;
color: #ec058e;
border-color: #62bbc1;
}
.form-control:focus {
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 8px rgba(255, 251, 252, 0.6);
}
.btn-default:hover, .btn-default:focus {
background-color: #010400 !important;
color: #62bbc1 !important;
border-color: #62bbc1 !important;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
/* Set the fixed height of the footer here */
height: 60px;
background-color: #010400;
}
body > .container {
padding: 60px 15px 0;
}
.container .text-muted {
margin: 20px 0;
}
.footer > .container {
padding-right: 15px;
padding-left: 15px;
}
code {
font-size: 80%;
}
.taddress {
color: #ec058e;
}
.zaddress {
color: #62bbc1;
}

View File

View File

@ -0,0 +1,34 @@
{% load static %}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>{% block title %}{% endblock %}</title>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
<link href="{% static "styles/bootstrap-custom.css" %}" rel="stylesheet">
{% block head-extra %}{% endblock %}
</head>
<body>
{% include 'faucet/header.html' %}
<div class="container">
{% block content %}
{% endblock %}
</div>
{% include 'faucet/footer.html' %}
{% block extend-js %}
{% endblock %}
</body>
</html>

View File

@ -0,0 +1,62 @@
{% extends "faucet/base.html" %}
{% block title %}ZCash Faucet {% endblock %}
{% block head-extra %} {% endblock %}
{% block extend-js %} {% endblock %}
{% block content %}
{% if flash %}
<div class="alert alert-info">
{{ message }}
</div>
{% endif %}
<div class="row">
<div class="col-xs-12">
<h1 style="text-align:center"> ZCash Faucet </h1>
<div style="text-align:center;font-size:1.5rem">Help fund the faucet: mfu8LbjAq15zmCDLCwUuay9cVc2FcGuY4d</div></br>
</div>
<div class="col-xs-4">
<h2>Stats:</h2>
<i class="fa fa-code-fork" aria-hidden="true"></i>&nbsp;Currently running: z9 (testnet) </br>
<i class="fa fa-database" aria-hidden="true"></i>&nbsp;Block Height: {{ height }} </br>
<i class="fa fa-cog" aria-hidden="true"></i>&nbsp;Difficulty: {{ difficulty | floatformat:4 }} </br>
<i class="fa fa-money" aria-hidden="true"></i>&nbsp;Payouts: {{ payouts }} </br>
<i class="fa fa-usd" aria-hidden="true"></i>&nbsp;Balance: {{ balance | floatformat:3}} ZEC </br>
</div>
<div class="col-xs-8">
<div class="panel panel-default">
<div class="panel-body" style="color:black">
<b>Welcome to the ZCash Faucet</b></br>
Enter your address and receive a small amount of ZEC to play with.<br>
Wallet is refilled with available mined ZEC every few hours. Donations appreciated!</br>
Currently only <span class="taddress">transparent addresses</span> are supported, but <span class="zaddress">protected address</span> support coming soon.</br>
Transactions may not send if you recently used the faucet, to maintain enough funds for everyone who visits.</br>
</div>
</div>
</div>
</div>
</br>
<form action="/" method="post">
{% csrf_token %}
<div class="input-group input-group-lg">
<span class="input-group-addon" id="sizing-addon1">Address:</span>
<input type="text" name="address" class="form-control" placeholder="mfu8LbjAq15zmCDLCwUuay9cVc2FcGuY4d" aria-describedby="sizing-addon1" maxlength="34">
</div>
<button class="btn btn-block btn-lg btn-default" action="submit" ><span class="glyphicon glyphicon-tint"></span> Tap Faucet</button>
</form>
</br>
{% endblock %}

View File

@ -0,0 +1,6 @@
<footer class="footer">
<div class="container">
<p class="text-muted" style="text-align:center;font-size:1rem">Copyright 2016 Zeropond</p>
</div>
</footer>

View File

@ -0,0 +1,13 @@
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Zeropond ZCash Faucet</a>
</div>
</div>
</nav>

3
faucet/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

16
faucet/urls.py Normal file
View File

@ -0,0 +1,16 @@
from django.conf.urls import url
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
#TODO: check if dev or prod and only use below in dev
urlpatterns += urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

56
faucet/views.py Normal file
View File

@ -0,0 +1,56 @@
from django.shortcuts import render
from django.http import HttpResponse
from django.db.models import Q
from django.utils import timezone
from datetime import *
from pyzcash.rpc.ZDaemon import *
from faucet.models import *
def index(request):
#Going to show the page no matter what, so pull these variables out.
hc = HealthCheck.objects.latest('timestamp')
payouts = Drip.objects.count()
#If it is a post, an address was submitted.
if request.method == 'POST':
#Check IP and payout address
ip = request.META.get('REMOTE_ADDR')
if ip == '127.0.0.1':
ip = request.META['HTTP_X_REAL_IP']
address = request.POST.get('address', '')
try:
last_payout = Drip.objects.filter(Q(ip=ip) | Q(address=address)).order_by('-timestamp')[0]
now = datetime.utcnow().replace(tzinfo=timezone.get_current_timezone())
timesince = (now - last_payout.timestamp).total_seconds()
if timesince < (60*60*12):
return render(request, 'faucet/faucet.html', {'balance':hc.balance,'difficulty':hc.difficulty,'height':hc.height, 'payouts':payouts, 'flash':True, 'message':"Sorry, you received a payout too recently. Come back later."})
except (Drip.DoesNotExist, IndexError) as e:
#Nothing in queryset, so we've never seen this ip and address before (individually)
pass
zd = ZDaemon()
tx = zd.sendTransparent(address, 0.1)
#Did the tx work?
if tx:
#Save Drip.
drip = Drip(address=address,txid=tx,ip=ip)
drip.save()
return render(request, 'faucet/faucet.html', {'balance':hc.balance,'difficulty':hc.difficulty,'height':hc.height, 'payouts':payouts, 'flash':True, 'message':"Sent! txid:" + tx})
else:
return render(request, 'faucet/faucet.html', {'balance':hc.balance,'difficulty':hc.difficulty,'height':hc.height, 'payouts':payouts, 'flash':True, 'message':"Issue sending transaction. Is your address correct?"})
return render(request, 'faucet/faucet.html', {'balance':hc.balance,'difficulty':hc.difficulty,'height':hc.height, 'payouts':payouts, 'flash':False, 'message':""})

22
manage.py Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zfaucet.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)

1
pyzcash Symbolic link
View File

@ -0,0 +1 @@
lib/pyzcash/pyzcash/

2
requirements-prod.txt Normal file
View File

@ -0,0 +1,2 @@
psycopg2
gunicorn

2
requirements.txt Normal file
View File

@ -0,0 +1,2 @@
django
requests

0
zfaucet/__init__.py Normal file
View File

155
zfaucet/settings.py Normal file
View File

@ -0,0 +1,155 @@
"""
Django settings for zfaucet project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
ENVIRONMENT = os.getenv('DJANGO_ENVIRONMENT', 'dev')
if ENVIRONMENT not in ['dev', 'stage', 'prod']:
raise Exception('Unknown settings environment "%s"' % ENVIRONMENT)
print 'settings environment is ' + ENVIRONMENT
# SECURITY WARNING: keep the secret key used in production secret!
if ENVIRONMENT == 'prod':
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
else:
SECRET_KEY = 'SECRETSECRET'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = ENVIRONMENT == 'dev'
if ENVIRONMENT == 'dev':
ALLOWED_HOSTS = []
else:
#Change to your site.
# prod and stage
ALLOWED_HOSTS = ['.yoursite.com',
'127.0.0.1']
# Application definition
INSTALLED_APPS = [
'faucet',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'zfaucet.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'zfaucet.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
if ENVIRONMENT == 'dev':
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'OPTIONS': {
'timeout': 10,
},
},
}
else:
# prod and stage
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': os.environ['DJANGO_POSTGRESQL_PASSWORD'],
'HOST': '127.0.0.1',
'PORT': '5432',
'CONN_MAX_AGE': 3600,
},
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = '/home/ansible/static/'

22
zfaucet/urls.py Normal file
View File

@ -0,0 +1,22 @@
"""zfaucet URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('faucet.urls')),
]

16
zfaucet/wsgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
WSGI config for zfaucet project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zfaucet.settings")
application = get_wsgi_application()