Beispiel #1
0
 def match(sig, pubs, msg):
     # for every pubkey in pubs
     for p in pubs:
         # verify is a simple verification method for signed messages
         if tools.verify(msg, sig, p):
             return {'bool': True, 'pub': p}
     return {'bool': False}
Beispiel #2
0
def spend_verify(tx, txs, DB): 
    tx_copy=copy.copy(tx)
    tx_copy.pop('signature')
    msg=tools.det_hash(tx_copy)
    if not tools.verify(msg, tx['signature'], tx['id']): return False
    if tx['amount']<custom.fee: return False
    if int(blockchain.db_get(tx['id'], DB)['amount'])<int(tx['amount']): 
        return False
    return True
 def sigs_match(sigs, pubs, msg):
     for sig in sigs:
         for pub in pubs:
             try:
                 if tools.verify(msg, sig, pub):
                     sigs.remove(sig)
                     pubs.remove(pub)
             except:
                 pass
     return len(sigs)==0
Beispiel #4
0
 def sigs_match(sigs, pubs, msg):
     for sig in sigs:
         for pub in pubs:
             try:
                 if tools.verify(msg, sig, pub):
                     sigs.remove(sig)
                     pubs.remove(pub)
             except:
                 pass
     return len(sigs) == 0
Beispiel #5
0
    62229893423380308135336276614282806444486645238749
    30358907296290491560440772390713810515859307960866
    70172427121883998797908792274921901699720888093776
    65727333001053367881220235421809751254540594752243
    52584907711670556013604839586446706324415722155397
    53697817977846174064955149290862569321978468622482
    83972241375657056057490261407972968652414535100474
    82166370484403199890008895243450658541227588666881
    16427171479924442928230863465674813919123162824586
    17866458359124566529476545682848912883142607690042
    24219022671055626321111109370544217506941658960408
    07198403850962455444362981230987879927244284909188
    84580156166097919133875499200524063689912560717606
    05886116467109405077541002256983155200055935729725
    71636269561882670428252483600823257530420752963450"""

numstr = "".join(numstr_readable.split())

# Answer:
# 40824

def solve():
    return xiter (xrange(len(numstr) - 4))                                     \
          .map   (lambda start: numstr[start:start + 5])                       \
          .map   (lambda substring: xiter(int(n) for n in substring))          \
          .map   (lambda numbers: numbers.product())                           \
    .max()
         
verify(solve(), 40824)

Beispiel #6
0
# Each new term in the Fibonacci sequence is generated by adding the previous two
# terms. By starting with 1 and 2, the first 10 terms will be:

# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

# By considering the terms in the Fibonacci sequence whose values do not exceed
# four million, find the sum of the even-valued terms.

# Answer:
# 4613732

from tools import fibonacci, divides, verify

def solve():
    return fibonacci()                                                         \
        .takewhile (lambda n: n <= 4000000)                                    \
        .filter    (lambda n: divides(2, n))                                   \
    .sum()
    
verify(solve(), 4613732)




Beispiel #7
0
 def sigs_match(sigs, pubs, msg):
     return all(tools.verify(msg, sig, pub) for sig in sigs for pub in pubs)
Beispiel #8
0
# 2520 is the smallest number that can be divided by each of the numbers from 1 to
# 10 without any remainder.

# What is the smallest positive number that is evenly divisible by all of the
# numbers from 1 to 20?

# Answer:
# 232792560

from tools import factors, verify

def solve():
    return factors(*range(1, 21), reduce_with = max).product()
    
verify(solve(), 232792560)
Beispiel #9
0
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we
# get 3, 5, 6 and 9. The sum of these multiples is 23.

# Find the sum of all the multiples of 3 or 5 below 1000.

# Answer:
# 233168

from xiter import xiter
from tools import verify, divides

def solve():
    return xiter(xrange(1, 1000))                                              \
        .filter (lambda n: divides(3, n) or divides(5, n))                     \
    .sum()
        
verify(solve(), 233168)
Beispiel #10
0
 def match(sig, pubs, msg):
     for p in pubs:
         if tools.verify(msg, sig, p):
             return {'bool':True, 'pub':p}
     return {'bool':False}
Beispiel #11
0
# The sum of the squares of the first ten natural numbers is,
#            12 + 22 + ... + 102 = 385
#            
# The square of the sum of the first ten natural numbers is,
#        (1 + 2 + ... + 10)2 = 552 = 3025
# 
# Hence the difference between the sum of the squares of the first ten natural
# numbers and the square of the sum is 3025  385 = 2640.

# Find the difference between the sum of the squares of the first one hundred
# natural numbers and the square of the sum.

# Answer:
# 25164150

from tools import verify, naturals

def square(x):
    return x ** 2

def solve():
    i1, i2 = naturals().slice(100).tee(2)
    
    return square(i2.sum()) - i1.map(square).sum()
    
verify(solve(), 25164150)
    
Beispiel #12
0
# The prime factors of 13195 are 5, 7, 13 and 29.

# What is the largest prime factor of the number 600851475143 ?

# Answer:
# 6857

from tools import factors, verify

def solve():
    return factors(600851475143).max()
    
verify(solve(), 6857)
Beispiel #13
0
# A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 99.

# Find the largest palindrome made from the product of two 3-digit numbers.

# Answer:
# 906609

from xiter import xiter
from tools import verify, is_palindrome

def products():
    for x in xrange(100, 1000):
        for y in xrange(100, x):
            yield x * y

def solve():
    return xiter(products())                                                   \
        .filter(is_palindrome)                                                 \
    .max()

verify(solve(), 906609)
Beispiel #14
0
 def verify_transaction(self, transaction, sender_pk):
     return verify(sender_pk, transaction.signature, transaction.hash_val)
Beispiel #15
0
    def block_check(block):
        def log_(txt):
            pass  # return tools.log(txt)

        def check_txs(txs):

            start = copy.deepcopy(txs)
            out = []
            start_copy = []

            # until starting copy of transactions are empty
            while start != start_copy:
                if start == []:
                    return False  # Block passes this test

                start_copy = copy.deepcopy(start)

                # if transaction is valid, then add the transaction to the out list
                if transactions.tx_check[start[-1]['type']](start[-1], out,
                                                            ['']):
                    out.append(start.pop())

                else:
                    return True  # Block is invalid

            return True  # Block is invalid

        # if block is not a dict, return false
        if not isinstance(block, dict): return False

        # block contains error
        if 'error' in block: return False

        # E_check function is responsible for checking the block(dict) if it has a length attribute which is int
        if not tools.E_check(block, 'length', [int]):
            log_('no length')
            return False

        # get the length of blockchain
        length = tools.db_get('length')

        # check length if it is integer, yeah yeah we have done that so what?
        if type(block['length']) != type(1):
            log_('wrong length type')
            return False

        # check length condition. It must be one bigger than our current blockchain length, or we would be missing something
        if int(block['length']) != int(length) + 1:
            log_('wrong longth')
            return False

        # checking if prevHash was actually the previous block's hash
        if length >= 0:
            if tools.det_hash(tools.db_get(length)) != block['prevHash']:
                log_('det hash error')
                return False

        # --------------------- START OF THE NEW PROOF-OF-WORK CHECK---------------------------------

        # Returns a dictionary with auth_sign and halfHash of block.
        # Authority must sign the block with its pubkey. This way, we are going to know which authority signed the block
        half_way = tools.make_half_way(block)
        if not half_way.get('auth_pubkey') in tools.db_get('authorities'):
            print 'no auth pubkey'
            return False

        if not tools.verify(half_way.get('halfHash'),
                            half_way.get('auth_sign'),
                            half_way.get('auth_pubkey')):
            print 'no verify'
            return False

        # --------------------- END OF THE NEW PROOF-OF-WORK CHECK-----------------------------------

        # recent_blockthings returns a map with get_val function and range starting from 100 early blocks to most recent block
        # then earliest is the median of sorted blocks
        earliest = median(recent_blockthings('times', custom.mmm))

        # time has to be present in block
        if 'time' not in block:
            log_('no time')
            return False

        # it is late to check this block
        if block['time'] > time.time() + 60 * 6:
            log_('too late')
            return False

        # block does not seem to be created at correct time
        if block['time'] < earliest:
            log_('too early')
            return False

        # check the transactions in the block
        # this function returns True on negative situation, because f**k the logic!
        # please someone fix this. I left it for now to show how a joken source this project is!
        if check_txs(block['txs']):
            log_('tx check')
            return False

        return True
Beispiel #16
0
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
# that the 6th prime is 13.

# What is the 10.001st prime number?

# Answer:
# 104743

from tools import primes, verify


def solve():
    return primes().drop(10000).next()


verify(solve(), 104743)
Beispiel #17
0
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

# Find the sum of all the primes below two million.

# Answer:
# 142913828922

from tools import verify, primes

def solve():
    return primes()                                                            \
        .takewhile(lambda prime: prime < 2000000)                              \
    .sum()
    
verify(solve(), 142913828922)

Beispiel #18
0
 def match(sig, pubs, msg):
     for p in pubs:
         if tools.verify(msg, sig, p):
             return {"bool": True, "pub": p}
     return {"bool": False}
Beispiel #19
0
    def block_check(block):

        def log_(txt):
            pass  # return tools.log(txt)

        def check_txs(txs):

            start = copy.deepcopy(txs)
            out = []
            start_copy = []

            # until starting copy of transactions are empty
            while start != start_copy:
                if start == []:
                    return False  # Block passes this test

                start_copy = copy.deepcopy(start)

                # if transaction is valid, then add the transaction to the out list
                if transactions.tx_check[start[-1]['type']](start[-1], out, ['']):
                    out.append(start.pop())

                else:
                    return True  # Block is invalid

            return True  # Block is invalid

        # if block is not a dict, return false
        if not isinstance(block, dict): return False

        # block contains error
        if 'error' in block: return False

        # E_check function is responsible for checking the block(dict) if it has a length attribute which is int
        if not tools.E_check(block, 'length', [int]):
            log_('no length')
            return False

        # get the length of blockchain
        length = tools.db_get('length')

        # check length if it is integer, yeah yeah we have done that so what?
        if type(block['length']) != type(1):
            log_('wrong length type')
            return False

        # check length condition. It must be one bigger than our current blockchain length, or we would be missing something
        if int(block['length']) != int(length) + 1:
            log_('wrong longth')
            return False

        # checking if prevHash was actually the previous block's hash
        if length >= 0:
            if tools.det_hash(tools.db_get(length)) != block['prevHash']:
                log_('det hash error')
                return False

        # --------------------- START OF THE NEW PROOF-OF-WORK CHECK---------------------------------

        # Returns a dictionary with auth_sign and halfHash of block.
        # Authority must sign the block with its pubkey. This way, we are going to know which authority signed the block
        half_way = tools.make_half_way(block)
        if not half_way.get('auth_pubkey') in tools.db_get('authorities'):
            print 'no auth pubkey'
            return False

        if not tools.verify(half_way.get('halfHash'), half_way.get('auth_sign'), half_way.get('auth_pubkey')):
            print 'no verify'
            return False

        # --------------------- END OF THE NEW PROOF-OF-WORK CHECK-----------------------------------

        # recent_blockthings returns a map with get_val function and range starting from 100 early blocks to most recent block
        # then earliest is the median of sorted blocks
        earliest = median(recent_blockthings('times', custom.mmm))

        # time has to be present in block
        if 'time' not in block:
            log_('no time')
            return False

        # it is late to check this block
        if block['time'] > time.time() + 60 * 6:
            log_('too late')
            return False

        # block does not seem to be created at correct time
        if block['time'] < earliest:
            log_('too early')
            return False

        # check the transactions in the block
        # this function returns True on negative situation, because f**k the logic!
        # please someone fix this. I left it for now to show how a joken source this project is!
        if check_txs(block['txs']):
            log_('tx check')
            return False

        return True
Beispiel #20
0
 def sigs_match(sigs, pubs, msg):
     return all(tools.verify(msg, sig, pub) for sig in sigs for pub in pubs)
Beispiel #21
0
 def match(sig, pubs, msg):
     for p in pubs:
         if tools.verify(msg, sig, p):
             return {'bool': True, 'pub': p}
     return {'bool': False}
Beispiel #22
0
# A Pythagorean triplet is a set of three natural numbers, a  b  c, for which,

# a**2 + b**2 = c**2
# For example, 32 + 42 = 9 + 16 = 25 = 52.

# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.

# Answer:
# 31875000

from xiter import xiter
from tools import verify

def triplets():
    for x in xrange(1, 999):
        for y in xrange(1, 1000 - x):
            yield (x, y, 1000 - x - y)

def solve():
    ntuple = xiter(triplets())                                                 \
        .filter(lambda (x, y, z): x**2 + y**2 == z**2)                         \
    .next()
    
    return reduce(lambda x, y: x * y, ntuple)
                
verify(solve(), 31875000)