예제 #1
0
def get_kG(e, P, s=None):
    '''Use EC operation: kG = sG +eP.
    If s (signature) is not provided, it is generated
    randomly and returned.
    e - hash value, 32 bytes binary
    P - verification pubkey
    s - 32 bytes binary'''
    if not s:
	s = os.urandom(32)
    sG = btc.fast_multiply(btc.G,btc.decode(s,256))
    eP = btc.fast_multiply(P,btc.decode(e,256))
    return (btc.fast_add(sG, eP), s)    
예제 #2
0
def trade_pow(branch, market, address, trade_nonce, difficulty=10000):
    nonce = 0
    target = 2 ** 254 / difficulty
    address = decode(address, 16)
    data = [branch, market, address, trade_nonce]
    encoder = lambda x: encode(x, 256, 32)
    decoder = lambda x: decode(x, 256)
    first_hash = sha3("".join(map(encoder, data))).digest()
    while True:
        h = decoder(sha3(first_hash + encoder(nonce)).digest())
        if h < target:
            return nonce
        nonce += 1
예제 #3
0
def read_int(ptr, payload, n, littleendian=True):
    data = payload[ptr[0] : ptr[0]+n]
    if littleendian:
        data = data[::-1]
    ret =  btc.decode(data, 256)
    ptr[0] += n
    return ret
    def __init__(self, state, code, sender, gas, endowment, language):
        if language not in _t.languages:
            _t.languages[language] = __import__(language)
        language = _t.languages[language]
        
        if os.path.exists(code):
            cache = code.replace('.se', '.sec')
            if os.path.exists(cache):
                cache_made = os.path.getmtime(cache)
                code_made = os.path.getmtime(code)
                if code_made > cache_made:
                    with open(cache, 'wb') as f:
                        print Fore.YELLOW + Style.BRIGHT + 'Stale cache, recompiling...' + Style.RESET_ALL
                        with timer():
                            evm = language.compile(code)
                            sig = language.mk_full_signature(code)
                            evm_len = encode(len(evm), 256, 2)
                            sig_len = encode(len(sig), 256, 2)
                            f.write(evm_len + evm + sig_len + sig)
                else:
                    print Fore.YELLOW + Style.BRIGHT + 'Loading from cache...' + Style.RESET_ALL
                    with open(cache, 'rb') as f:
                        with timer():
                            evm_len = decode(f.read(2), 256)
                            evm = f.read(evm_len)
                            sig_len = decode(f.read(2), 256)
                            sig = f.read(sig_len)
            else:
                with open(cache, 'wb') as f:
                    print Fore.YELLOW + Style.BRIGHT + 'Generating cache...' + Style.RESET_ALL
                    with timer():
                        evm = language.compile(code)
                        sig = language.mk_full_signature(code)
                        evm_len = encode(len(evm), 256, 2)
                        sig_len = encode(len(sig), 256, 2)
                        f.write(evm_len + evm + sig_len + sig)

            with suppressed_output():
                self.address = _t.encode_hex(state.evm(evm, sender, endowment, gas))
            self._translator = _t.abi.ContractTranslator(sig)
            assert len(state.block.get_code(self.address)), "Contract code empty"
            for funcname in self._translator.function_data:
                vars(self)[funcname] = make_dispatcher(state, self, funcname)
예제 #5
0
def sha3(*args):
    data = ""
    for i in args:
        if isinstance(i, (int, long)):
            data += encode(i, 256, 32)
        if isinstance(i, (list, tuple)):
            data += "".join(encode(j, 256, 32) for j in i)
        if isinstance(i, str):
            data += i
    result = decode(_sha3(data).digest(), 256)
    if result > 2 ** 255:
        result -= 2 ** 256
    return result
