Esempio n. 1
0
def add_hash_to_blockchain():
    # Reference hash: shasum -a 256 database/data.csv
    print("Hash: " + str(hash_sha256))

    # Put sha256 hash into bitcoin-tools
    private_key = BitcoinPrivateKey(hash_sha256)
    public_key = private_key.public_key()

    # Get address
    addr = public_key.address()
    print("Address: " + addr)

    # Get API keys
    with open(identifier_file, "r") as identifier_file_open:
        identifier = identifier_file_open.readline().rstrip('\n')

    with open(password_file, "r") as password_file_open:
        password = password_file_open.readline().rstrip('\n')

    # print("API Identifier: " + identifier)
    # print("API Password: "******"Payment TX: " + str(payment.tx_hash))
Esempio n. 2
0
def btc_release_from_escrow(escrow_id):
    escrow = Escrow.get(escrow_id)
    if not escrow:
        raise AssertionError("Escrow invalid.")
    bid = Bid.get(escrow.bid_id)
    if not bid or bid.is_win is None:
        raise AssertionError("Bid invalid.")
    '''
    if the bid is a winning one, we send (odds * value * (1 - commision))
    to the bidder
    if the bid is a losing one, we send (value * (1 - commission))
    to the seller
    '''

    escrow_wallet = Wallet(BaseConfig.BLOCKCHAIN_ESCROW_GUID,
                           BaseConfig.BLOCKCHAIN_ESCROW_PASSWORD,
                           BaseConfig.BLOCKCHAIN_SERVICE_URL)
    if not bid.is_win:
        to_send = btc_to_satoshi(bid.value * (1 - BaseConfig.COMISSION_RATE))
        destination = Wallet.get_user_wallet(bid.offer.user_id)
    else:
        to_send = btc_to_satoshi(bid.value * bid.offer.odds *
                                 (1 - BaseConfig.COMISSION_RATE))
        destination = bid.wallet_id
    payment = escrow_wallet.send(destination, to_send)
    if not payment or not payment.tx_hash:
        raise AssertionError("Payment failed.")
    else:
        escrow.active = False
        escrow.payout_date = datetime.datetime.now()
        db.session.commit()
Esempio n. 3
0
def send_btc_to_author():
    print "Attempting to send 10000 bits from reader to author for turning page"

    # Set Wallet object to readers wallet
    wallet = Wallet(reader_wallet_id, reader_wallet_password)

    # Send from wallet to new address (Receiving address (AUTHOR), Amount in satoshi, from address (READER))
    payment = wallet.send(author_receive_address, 10000, from_address=reader_send_from_address)

    # Adds 10,000 for some unknown reason in the error message when you try to send again with an unconfirmed transactions

    print "Sent 10000 bits from reader to author for turning page"
    print "Transaction Hash to search blockchain.info to verify transactions: " + str(payment.tx_hash)

    # Return the balance of reader's wallet
    balance = wallet.get_balance()

    print "Current total balance of readers wallet in Satoshi is  " + str(balance)

    # Convert from Satoshi's to bits
    converted_balance = convert_satoshi_to_bits(balance)

    print "Current total balance of readers wallet in Bits is  " + str(converted_balance)

    # return current wallet balance (includes unconfirmed) for front end
    return str(converted_balance)
Esempio n. 4
0
def process_out(CurrencyTitle):
        blockchain.util.TIMEOUT = 160
        user_system =   User.objects.get(id = 1)
        CurrencyInstance = Currency.objects.get(title = CurrencyTitle)
        if not check_btc_balance() or check_global_lock():
            raise LockBusyException("global check crypto currency has raised")

        Crypton = Wallet(CryptoSettings["BTC"]["host"],
                         CryptoSettings["BTC"]["rpc_user"],
                         CryptoSettings["BTC"]["rpc_pwd"])#sys.exit(0)
        getcontext().prec = settings.TRANS_PREC
        for obj in CryptoTransfers.objects.filter(status="processing", 
                                                  debit_credit ="out",
                                                  currency = CurrencyInstance):

                Amnt  =  int(obj.amnt*100000000)
                print "sending funds of %s to %s amount %i"  % (obj.user.username,  obj.account, Amnt)
                if 1 and not obj.verify(get_decrypted_user_pin(obj.user)):
                                print "SALT FAILED"
                                continue
                    else:
                                print "Salt ok"

                obj.status = "processed"
                obj.user_accomplished = user_system               
                obj.save()
                Account = obj.account
                Account = clean(Account)                     
                Txid = Crypton.send(Account, Amnt )
                print "txid %s" % (Txid.tx_hash)
                obj.order.status = "processed"
                obj.order.save()                       
                obj.crypto_txid = Txid.tx_hash
                obj.save()
                notify_email(obj.user, "withdraw_notify", obj)
