Skip to content

Commit

Permalink
Split Validation and PEP 8
Browse files Browse the repository at this point in the history
  • Loading branch information
super3 committed May 30, 2015
1 parent 3c51abc commit 3494e56
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 49 deletions.
46 changes: 18 additions & 28 deletions dataserv/Farmer.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import hashlib
from flask import Flask
from datetime import datetime
from sqlalchemy import DateTime
from flask.ext.sqlalchemy import SQLAlchemy
from dataserv.Validator import is_btc_address

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///dataserv.db'
db = SQLAlchemy(app)


def sha256(content):
"""Finds the sha256 hash of the content."""
content = content.encode('utf-8')
return hashlib.sha256(content).hexdigest()


class Farmer(db.Model):
id = db.Column(db.Integer, primary_key=True)
btc_addr = db.Column(db.String(35), unique=True)

last_seen = db.Column(DateTime, default=datetime.utcnow)
last_audit = db.Column(DateTime, default=datetime.utcnow)

iter_seed = db.Column(db.Integer)
response = db.Column(db.String(128))

def __init__(self, btc_addr, last_seen=None, last_audit=None):
"""
A farmer is a un-trusted client that provides some disk space
Expand All @@ -24,45 +36,23 @@ def __init__(self, btc_addr, last_seen=None, last_audit=None):
self.btc_addr = btc_addr
self.last_seen = last_seen
self.last_audit = last_audit
self.iter_seed = None
self.response = None

def __repr__(self):
return '<Farmer BTC Address: %r>' % self.btc_addr

def is_btc_address(self):
return is_btc_address(self.btc_addr)

def validate(self):
"""Make sure this farmer fits the rules for this node."""
# check if this is a valid BTC address or not
if not self.is_btc_address():
raise ValueError("Invalid BTC Address.")
elif self.exists():
raise ValueError("Address Already Is Registered.")

def is_btc_address(self):
"""
Does simple validation of a bitcoin-like address.
Source: http://bit.ly/17OhFP5
param : address : an ASCII or unicode string, of a bitcoin address.
returns : boolean, indicating that the address has a correct format.
"""

# The first character indicates the "version" of the address.
chars_ok_first = "123"
# alphanumeric characters without : l I O 0
chars_ok = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

# We do not check the high length limit of the address.
# Usually, it is 35, but nobody knows what could happen in the future.
if len(self.btc_addr) < 27:
return False
# Changed from the original code, we do want to check the upper bounds
elif len(self.btc_addr) > 35:
return False
elif self.btc_addr[0] not in chars_ok_first:
return False

# We use the function "all" by passing it an enumerator as parameter.
# It does a little optimization :
# if one of the character is not valid, the next ones are not tested.
return all((char in chars_ok for char in self.btc_addr[1:]))

def register(self):
"""Add the farmer to the database."""

Expand Down
36 changes: 36 additions & 0 deletions dataserv/Validator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
def is_sha256(content):
"""Make sure this is actually an valid SHA256 hash."""
digits58 = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
for i in range(len(content)):
if not content[i] in digits58:
return False
return len(content) == 64


def is_btc_address(content):
"""
Does simple validation of a bitcoin-like address.
Source: http://bit.ly/17OhFP5
param : address : an ASCII or unicode string, of a bitcoin address.
returns : boolean, indicating that the address has a correct format.
"""

# The first character indicates the "version" of the address.
chars_ok_first = "123"
# alphanumeric characters without : l I O 0
chars_ok = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

# We do not check the high length limit of the address.
# Usually, it is 35, but nobody knows what could happen in the future.
if len(content) < 27:
return False
# Changed from the original code, we do want to check the upper bounds
elif len(content) > 35:
return False
elif content[0] not in chars_ok_first:
return False

# We use the function "all" by passing it an enumerator as parameter.
# It does a little optimization :
# if one of the character is not valid, the next ones are not tested.
return all((char in chars_ok for char in content[1:]))
19 changes: 0 additions & 19 deletions tests/test_Farmer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,6 @@ def tearDown(self):
db.session.remove()
db.drop_all()

def test_valid_address(self):
addr1 = '191GVvAaTRxLmz3rW3nU5jAV1rF186VxQc'
addr2 = '191GVvAaTRxLmz3rW3nU5jAV1rF186VxQc9999ghjfghj99'
addr3 = 'not valid address'
addr4 = 'not valid &address'
addr5 = '791GVvAaTRxLmz3rW3nU5jAV1rF186VxQc'

farmer1 = Farmer(addr1)
farmer2 = Farmer(addr2)
farmer3 = Farmer(addr3)
farmer4 = Farmer(addr4)
farmer5 = Farmer(addr5)

self.assertTrue(farmer1.is_btc_address())
self.assertFalse(farmer2.is_btc_address())
self.assertFalse(farmer3.is_btc_address())
self.assertFalse(farmer4.is_btc_address())
self.assertFalse(farmer5.is_btc_address())

def test_address_error(self):
addr1 = 'not valid address'
farmer1 = Farmer(addr1)
Expand Down
24 changes: 24 additions & 0 deletions tests/test_Validator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import unittest
from dataserv.Validator import is_sha256, is_btc_address


class ValidatorTest(unittest.TestCase):
def test_valid_address(self):
addr1 = '191GVvAaTRxLmz3rW3nU5jAV1rF186VxQc'
addr2 = '191GVvAaTRxLmz3rW3nU5jAV1rF186VxQc9999ghjfghj99'
addr3 = 'not valid address'
addr4 = 'not valid &address'
addr5 = '791GVvAaTRxLmz3rW3nU5jAV1rF186VxQc'

self.assertTrue(is_btc_address(addr1))
self.assertFalse(is_btc_address(addr2))
self.assertFalse(is_btc_address(addr3))
self.assertFalse(is_btc_address(addr4))
self.assertFalse(is_btc_address(addr5))

def test_valid_sha256(self):
valid_hash = '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
self.assertTrue(is_sha256(valid_hash))

invalid_hash = 'notarealhash'
self.assertFalse(is_sha256(invalid_hash))
4 changes: 2 additions & 2 deletions tools/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import RandomIO

path = RandomIO.RandomIO('seed string').genfile(50)
with open(path,'rb') as f:
print(f.read())
with open(path, 'rb') as f:
print(f.read())

0 comments on commit 3494e56

Please sign in to comment.