예제 #6
0
	
	#the set of all signature values (s(i,j))
	s = {}
	
	#for each OR loop, the index at which we start
	#the signature calculations, the one after the
	#the signing index (the one we have the privkey for)
	start_index = {}
	
	#the random value set as the k-value for the signing index
	k = [os.urandom(32) for i in range(len(vks))] 
	to_be_hashed = ''
	for i, loop in enumerate(vks):
	    e[i]=[None]*len(vks[loop])
	    s[i] = [None]*len(vks[loop])
	    kG = btc.fast_multiply(btc.G, btc.decode(k[i],256))
	    start_index[i] = (signing_indices[i]+1)%len(vks[loop])
	    
	    if start_index[i]==0:
		to_be_hashed += btc.encode_pubkey(kG,'bin_compressed')
		#in this case, there are no more vertices to process in the first stage
		continue
	    
	    e[i][start_index[i]] = borr_hash(M, kG, i, start_index[i])
	    for x in range(start_index[i]+1,len(vks[loop])):
		y,s[i][x-1] = get_kG(e[i][x-1], vks[i][x-1])
		e[i][x] = borr_hash(M,y,i,x)
	    
	    #kGend is the EC point corresponding to the k-value
	    #for the vertex before zero, which will be included in the hash for e0
	    kGend, s[i][len(vks[i])-1] = get_kG(e[i][len(vks[i])-1],vks[i][len(vks[i])-1])
예제 #7
0
 def base_encoder_tests(self):
   self.assertEqual(b.encode(1029,256),'\x04\x05')
   self.assertEqual(b.decode('DEADBEEF',16),3735928559)
   r = random.randrange(2**256)
   self.assertEqual(b.decode(b.changebase(b.encode(r,16),16,58),58),r)
   self.assertEqual(b.base58export(b.base58check(r,101,34)),r)
예제 #8
0
def _decode_sig(sig):
    return ord(sig[64]) + 27, bitcoin.decode(sig[0:32], 256), bitcoin.decode(sig[32:64], 256)
 def read_as_int(bytez):
     pos[0] += bytez
     return btc.decode(proof[pos[0] - bytez:pos[0]][::-1], 256)
예제 #10
0
 def read_as_int(bytez):
     pos[0] += bytez
     return bitcoin.decode(tx[pos[0]-bytez:pos[0]][::-1], 256)
예제 #11
0
 def read_as_int(bytez):
     pos[0] += bytez
     return bitcoin.decode(tx[pos[0] - bytez:pos[0]][::-1], 256)
예제 #12
0
def _decode_sig(sig):
    return ord(sig[64]) + 27, bitcoin.decode(sig[0:32], 256), bitcoin.decode(sig[32:64], 256)
예제 #13
0
    def post(self):

        hh = json.loads(self.request.body)
        
        """
        {the_pub: the_pub,
	 challenge: dd,
	 sig_v: sig.v,
	 sig_r: sig.r.toString('hex'),
	 sig_s: sig.s.toString('hex')
	}
        """
        
        the_pub = hh['the_pub']
        
        challenge = self.cccoin.DBL['CHALLENGES_DB'].get(the_pub, False)
        
        if challenge is False:
            print ('LOGIN_2: ERROR UNKNOWN CHALLENGE', challenge)
            self.write_json({"success":False,
	                     "username_success":False,
	                     "password_success":False,
	                     "got_username":"",
	                     "message":'Unknown or expired challenge during login.',
	                     })
            return
        
        print 'GOT=============='
        print json.dumps(hh, indent=4)
        print '================='
        
        ## Check challenge response, i.e. if password is good:
        
        password_success = btc.ecdsa_raw_verify(btc.sha256(challenge.encode('utf8')),
                                                (hh['sig']['sig_v'],
                                                 btc.decode(hh['sig']['sig_r'],16),
                                                 btc.decode(hh['sig']['sig_s'],16)),
                                                the_pub,
                                                )
        
        ## Check for immediate rejection of username request:
        
        username_success = True
        if hh['requested_username'] and (hh['requested_username'] in self.cccoin.DBL['TAKEN_USERNAMES_DB']):
            username_success = False
        
        if hh['requested_username'] and self.cccoin.tdb.lookup('username_to_user_id',
                                                               T_ANY_FORK,
                                                               hh['requested_username'],
                                                               default=False,
                                                               ):
            username_success = False

        ## Check if user already registered a username before:

        uu = self.cccoin.tdb.lookup('user_id_to_username',
                                    T_ANY_FORK,
                                    the_pub,
                                    default = False,
                                    )
        
        if uu:
            got_username = hh['requested_username']
            username_success = True
        else:
            got_username = hh['requested_username']
        
        self.cccoin.tdb.store('user_id_to_username',
                              'DIRECT',
                              the_pub,
                              hh['requested_username'],
                              start_block = self.cccoin.cw.c.eth_blockNumber(),
                              )

        xx = self.cccoin.tdb.lookup('user_id_to_username',
                                    T_ANY_FORK,
                                    the_pub,
                                    )
        assert xx[0] == hh['requested_username'], xx
        
        ## Check if previously unseen user ID:
        
        is_new = self.cccoin.DBL['SEEN_USERS_DB'].get(the_pub, False)
        
        ## Write out results:
        
        print ('LOGIN_2_RESULT','username_success:', username_success, 'password_success:', password_success)
        
        if (username_success and password_success):
            self.set_secure_cookie('auth', json.dumps({'created':int(time()),
                                                       'pub':the_pub,
                                                       'address':pub_to_address(the_pub),
                                                       }))
            self.cccoin.DBL['SEEN_USERS_DB'][the_pub] = True
        
        self.write_json({"success":password_success,
	                 "username_success":username_success,
	                 "password_success":password_success,
	                 "got_username":got_username,
	                 "message":'',
                         'is_new':is_new,
	                 })