Esempio n. 5
0
def betting_withdraw(request):
    if request.method == "POST":
        jsonRtn = {"success": True}

        try:
            bitcoin_address_session = BitcoinAddressSession.objects.get(pk=request.session["bas"])
            withdraw_address = request.POST.get('ig-address-text', None)
            withdraw_amount = request.POST.get('ig-amount-text', None)
            withdraw_lock = None

            if not withdraw_address or not withdraw_amount:
                raise ValueError("Please enter address and amount")
            if bitcoin_address_session.amount == 0:
                raise ValueError("Could not withdraw. Your current balance is 0 BTC.")

            withdraw_amount = float(withdraw_amount) * settings.SATOSHI_RATIO

            if withdraw_amount > bitcoin_address_session.amount:
                raise ValueError("You cannot withdraw more than your current balance.")

            if withdraw_amount < (0.0001 * settings.SATOSHI_RATIO):
                raise ValueError("Minimum withdrawal amount is 0.0001 BTC.")

            withdraw_lock = "{}{}".format(settings.REDIS_WITHDRAW_LOCK_PREFIX, bitcoin_address_session.id)

            while settings.REDIS_CLIENT.get(withdraw_lock):
                settings.REDIS_CLIENT.incrby(settings.REDIS_WITHDRAW_LOCK_COUNT, 1)

            settings.REDIS_CLIENT.set(withdraw_lock, 1)

            wallet = Wallet(settings.BITCOIN_PRIVATE_ADDRESS, None)
            wallet_withdraw = wallet.send(withdraw_address, withdraw_amount)

            withdraw_request = BitcoinWithdrawRequest()
            withdraw_request.bitcoin_address_session = bitcoin_address_session
            withdraw_request.amount = withdraw_amount
            withdraw_request.to_address = withdraw_address
            withdraw_request.transaction_hash = wallet_withdraw.tx_hash
            withdraw_request.save()

            bitcoin_address_session.amount -= withdraw_amount
            bitcoin_address_session.save()

            jsonRtn["message"] = wallet_withdraw.message
        except APIException, apie:
            LogUtils().info('bcjp.file', 'views', 'betting_withdraw', "APIException")
            jsonRtn["success"] = False
            jsonRtn["message"] = str(apie)
        except ValueError, ve:
            LogUtils().info('bcjp.file', 'views', 'betting_withdraw', "ValueError")
            jsonRtn["success"] = False
            jsonRtn["message"] = str(ve)
Esempio n. 6
0
def btc_send_to_escrow(wallet_id, bid_id, password):
    bid = Bid.get(bid_id)
    wallet = Wallet.get(wallet_id)
    if not bid or not wallet:
        raise AssertionError("Bid or wallet invalid.")
    else:
        true_value = bid.value * (1 - BaseConfig.COMISSION_RATE)
        commision = bid.value * BaseConfig.COMISSION_RATE
        escrow = Escrow(bid.offer_id, wallet_id, bid_id, commision, true_value)
        btc_wallet = Wallet(wallet.guid, password,
                            BaseConfig.BLOCKCHAIN_SERVICE_URL)
        payment = btc_wallet.send(BaseConfig.BLOCKCHAIN_ESCROW_ADDRESS,
                                  btc_to_satoshi(bid.value))
        if not payment or not payment.tx_hash:
            raise AssertionError("Payment failed.")
        escrow.incoming_hash = payment.tx_hash
        db.session.add(escrow)
        db.session.commit()
Esempio n. 7
0
class BTCProcessor:
    def __init__(self, customer):
        self.customer = customer  #models.Customers.objects.get(id=1) #customer
        if self.customer.btc_wallet() is None:
            self.wallet_generation()
        self.password = self.customer.btc_wallet().password
        self.wallet_id = self.customer.btc_wallet().id
        self.wallet = Wallet(self.wallet_id, self.password,
                             NODE_WALLET_SERVICES)

    def wallet_generation(self, label=None):
        label = label if label is not None else self.customer.user.get_fullname(
        ) + ' wallet'
        user_password = get_random_string(60)
        new_wallet = createwallet.create_wallet(user_password,
                                                API_CODE,
                                                NODE_WALLET_SERVICES,
                                                label=label)
        btc_wallet = BTC(id=new_wallet.identifier,
                         addr=new_wallet.address,
                         label=new_wallet.label,
                         customer=self.customer,
                         password=user_password)
        btc_wallet.save()
        return new_wallet.__dict__

    def wallet_info(self):
        wallet = self.wallet
        return wallet.__dict__

    def new_address(self, label='test_label'):
        newaddr = self.wallet.new_address(label)
        return newaddr

    def list_addresses(self):
        addresses = self.wallet.list_addresses()
        return addresses

    def get_balance(self):
        get_balance = float(self.wallet.get_balance() / 100000000)
        obj, created = models.Balance.objects.get_or_create(
            customer=self.customer, currency='BTC')
        obj.amount = get_balance
        obj.save()
        return get_balance

    def send_tx(self, target_addr, amount, from_address=None):
        amount = amount * 100000000
        payment = self.wallet.send(target_addr, amount, fee=500)  #min fee=220
        return payment.__dict__['tx_hash']

    def send_many_tx(self, recipients):
        # recipients = { '1NAF7GbdyRg3miHNrw2bGxrd63tfMEmJob' : 1428300,
        # 		'1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq' : 234522117 }
        payment_many = self.wallet.send_many(recipients)
        return payment_many.tx_id

    def get_address(self, addr, confirmations=2):
        addr = self.wallet.get_address(addr, confirmations=confirmations)
        return addr

    def archive_address(self, addr):
        archive_address = self.wallet.archive_address(addr)
        return archive_address

    def unarchive_address(self, addr):
        unarchive_address = self.wallet.unarchive_address(addr)
        return unarchive_address

    def push_tx(self, push_code):
        # push_code = '0100000001fd468e431cf5797b108e4d22724e1e055b3ecec59af4ef17b063afd36d3c5cf6010000008c4930460221009918eee8be186035be8ca573b7a4ef7bc672c59430785e5390cc375329a2099702210085b86387e3e15d68c847a1bdf786ed0fdbc87ab3b7c224f3c5490ac19ff4e756014104fe2cfcf0733e559cbf28d7b1489a673c0d7d6de8470d7ff3b272e7221afb051b777b5f879dd6a8908f459f950650319f0e83a5cf1d7c1dfadf6458f09a84ba80ffffffff01185d2033000000001976a9144be9a6a5f6fb75765145d9c54f1a4929e407d2ec88ac00000000'
        pushtxed = pushtx.pushtx(push_code)
        return pushtxed

    def get_price(self, currency, amount):
        btc_amount = exchangerates.to_btc(currency, amount)
        return btc_amount

    def statistics(self):
        stats = statistics.get()
        return stats

    def blockexplorer(self):
        block = blockexplorer.get_block(
            '000000000000000016f9a2c3e0f4c1245ff24856a79c34806969f5084f410680')
        tx = blockexplorer.get_tx(
            'd4af240386cdacab4ca666d178afc88280b620ae308ae8d2585e9ab8fc664a94')
        blocks = blockexplorer.get_block_height(2570)
        address = blockexplorer.get_address(
            '1HS9RLmKvJ7D1ZYgfPExJZQZA1DMU3DEVd')
        xpub = None  #blockexplorer.get_xpub('xpub6CmZamQcHw2TPtbGmJNEvRgfhLwitarvzFn3fBYEEkFTqztus7W7CNbf48Kxuj1bRRBmZPzQocB6qar9ay6buVkQk73ftKE1z4tt9cPHWRn')
        addresses = None  # blockexplorer.get_multi_address('1HS9RLmKvJ7D1ZYgfPExJZQZA1DMU3DEVd', 'xpub6CmZamQcHw2TPtbGmJNEvRgfhLwitarvzFn3fBYEEkFTqztus7W7CNbf48Kxuj1bRRBmZPzQocB6qar9ay6buVkQk73ftKE1z4tt9cPHWRn')
        outs = blockexplorer.get_unspent_outputs(
            '1HS9RLmKvJ7D1ZYgfPExJZQZA1DMU3DEVd')
        latest_block = blockexplorer.get_latest_block()
        txs = blockexplorer.get_unconfirmed_tx()
        blocks_by_name = None  #blockexplorer.get_blocks(pool_name = 'Discus Fish')

    def get_target_wallet_addr(self, customer=None, email=None):
        if customer is not None:
            return customer.btc_wallet().addr
        if email is not None:
            user = models.Users.objects.get(email=email)
            return user.customer().btc_wallet().addr
        return None