예제 #14
0
        def proxyfunc(self, *args, **kw):
            
            self._current_user = {}
            
            #
            ## Get read authorization via encrypted cookies.
            ## Only for reading pending your own pending blind data:
            #

            if not needs_write: ## Don't bother checking for read if write is needed.
                
                cook = self.get_secure_cookie('auth')
                
                if cook:
                    h2 = json.loads(cook)
                    if (time() - h2['created'] <= cookie_expiration_time):
                        self._current_user = {'pub':h2['pub'],
                                              'has_read': True,
                                              'has_write': False,
                                              }
            
            #   
            ## Write authorization, must have valid monotonically increasing nonce:
            #
            
            try:
                hh = json.loads(self.request.body)
            except:
                hh = False
            
            if hh:
                print ('AUTH_CHECK_USER', hh['pub'][:32])

                hh['payload_decoded'] = json.loads(hh['payload'])
                
                if (hh['pub'] in self.cccoin.DBL['LATEST_NONCE']) and \
                   ('nonce' in hh['payload_decoded']) and \
                   (hh['payload_decoded']['nonce'] <= self.cccoin.DBL['LATEST_NONCE'][hh['pub']]
                   ):
                    print ('OUTDATED NONCE')
                    self.write_json({'error':'AUTH_OUTDATED_NONCE'})
                    return
                
                #LATEST_NONCE[user_key] = hh['payload_decoded']['nonce']
                
                is_success = btc.ecdsa_raw_verify(btc.sha256(hh['payload'].encode('utf8')),
                                                  (hh['sig']['sig_v'],
                                                   btc.decode(hh['sig']['sig_r'],16),
                                                   btc.decode(hh['sig']['sig_s'],16),
                                                  ),
                                                  hh['pub'],
                                                  )
                
                if is_success:
                    ## write auth overwrites read auth:
                    self._current_user = {'pub':hh['pub'],
                                          'has_read': True,
                                          'has_write': True,
                                          'write_data': hh,
                                          }
            
            if needs_read and not self._current_user.get('has_read'):
                print ('AUTH_FAILED_READ')
                self.write_json({'error':'AUTH_FAILED_READ'})
                #raise tornado.web.HTTPError(403)
                return
            
            if needs_write and not self._current_user.get('has_write'):
                print ('AUTH_FAILED_READ')
                self.write_json({'error':'AUTH_FAILED_READ'})
                #raise tornado.web.HTTPError(403)
                return
            
            ## TODO: per-public-key sponsorship rate throttling:
            
            self.add_header('X-RATE-USED','0')
            self.add_header('X-RATE-REMAINING','100')
            
            print ('AUTH_FINISHED', self._current_user)
            
            func(self, *args, **kw)
            
            return
예제 #15
0
def segwit_verify_tx_input(tx, i, script, sig, pub, amount):
    hashcode = decode(sig[-2:], 16)
    signing_tx = segwit_signature_form(tx, int(i), script, amount, hashcode=hashcode)
    hashed_signing_tx = hashlib.sha256(hashlib.sha256(binascii.unhexlify(signing_tx)).digest()).hexdigest()
    return ecdsa_raw_verify(hashed_signing_tx, der_decode_sig(sig), pub)