Esempio n. 8
0
def parser(origination_number,input,bank):

    #split the input 
    mod_input = input.split()
    verb = mod_input[0]
    
    if (verb == "my_number"):
        return origination_number

    #CREATE
    if(verb == "create"):
        # phone_number = origination_number
        identifier = mod_input[1]
        address = mod_input[2]
        pw = mod_input[3]
        #act = account(origination_number, identifier, address, pw,bank)
        bank.add_account(origination_number, identifier, address, pw)
        act = bank.get_account(origination_number)
        return "account created for {0}".format(act.account_id)

    
    caller = bank.get_account(origination_number)
    
    #Amount account
    if (verb == "balance"):
        #account = mod_input[1]
        return "balance {0}".format(caller.wallet.get_balance())
   
    #combine     
    if (verb == "combine"):
        identifier = mod_input[1]
        outgoing = mod_input[2]
        #password = mod_input[2]
        wallet = Wallet(identifier, 'Boondock2013')
        #failsafe: only import 10 satoshi max
        previous_balance = wallet.get_balance()
        previous_balance = min(previous_balance, 10)
        ra = caller.address.address
        rw = caller.wallet
        print ra
        print previous_balance
        #outgoing_addr = wallet.get_address(outgoing)
        print outgoing
        wallet.send(ra, previous_balance, outgoing)
        #current_balance = rw.get_balance()
        return "Successfully moved {0} satoshi from {1} to {2}: ".format(previous_balance, outgoing, ra )

    #INFO
    if (verb == "account_info"):
        #account = mod_input[1]
        return "Blockchain Wallet: {0}\n Address: {1}".format(caller.wallet.identifier, caller.address)

    #WITHDRAW
    if (verb == "withdraw"):
        accountID = mod_input[1]
        amount = mod_input[2]

        #check if amount is valid
        amount = get_satoshis(amount)
        if(amount < 0):
            return "Invalid quantity specified: amount must be a valid currency valued at greater than 1 satoshi"


        #check if the user has the account that they want to draw from 
        if (accountID in caller.waccounts ):
            
            #get the actual account from the bank 
            account = bank.get_account(accountID)

            if (hasFunds(amount, account)):
                withdraw(account, caller, amount)
                return "SUCCESS " + input

        else:
            return "Invalid/Unknown account"


    #DEPOSIT
    if (verb == "deposit"):
        accountID = mod_input[1]
        amount = mod_input[2]

        #check if amount is valid
        amount = get_satoshis(amount)
        if(amount < 0):
            return "Invalid quantity specified: amount must be a valid currency valued at greater than 1 satoshi"

        if (accountID in caller.daccounts):
            
            act = bank.get_account(accountID)
            deposit(act,caller,amount)
            return ("SUCCESS " + input)

        else:
            return "Invalid/Unknown account"

    #bxb
    if (verb == "bxb"):
        pn = mod_input[1]
        amount = mod_input[2]

        #check if amount is valid
        #amount = get_satoshis(amount)
        if(amount < 0):
            return "Invalid quantity specified: amount must be a valid currency valued at greater than 1 satoshi"

        # if (accountID in caller.daccounts):
            
        else: 
            act = bank.get_account(pn)
            transaction.deposit(act,caller,amount,15000)
            return ("SUCCESS " + input)

    else:
        return "Invalid/Unknown account"


    


    #ADD, this adds money to an account, gives a person the ability to access the account, what percent of the money they have access to     
    if (verb == "add"):
        #def account_to_person(self, account, person, permission, person_to_percent = 1.0):

        #this is the account you are sending the coins from
        act = origination_number

        #this is the phone number you are sending the coins to. 
        desitnation_phone = mod_input[1]

        #this is the permission that you want to give the person 
        permission = mod_input[2]

        #this is the amount of coins you are sending 
        amount = get_satoshis(mod_input[3])
        if(amount < 0):
            return "Invalid quantity specified: amount must be a valid currency valued at greater than 1 satoshi"

        #this is the percent they can withdraw ONLY if they are actually withdrawers 
        percent = mod_input[4]

        #this checks if the persons phone number is in the bank keys 
        if (not(desitnation_phone in bank.accounts.keys())):
            return "Person doesn't exist"

        actual_amount = (amount * percent)

        if (not(hasFunds(act,amount))):
            return "Not enough coins to make transfer"

        #transfers from an account to a person: 
            # 1. take the account we are transferring from!
            # 2. the desitnation_phone we are sending it to. 
            # 3. permission whether they can take or depsoit
            # 4. the amount we are actually transferring
            # 5. the percent to transfer

        #account_to_person(account,desitnation_phone,permission,actual_amount)
    else:
        return "Unknown verb!"